Scope FXML view models and dispose managed views

This commit is contained in:
2026-11-23 18:22:54 +01:00
parent 8aefe53ad1
commit e915ed392f
19 changed files with 774 additions and 205 deletions
+26
View File
@@ -433,6 +433,32 @@ Other load failures, all `IllegalArgumentException`:
These style classes are on the nodes: `table`, `column-header-row`, `table-scroll`, `table-header-scroll`, `column-header`, `column-cell`, `column-resize`, `column-opener`, `sort-mark`, `selected`, `column-popup`, `column-search`, `column-select-all`, `column-comparison-operator`, `column-comparison-value`, and `filtered` on an opener whose column has an active filter. These style classes are on the nodes: `table`, `column-header-row`, `table-scroll`, `table-header-scroll`, `column-header`, `column-cell`, `column-resize`, `column-opener`, `sort-mark`, `selected`, `column-popup`, `column-search`, `column-select-all`, `column-comparison-operator`, `column-comparison-value`, and `filtered` on an opener whose column has an active filter.
### Managed Views and Model contexts
Use the four-argument loader when a window, dialog or dockable owns a View:
```java
try (var models = new ViewModelContext();
var loaded = ViewLoader.load(fxml, model, application, models)) {
// Use loaded.getRoot() while this View is open.
}
```
In a GUI host, retain the handles until the real close event. A drag between docking groups
keeps the same View open. Close an individual `LoadedView` to remove its bindings, including
those on components and collection rows. Close its `ViewModelContext` once the owning
window or archive ends. The context closes remaining Views and releases the Model-to-ViewModel
registrations. Views of the same model instance in one context share a ViewModel.
The managed loader creates a fresh injected Controller or Component for each instance.
Dependencies still come from the application context. Controllers and Components can
implement `AutoCloseable` to release additional resources such as programmatic event handlers
or subscriptions to application services. The library also closes these resources if FXML or
binding setup throws. Use these handles on the FX application thread.
The three-argument loader keeps its existing shared cache and Controller behavior. Manage a
View with the four-argument loader if it needs deterministic cleanup.
### Column width ### Column width
A column with no `width` shares the table width with the other open columns. A `width` is the starting width, and not below the header text. The text minimum is the header text's layout width, rounded up, plus 8. The desk's Street column opens at 300 and Visited at 120. City names no width, so it receives what remains of the table's 496, which is 76. A column with no `width` shares the table width with the other open columns. A `width` is the starting width, and not below the header text. The text minimum is the header text's layout width, rounded up, plus 8. The desk's Street column opens at 300 and Visited at 120. City names no width, so it receives what remains of the table's 496, which is 76.
@@ -42,14 +42,14 @@ public class BindingList {
* @param context the container that creates a named Converter * @param context the container that creates a named Converter
*/ */
void apply(Map<String, Object> namespace, Object viewModel, Object controller, Parent root, void apply(Map<String, Object> namespace, Object viewModel, Object controller, Parent root,
ApplicationContext context) { ApplicationContext context, ViewLifetime lifetime) {
for (Object element : elements) { for (Object element : elements) {
if (element instanceof DirectBinding directBinding) { if (element instanceof DirectBinding directBinding) {
DirectBindingApplier.apply(namespace, viewModel, directBinding, context); DirectBindingApplier.apply(namespace, viewModel, directBinding, context, lifetime);
} else if (element instanceof ComputedBinding computedBinding) { } else if (element instanceof ComputedBinding computedBinding) {
ComputedBindingApplier.apply(namespace, viewModel, controller, root, computedBinding); ComputedBindingApplier.apply(namespace, viewModel, controller, root, computedBinding, lifetime);
} else if (element instanceof Repeat repeat) { } else if (element instanceof Repeat repeat) {
RepeatApplier.apply(namespace, viewModel, repeat, context); RepeatApplier.apply(namespace, viewModel, repeat, context, lifetime);
} else { } else {
throw new IllegalArgumentException("Not a binding element: " + element); throw new IllegalArgumentException("Not a binding element: " + element);
} }
@@ -14,6 +14,7 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import javafx.beans.property.Property; import javafx.beans.property.Property;
import javafx.fxml.FXMLLoader; import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent; import javafx.scene.Parent;
import javafx.util.Builder; import javafx.util.Builder;
import lombok.AccessLevel; import lombok.AccessLevel;
@@ -51,20 +52,20 @@ final class Components {
* @param context the container that creates Components * @param context the container that creates Components
* @return a builder for a Component, or {@code null} when the type is not a Component * @return a builder for a Component, or {@code null} when the type is not a Component
*/ */
static Builder<?> builder(Class<?> type, ApplicationContext context) { static Builder<?> builder(Class<?> type, ApplicationContext context, ViewLifetime owner) {
Object component; Object component;
try { try {
component = context.getComponent(type.asSubclass(Object.class)); component = owner.managed() ? context.createComponent(type) : context.getComponent(type);
} catch (IllegalArgumentException notAComponent) { } catch (IllegalArgumentException notAComponent) {
return null; return null;
} }
if (component.getClass() != type) { if (component.getClass() != type) {
return null; return null;
} }
if (!LoadSession.claimFirst(type)) { if (!owner.managed() && !LoadSession.claimFirst(type)) {
component = context.createComponent(type.asSubclass(Object.class)); component = context.createComponent(type.asSubclass(Object.class));
} }
return new ComponentBuilder(component, context); return new ComponentBuilder(component, context, owner.child());
} }
/** /**
@@ -77,6 +78,7 @@ final class Components {
private final Object component; private final Object component;
/** The context used to load its document. */ /** The context used to load its document. */
private final ApplicationContext context; private final ApplicationContext context;
private final ViewLifetime lifetime;
/** Values already resolved by the containing FXMLLoader. */ /** Values already resolved by the containing FXMLLoader. */
private final Map<String, Object> values = new LinkedHashMap<>(); private final Map<String, Object> values = new LinkedHashMap<>();
@@ -106,7 +108,7 @@ final class Components {
*/ */
@Override @Override
public Object build() { public Object build() {
Object result = load(component, context); Object result = load(component, context, lifetime);
if (!values.isEmpty()) { if (!values.isEmpty()) {
// A second fx:root load uses the public FXMLLoader API for bean setters, // A second fx:root load uses the public FXMLLoader API for bean setters,
// enum/numeric coercion and diagnostics, without depending on BeanAdapter // enum/numeric coercion and diagnostics, without depending on BeanAdapter
@@ -145,9 +147,9 @@ final class Components {
* @param context the container that creates the instance and its dependencies * @param context the container that creates the instance and its dependencies
* @return the loaded Component * @return the loaded Component
*/ */
static Object fresh(Class<?> type, ApplicationContext context) { static Object fresh(Class<?> type, ApplicationContext context, ViewLifetime lifetime) {
Object component = context.createComponent(type.asSubclass(Object.class)); Object component = context.createComponent(type.asSubclass(Object.class));
return load(component, context); return load(component, context, lifetime);
} }
/** /**
@@ -158,8 +160,18 @@ final class Components {
* @param component the Component * @param component the Component
* @param model the Model instance * @param model the Model instance
*/ */
static void setModel(Object component, Object model) { static void setModel(Object component, Object model, ViewLifetime lifetime) {
modelProperty(component).setValue(model); if (!lifetime.managed()) {
modelProperty(component).setValue(model);
return;
}
LoadSession session = LoadSession.nest();
try {
modelProperty(component).setValue(model);
session.checkFailure();
} finally {
LoadSession.unnest();
}
} }
/** /**
@@ -169,7 +181,8 @@ final class Components {
* @param context the container that creates nested Components * @param context the container that creates nested Components
* @return the loaded Component * @return the loaded Component
*/ */
private static Object load(Object component, ApplicationContext context) { private static Object load(Object component, ApplicationContext context, ViewLifetime lifetime) {
lifetime.ownController(component);
Class<?> type = component.getClass(); Class<?> type = component.getClass();
String document = type.getSimpleName() + ".fxml"; String document = type.getSimpleName() + ".fxml";
URL fxml = type.getResource(document); URL fxml = type.getResource(document);
@@ -179,11 +192,18 @@ final class Components {
LoadSession nested = LoadSession.nest(); LoadSession nested = LoadSession.nest();
try { try {
FXMLLoader loader = new FXMLLoader(fxml, ViewLoader.resources(context, fxml, type)); FXMLLoader loader = new FXMLLoader(fxml, ViewLoader.resources(context, fxml, type));
FxmlHandlers.observe(loader, lifetime);
loader.setRoot(component); loader.setRoot(component);
loader.setController(component); loader.setController(component);
loader.setBuilderFactory(nestedType -> builder(nestedType, context)); loader.setControllerFactory(nestedType -> ViewLoader.createController(context, nestedType, lifetime));
loader.setBuilderFactory(nestedType -> builder(nestedType, context, lifetime));
loader.load(); loader.load();
watchModel(component, List.copyOf(nested.bindingLists()), loader.getNamespace(), context); nested.checkFailure();
if (lifetime.managed() && component instanceof Node node) {
node.getProperties().put(Components.class, Boolean.TRUE);
lifetime.own(() -> node.getProperties().remove(Components.class));
}
watchModel(component, List.copyOf(nested.bindingLists()), loader.getNamespace(), context, lifetime);
return component; return component;
} catch (IOException failure) { } catch (IOException failure) {
throw new IllegalStateException("Could not load component " + fxml, failure); throw new IllegalStateException("Could not load component " + fxml, failure);
@@ -201,25 +221,37 @@ final class Components {
* @param context the container that creates a named Converter * @param context the container that creates a named Converter
*/ */
private static void watchModel(Object component, List<BindingList> lists, Map<String, Object> namespace, private static void watchModel(Object component, List<BindingList> lists, Map<String, Object> namespace,
ApplicationContext context) { ApplicationContext context, ViewLifetime lifetime) {
Property<Object> model = modelProperty(component); Property<Object> model = modelProperty(component);
boolean[] applied = {false}; boolean[] applied = {false};
model.addListener((observable, oldValue, newValue) -> { lifetime.listen(model, (observable, oldValue, newValue) -> {
if (newValue == null || applied[0]) { if (newValue == null || applied[0]) {
return; return;
} }
applied[0] = true; applied[0] = true;
Object viewModel = ViewModels.of(newValue, ViewModels.namedOn(component.getClass())); try {
if (component instanceof HasViewModel hasViewModel && viewModel instanceof ViewModel bound) { Object viewModel = ViewModels.of(lifetime.models(), newValue, ViewModels.namedOn(component.getClass()));
hasViewModel.setViewModel(bound); if (component instanceof HasViewModel hasViewModel && viewModel instanceof ViewModel bound) {
} hasViewModel.setViewModel(bound);
Parent root = (Parent) component; }
for (BindingList list : lists) { Parent root = (Parent) component;
list.apply(namespace, viewModel, component, root, context); for (BindingList list : lists) {
list.apply(namespace, viewModel, component, root, context, lifetime);
}
if (lifetime.managed()) Table.openAll(root, viewModel, context, lifetime);
} catch (RuntimeException | Error failure) {
lifetime.rollback(failure);
if (!lifetime.managed() || !LoadSession.recordFailure(failure)) {
throw failure;
}
} }
}); });
} }
static boolean ownsBindings(Node node) {
return node.hasProperties() && node.getProperties().containsKey(Components.class);
}
/** /**
* Returns the Component's {@code model} property. * Returns the Component's {@code model} property.
* *
@@ -41,7 +41,7 @@ final class ComputedBindingApplier {
Object viewModel, Object viewModel,
Object controller, Object controller,
Parent root, Parent root,
ComputedBinding binding) { ComputedBinding binding, ViewLifetime lifetime) {
Object control = namespace.get(binding.getControl()); Object control = namespace.get(binding.getControl());
if (control == null) { if (control == null) {
throw new IllegalArgumentException("No control \"" + binding.getControl() + "\""); throw new IllegalArgumentException("No control \"" + binding.getControl() + "\"");
@@ -49,9 +49,9 @@ final class ComputedBindingApplier {
Property<Object> target = controlProperty(control, binding.getProperty()); Property<Object> target = controlProperty(control, binding.getProperty());
Runnable refresh = refresh(controller, binding.getMethod(), target); Runnable refresh = refresh(controller, binding.getMethod(), target);
refresh.run(); refresh.run();
watchControls(root, target, refresh); watchNode(root, target, refresh, lifetime);
if (viewModel instanceof ViewModel model) { if (viewModel instanceof ViewModel model) {
model.addAttributeListener((observable, oldValue, newValue) -> refresh.run()); model.addAttributeListener(lifetime, (observable, oldValue, newValue) -> refresh.run());
} }
} }
@@ -80,17 +80,6 @@ final class ComputedBindingApplier {
}; };
} }
/**
* Watches JavaFX properties on controls under {@code root}, other than {@code target}.
*
* @param root the scene-graph root
* @param target the property the method writes, which is not watched
* @param refresh the refresh to run when a watched property changes
*/
private static void watchControls(Parent root, Property<?> target, Runnable refresh) {
watchNode(root, target, refresh);
}
/** /**
* Watches one control and walks its children. * Watches one control and walks its children.
* *
@@ -98,13 +87,13 @@ final class ComputedBindingApplier {
* @param target the property the method writes, which is not watched * @param target the property the method writes, which is not watched
* @param refresh the refresh to run when a watched property changes * @param refresh the refresh to run when a watched property changes
*/ */
private static void watchNode(Node node, Property<?> target, Runnable refresh) { private static void watchNode(Node node, Property<?> target, Runnable refresh, ViewLifetime lifetime) {
if (node instanceof Control control) { if (node instanceof Control control) {
watchProperties(control, target, refresh); watchProperties(control, target, refresh, lifetime);
} }
if (node instanceof Parent parent) { if (node instanceof Parent parent) {
for (Node child : parent.getChildrenUnmodifiable()) { for (Node child : parent.getChildrenUnmodifiable()) {
watchNode(child, target, refresh); watchNode(child, target, refresh, lifetime);
} }
} }
} }
@@ -117,7 +106,7 @@ final class ComputedBindingApplier {
* @param refresh the refresh to run when a watched property changes * @param refresh the refresh to run when a watched property changes
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static void watchProperties(Object bean, Property<?> target, Runnable refresh) { private static void watchProperties(Object bean, Property<?> target, Runnable refresh, ViewLifetime lifetime) {
ChangeListener<Object> listener = (observable, oldValue, newValue) -> refresh.run(); ChangeListener<Object> listener = (observable, oldValue, newValue) -> refresh.run();
for (Method method : bean.getClass().getMethods()) { for (Method method : bean.getClass().getMethods()) {
if (method.getParameterCount() != 0 || !method.getName().endsWith("Property")) { if (method.getParameterCount() != 0 || !method.getName().endsWith("Property")) {
@@ -128,7 +117,7 @@ final class ComputedBindingApplier {
} }
Object value = readProperty(bean, method); Object value = readProperty(bean, method);
if (value instanceof ObservableValue<?> observable && observable != target) { if (value instanceof ObservableValue<?> observable && observable != target) {
((ObservableValue<Object>) observable).addListener(listener); lifetime.listen((ObservableValue<Object>) observable, listener);
} }
} }
} }
@@ -30,12 +30,12 @@ final class DirectBindingApplier {
* @param context the container that creates a named Converter * @param context the container that creates a named Converter
*/ */
static void apply(Map<String, Object> namespace, Object viewModel, DirectBinding binding, static void apply(Map<String, Object> namespace, Object viewModel, DirectBinding binding,
ApplicationContext context) { ApplicationContext context, ViewLifetime lifetime) {
Object control = namespace.get(binding.getControl()); Object control = namespace.get(binding.getControl());
if (control == null) { if (control == null) {
throw new IllegalArgumentException("No control \"" + binding.getControl() + "\""); throw new IllegalArgumentException("No control \"" + binding.getControl() + "\"");
} }
selectComponentViewModel(control, viewModel, binding); selectComponentViewModel(control, viewModel, binding, lifetime);
Resolved resolved = resolve(viewModel, binding.getPath()); Resolved resolved = resolve(viewModel, binding.getPath());
if (resolved == null) { if (resolved == null) {
return; return;
@@ -44,30 +44,30 @@ final class DirectBindingApplier {
Property<?> attribute = resolved.attribute; Property<?> attribute = resolved.attribute;
if (resolved.complex) { if (resolved.complex) {
switch (binding.getDirection()) { switch (binding.getDirection()) {
case "both" -> alignBothComplex(controlProperty, attribute); case "both" -> alignBothComplex(controlProperty, attribute, lifetime);
case "view" -> alignTowardViewComplex(controlProperty, attribute); case "view" -> alignTowardViewComplex(controlProperty, attribute, lifetime);
case "model" -> alignTowardModelComplex(controlProperty, attribute); case "model" -> alignTowardModelComplex(controlProperty, attribute, lifetime);
default -> throw new IllegalArgumentException("Not a direction: " + binding.getDirection()); default -> throw new IllegalArgumentException("Not a direction: " + binding.getDirection());
} }
return; return;
} }
if (attribute.getValue() instanceof ObservableList<?> values) { if (attribute.getValue() instanceof ObservableList<?> values) {
assignList(controlProperty, values); assignList(controlProperty, values, lifetime);
return; return;
} }
String converterName = binding.getConverter(); String converterName = binding.getConverter();
if (converterName == null || converterName.isEmpty()) { if (converterName == null || converterName.isEmpty()) {
alignPlain(controlProperty, attribute, binding.getDirection()); alignPlain(controlProperty, attribute, binding.getDirection(), lifetime);
return; return;
} }
Converter converter = converter(context, converterName); Converter converter = converter(context, converterName);
switch (binding.getDirection()) { switch (binding.getDirection()) {
case "both" -> alignConverted( case "both" -> alignConverted(
controlProperty, attribute, converter, resolved.owner, resolved.name, true, true); controlProperty, attribute, converter, resolved.owner, resolved.name, true, true, lifetime);
case "view" -> alignConverted( case "view" -> alignConverted(
controlProperty, attribute, converter, resolved.owner, resolved.name, true, false); controlProperty, attribute, converter, resolved.owner, resolved.name, true, false, lifetime);
case "model" -> alignConverted( case "model" -> alignConverted(
controlProperty, attribute, converter, resolved.owner, resolved.name, false, true); controlProperty, attribute, converter, resolved.owner, resolved.name, false, true, lifetime);
default -> throw new IllegalArgumentException("Not a direction: " + binding.getDirection()); default -> throw new IllegalArgumentException("Not a direction: " + binding.getDirection());
} }
} }
@@ -79,11 +79,11 @@ final class DirectBindingApplier {
* @param attribute the Attribute * @param attribute the Attribute
* @param direction {@code view}, {@code model}, or {@code both} * @param direction {@code view}, {@code model}, or {@code both}
*/ */
private static void alignPlain(Property<?> controlProperty, Property<?> attribute, String direction) { private static void alignPlain(Property<?> controlProperty, Property<?> attribute, String direction, ViewLifetime lifetime) {
switch (direction) { switch (direction) {
case "both" -> alignBoth(controlProperty, attribute); case "both" -> alignBoth(controlProperty, attribute, lifetime);
case "view" -> alignTowardView(controlProperty, attribute); case "view" -> alignTowardView(controlProperty, attribute, lifetime);
case "model" -> alignTowardModel(controlProperty, attribute); case "model" -> alignTowardModel(controlProperty, attribute, lifetime);
default -> throw new IllegalArgumentException("Not a direction: " + direction); default -> throw new IllegalArgumentException("Not a direction: " + direction);
} }
} }
@@ -172,7 +172,7 @@ final class DirectBindingApplier {
* @param viewModel the ViewModel for this View * @param viewModel the ViewModel for this View
* @param binding the declaration * @param binding the declaration
*/ */
private static void selectComponentViewModel(Object control, Object viewModel, DirectBinding binding) { private static void selectComponentViewModel(Object control, Object viewModel, DirectBinding binding, ViewLifetime lifetime) {
if (!"model".equals(binding.getProperty())) { if (!"model".equals(binding.getProperty())) {
return; return;
} }
@@ -184,7 +184,7 @@ final class DirectBindingApplier {
if (instance == null) { if (instance == null) {
return; return;
} }
ViewModels.of(instance, requested); ViewModels.of(lifetime.models(), instance, requested);
} }
/** /**
@@ -280,20 +280,20 @@ final class DirectBindingApplier {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static void alignConverted(Property<?> controlProperty, Property<?> attribute, Converter converter, private static void alignConverted(Property<?> controlProperty, Property<?> attribute, Converter converter,
ViewModel owner, String sourceName, boolean towardView, boolean towardModel) { ViewModel owner, String sourceName, boolean towardView, boolean towardModel, ViewLifetime lifetime) {
Property<Object> control = (Property<Object>) controlProperty; Property<Object> control = (Property<Object>) controlProperty;
Property<Object> source = (Property<Object>) attribute; Property<Object> source = (Property<Object>) attribute;
Link link = new Link(); Link link = new Link();
pushControl(control, source, converter, owner, sourceName, link); pushControl(control, source, converter, owner, sourceName, link);
if (towardView) { if (towardView) {
source.addListener((observable, oldValue, newValue) -> { lifetime.listen(source, (observable, oldValue, newValue) -> {
if (!link.applying) { if (!link.applying) {
pushControl(control, source, converter, owner, sourceName, link); pushControl(control, source, converter, owner, sourceName, link);
} }
}); });
} }
if (towardModel) { if (towardModel) {
control.addListener((observable, oldValue, newValue) -> { lifetime.listen(control, (observable, oldValue, newValue) -> {
if (!link.applying) { if (!link.applying) {
pushAttribute(control, source, converter, owner, sourceName, link); pushAttribute(control, source, converter, owner, sourceName, link);
} }
@@ -412,21 +412,21 @@ final class DirectBindingApplier {
* @param attribute the complex Attribute * @param attribute the complex Attribute
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static void alignBothComplex(Property<?> controlProperty, Property<?> attribute) { private static void alignBothComplex(Property<?> controlProperty, Property<?> attribute, ViewLifetime lifetime) {
Property<Object> control = (Property<Object>) controlProperty; Property<Object> control = (Property<Object>) controlProperty;
Property<Object> source = (Property<Object>) attribute; Property<Object> source = (Property<Object>) attribute;
control.setValue(modelBehind(source.getValue())); control.setValue(modelBehind(source.getValue()));
source.addListener((observable, oldValue, newValue) -> { lifetime.listen(source, (observable, oldValue, newValue) -> {
Object model = modelBehind(newValue); Object model = modelBehind(newValue);
if (control.getValue() != model) { if (control.getValue() != model) {
control.setValue(model); control.setValue(model);
} }
}); });
control.addListener((observable, oldValue, newValue) -> { lifetime.listen(control, (observable, oldValue, newValue) -> {
if (modelBehind(source.getValue()) == newValue) { if (modelBehind(source.getValue()) == newValue) {
return; return;
} }
source.setValue(newValue == null ? null : ViewModels.of(newValue)); source.setValue(newValue == null ? null : ViewModels.of(lifetime.models(), newValue, null));
}); });
} }
@@ -437,11 +437,11 @@ final class DirectBindingApplier {
* @param attribute the complex Attribute * @param attribute the complex Attribute
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static void alignTowardViewComplex(Property<?> controlProperty, Property<?> attribute) { private static void alignTowardViewComplex(Property<?> controlProperty, Property<?> attribute, ViewLifetime lifetime) {
Property<Object> control = (Property<Object>) controlProperty; Property<Object> control = (Property<Object>) controlProperty;
Property<Object> source = (Property<Object>) attribute; Property<Object> source = (Property<Object>) attribute;
control.setValue(modelBehind(source.getValue())); control.setValue(modelBehind(source.getValue()));
source.addListener((observable, oldValue, newValue) -> control.setValue(modelBehind(newValue))); lifetime.listen(source, (observable, oldValue, newValue) -> control.setValue(modelBehind(newValue)));
} }
/** /**
@@ -451,15 +451,15 @@ final class DirectBindingApplier {
* @param attribute the complex Attribute * @param attribute the complex Attribute
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static void alignTowardModelComplex(Property<?> controlProperty, Property<?> attribute) { private static void alignTowardModelComplex(Property<?> controlProperty, Property<?> attribute, ViewLifetime lifetime) {
Property<Object> control = (Property<Object>) controlProperty; Property<Object> control = (Property<Object>) controlProperty;
Property<Object> source = (Property<Object>) attribute; Property<Object> source = (Property<Object>) attribute;
control.setValue(modelBehind(source.getValue())); control.setValue(modelBehind(source.getValue()));
control.addListener((observable, oldValue, newValue) -> { lifetime.listen(control, (observable, oldValue, newValue) -> {
if (modelBehind(source.getValue()) == newValue) { if (modelBehind(source.getValue()) == newValue) {
return; return;
} }
source.setValue(newValue == null ? null : ViewModels.of(newValue)); source.setValue(newValue == null ? null : ViewModels.of(lifetime.models(), newValue, null));
}); });
} }
@@ -483,8 +483,13 @@ final class DirectBindingApplier {
* @param values the list the ViewModel and the Model share * @param values the list the ViewModel and the Model share
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static void assignList(Property<?> controlProperty, ObservableList<?> values) { private static void assignList(Property<?> controlProperty, ObservableList<?> values, ViewLifetime lifetime) {
((Property<Object>) controlProperty).setValue(values); Property<Object> target = (Property<Object>) controlProperty;
Object previous = target.getValue();
target.setValue(values);
lifetime.own(() -> {
if (target.getValue() == values) target.setValue(previous);
});
} }
/** /**
@@ -494,8 +499,11 @@ final class DirectBindingApplier {
* @param attribute the Attribute * @param attribute the Attribute
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static void alignBoth(Property<?> controlProperty, Property<?> attribute) { private static void alignBoth(Property<?> controlProperty, Property<?> attribute, ViewLifetime lifetime) {
((Property<Object>) controlProperty).bindBidirectional((Property<Object>) attribute); Property<Object> control = (Property<Object>) controlProperty;
Property<Object> source = (Property<Object>) attribute;
control.bindBidirectional(source);
lifetime.own(() -> control.unbindBidirectional(source));
} }
/** /**
@@ -505,11 +513,11 @@ final class DirectBindingApplier {
* @param attribute the Attribute * @param attribute the Attribute
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static void alignTowardView(Property<?> controlProperty, Property<?> attribute) { private static void alignTowardView(Property<?> controlProperty, Property<?> attribute, ViewLifetime lifetime) {
Property<Object> control = (Property<Object>) controlProperty; Property<Object> control = (Property<Object>) controlProperty;
Property<Object> source = (Property<Object>) attribute; Property<Object> source = (Property<Object>) attribute;
control.setValue(source.getValue()); control.setValue(source.getValue());
source.addListener((observable, oldValue, newValue) -> control.setValue(newValue)); lifetime.listen(source, (observable, oldValue, newValue) -> control.setValue(newValue));
} }
/** /**
@@ -519,10 +527,10 @@ final class DirectBindingApplier {
* @param attribute the Attribute * @param attribute the Attribute
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static void alignTowardModel(Property<?> controlProperty, Property<?> attribute) { private static void alignTowardModel(Property<?> controlProperty, Property<?> attribute, ViewLifetime lifetime) {
Property<Object> control = (Property<Object>) controlProperty; Property<Object> control = (Property<Object>) controlProperty;
Property<Object> target = (Property<Object>) attribute; Property<Object> target = (Property<Object>) attribute;
control.setValue(target.getValue()); control.setValue(target.getValue());
control.addListener((observable, oldValue, newValue) -> target.setValue(newValue)); lifetime.listen(control, (observable, oldValue, newValue) -> target.setValue(newValue));
} }
} }
@@ -0,0 +1,66 @@
package de.neitzel.fx.view;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import javafx.beans.property.Property;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.fxml.LoadListener;
/** Removes handler properties assigned by the managed FXML document when its View closes. */
final class FxmlHandlers implements LoadListener {
private final ViewLifetime lifetime;
private final Deque<List<String>> handlers = new ArrayDeque<>();
private FxmlHandlers(ViewLifetime lifetime) {
this.lifetime = lifetime;
}
static void observe(FXMLLoader loader, ViewLifetime lifetime) {
if (lifetime.managed()) loader.setLoadListener(new FxmlHandlers(lifetime));
}
@Override
public void readEventHandlerAttribute(String name, String value) {
handlers.getLast().add(name);
}
@Override
public void endElement(Object value) {
List<String> attributes = handlers.removeLast();
if (value == null) return;
for (String attribute : attributes) {
Property<?> property = NamedProperties.get(value, attribute);
if (property != null && property.getValue() instanceof EventHandler<?> handler) {
lifetime.own(() -> {
if (property.getValue() == handler) property.setValue(null);
});
}
}
}
private void beginElement() {
handlers.addLast(new ArrayList<>());
}
@Override public void beginInstanceDeclarationElement(Class<?> type) { beginElement(); }
@Override public void beginUnknownTypeElement(String name) { beginElement(); }
@Override public void beginIncludeElement() { beginElement(); }
@Override public void beginReferenceElement() { beginElement(); }
@Override public void beginCopyElement() { beginElement(); }
@Override public void beginRootElement() { beginElement(); }
@Override public void beginPropertyElement(String name, Class<?> sourceType) { beginElement(); }
@Override public void beginUnknownStaticPropertyElement(String name) { beginElement(); }
@Override public void beginScriptElement() { beginElement(); }
@Override public void beginDefineElement() { beginElement(); }
@Override public void readImportProcessingInstruction(String target) { }
@Override public void readLanguageProcessingInstruction(String language) { }
@Override public void readComment(String comment) { }
@Override public void readInternalAttribute(String name, String value) { }
@Override public void readPropertyAttribute(String name, Class<?> sourceType, String value) { }
@Override public void readUnknownStaticPropertyAttribute(String name, String value) { }
}
@@ -18,7 +18,7 @@ import java.util.Set;
final class LoadSession { final class LoadSession {
/** /**
* The sessions open on this thread. The last one is the outermost load. * The sessions open on this thread, with the current session first.
*/ */
private static final ThreadLocal<Deque<LoadSession>> STACK = new ThreadLocal<>(); private static final ThreadLocal<Deque<LoadSession>> STACK = new ThreadLocal<>();
@@ -32,25 +32,33 @@ final class LoadSession {
*/ */
private final Set<Class<?>> built = new HashSet<>(); private final Set<Class<?>> built = new HashSet<>();
private Throwable bindingFailure;
// JavaFX reports exceptions from a property listener to the thread's uncaught handler.
// Keep a synchronous Component failure with the load that triggered that property change.
static boolean recordFailure(Throwable failure) {
Deque<LoadSession> stack = STACK.get();
if (stack == null) return false;
LoadSession session = stack.peek();
if (session.bindingFailure == null) {
session.bindingFailure = failure;
} else if (session.bindingFailure != failure) {
session.bindingFailure.addSuppressed(failure);
}
return true;
}
void checkFailure() {
if (bindingFailure instanceof RuntimeException runtime) throw runtime;
if (bindingFailure instanceof Error error) throw error;
}
/** /**
* Prevents instantiation from outside this class. * Prevents instantiation from outside this class.
*/ */
private LoadSession() { private LoadSession() {
} }
/**
* Starts a session on this thread.
*
* @return the open session
*/
static LoadSession open() {
Deque<LoadSession> stack = new ArrayDeque<>();
LoadSession session = new LoadSession();
stack.push(session);
STACK.set(stack);
return session;
}
/** /**
* Opens a nested session for a Component document. * Opens a nested session for a Component document.
* <p> * <p>
@@ -84,13 +92,6 @@ final class LoadSession {
} }
} }
/**
* Drops the session for this thread.
*/
static void close() {
STACK.remove();
}
/** /**
* Registers a binding list created while a session is open. * Registers a binding list created while a session is open.
* *
@@ -10,7 +10,7 @@ import lombok.RequiredArgsConstructor;
* The scene-graph root and ViewModel produced by loading a View for a Model instance. * The scene-graph root and ViewModel produced by loading a View for a Model instance.
*/ */
@RequiredArgsConstructor(access = AccessLevel.PACKAGE) @RequiredArgsConstructor(access = AccessLevel.PACKAGE)
public final class LoadedView { public final class LoadedView implements AutoCloseable {
/** /**
* The scene-graph root of the loaded View. * The scene-graph root of the loaded View.
@@ -23,6 +23,17 @@ public final class LoadedView {
*/ */
private final Object viewModel; private final Object viewModel;
private final ViewLifetime lifetime;
/**
* Releases the resources owned by a managed View. Calling this twice is harmless.
* Use the ViewLoader overload taking a ViewModelContext to opt into managed lifetimes.
*/
@Override
public void close() {
lifetime.close();
}
/** /**
* Returns the ViewModel the View is bound to. * Returns the ViewModel the View is bound to.
* <p> * <p>
@@ -2,11 +2,12 @@ package de.neitzel.fx.view;
import de.neitzel.injection.ApplicationContext; import de.neitzel.injection.ApplicationContext;
import javafx.beans.property.Property; import javafx.beans.property.Property;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
import javafx.scene.Node; import javafx.scene.Node;
import javafx.scene.layout.Pane; import javafx.scene.layout.Pane;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
@@ -34,7 +35,7 @@ final class RepeatApplier {
* @param context the container that creates each Component * @param context the container that creates each Component
*/ */
static void apply(Map<String, Object> namespace, Object viewModel, Repeat repeat, static void apply(Map<String, Object> namespace, Object viewModel, Repeat repeat,
ApplicationContext context) { ApplicationContext context, ViewLifetime lifetime) {
Object named = namespace.get(repeat.getPane()); Object named = namespace.get(repeat.getPane());
if (!(named instanceof Pane pane)) { if (!(named instanceof Pane pane)) {
throw new IllegalArgumentException("No pane \"" + repeat.getPane() + "\""); throw new IllegalArgumentException("No pane \"" + repeat.getPane() + "\"");
@@ -44,10 +45,15 @@ final class RepeatApplier {
throw new IllegalArgumentException("No collection \"" + repeat.getCollection() + "\""); throw new IllegalArgumentException("No collection \"" + repeat.getCollection() + "\"");
} }
Class<?> type = componentType(repeat.getComponent()); Class<?> type = componentType(repeat.getComponent());
int offset = pane.getChildren().size();
List<RepeatedChild> children = new ArrayList<>();
lifetime.own(() -> pane.getChildren().removeAll(children.stream().map(RepeatedChild::node).toList()));
for (Object element : values) { for (Object element : values) {
pane.getChildren().add(child(type, context, element)); RepeatedChild child = child(type, context, element, lifetime);
children.add(child);
pane.getChildren().add(child.node());
} }
listen(pane, type, context, values); listen(pane, type, context, values, lifetime, offset, children);
} }
/** /**
@@ -76,20 +82,24 @@ final class RepeatApplier {
* @param values the collection * @param values the collection
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static void listen(Pane pane, Class<?> type, ApplicationContext context, ObservableList<?> values) { private static void listen(Pane pane, Class<?> type, ApplicationContext context, ObservableList<?> values,
ViewLifetime lifetime, int offset, List<RepeatedChild> children) {
ObservableList<Object> elements = (ObservableList<Object>) values; ObservableList<Object> elements = (ObservableList<Object>) values;
elements.addListener((ListChangeListener<Object>) change -> { lifetime.listen(elements, change -> {
while (change.next()) { while (change.next()) {
if (change.wasPermutated() || change.wasUpdated()) { if (change.wasPermutated() || change.wasUpdated()) {
continue; continue;
} }
if (change.getRemovedSize() > 0) { for (int removed = 0; removed < change.getRemovedSize(); removed++) {
pane.getChildren().remove(change.getFrom(), change.getFrom() + change.getRemovedSize()); RepeatedChild child = children.remove(change.getFrom());
pane.getChildren().remove(child.node());
child.lifetime().close();
} }
for (int index = 0; index < change.getAddedSize(); index++) { for (int index = 0; index < change.getAddedSize(); index++) {
pane.getChildren().add( RepeatedChild child = child(type, context, change.getAddedSubList().get(index), lifetime);
change.getFrom() + index, int position = change.getFrom() + index;
child(type, context, change.getAddedSubList().get(index))); children.add(position, child);
pane.getChildren().add(offset + position, child.node());
} }
} }
}); });
@@ -103,12 +113,21 @@ final class RepeatApplier {
* @param element the Model instance * @param element the Model instance
* @return the loaded Component * @return the loaded Component
*/ */
private static Node child(Class<?> type, ApplicationContext context, Object element) { private static RepeatedChild child(Class<?> type, ApplicationContext context, Object element,
Object component = Components.fresh(type, context); ViewLifetime owner) {
Components.setModel(component, element); ViewLifetime lifetime = owner.child();
return (Node) component; try {
Object component = Components.fresh(type, context, lifetime);
Components.setModel(component, element, lifetime);
return new RepeatedChild((Node) component, lifetime);
} catch (RuntimeException | Error failure) {
lifetime.rollback(failure);
throw failure;
}
} }
private record RepeatedChild(Node node, ViewLifetime lifetime) {}
/** /**
* Returns the Component class named by the repeat. * Returns the Component class named by the repeat.
* *
+47 -22
View File
@@ -25,6 +25,7 @@ import javafx.beans.property.Property;
import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections; import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener; import javafx.collections.ListChangeListener;
import javafx.event.EventHandler;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
import javafx.scene.Node; import javafx.scene.Node;
import javafx.scene.Parent; import javafx.scene.Parent;
@@ -156,6 +157,8 @@ public class Table extends VBox {
* One Row per element that has been shown. A hidden element keeps its Row. * One Row per element that has been shown. A hidden element keeps its Row.
*/ */
private final Map<Object, Node> rows = new IdentityHashMap<>(); private final Map<Object, Node> rows = new IdentityHashMap<>();
private final Map<Object, ViewLifetime> rowLifetimes = new IdentityHashMap<>();
private ViewLifetime lifetime;
/** /**
* The collection this Table shows. * The collection this Table shows.
@@ -360,8 +363,8 @@ public class Table extends VBox {
* @param viewModel the ViewModel for this View * @param viewModel the ViewModel for this View
* @param context the container that creates each Row * @param context the container that creates each Row
*/ */
static void openAll(Parent root, Object viewModel, ApplicationContext context) { static void openAll(Parent root, Object viewModel, ApplicationContext context, ViewLifetime lifetime) {
walk(root, viewModel, context); walk(root, root, viewModel, context, lifetime);
} }
/** /**
@@ -370,7 +373,7 @@ public class Table extends VBox {
* @param viewModel the ViewModel for this View * @param viewModel the ViewModel for this View
* @param context the container that creates each Row * @param context the container that creates each Row
*/ */
void open(Object viewModel, ApplicationContext context) { void open(Object viewModel, ApplicationContext context, ViewLifetime owner) {
if (resultMode) { if (resultMode) {
return; return;
} }
@@ -379,6 +382,15 @@ public class Table extends VBox {
} }
opened = true; opened = true;
this.context = context; this.context = context;
lifetime = owner.child();
lifetime.own(() -> {
rowLifetimes.clear();
rows.clear();
body.getChildren().clear();
elements = FXCollections.observableArrayList();
selection.set(null);
this.context = null;
});
if (columns.isEmpty()) { if (columns.isEmpty()) {
throw new IllegalArgumentException("A table needs a column"); throw new IllegalArgumentException("A table needs a column");
} }
@@ -393,7 +405,7 @@ public class Table extends VBox {
} }
buildHeader(); buildHeader();
ensureWidths(); ensureWidths();
elements.addListener((ListChangeListener<Object>) this::onCollectionChange); lifetime.listen(elements, this::onCollectionChange);
refresh(); refresh();
} }
@@ -1182,6 +1194,8 @@ public class Table extends VBox {
} }
for (Object removed : change.getRemoved()) { for (Object removed : change.getRemoved()) {
rows.remove(removed); rows.remove(removed);
ViewLifetime removedRow = rowLifetimes.remove(removed);
if (removedRow != null) removedRow.close();
if (selection.get() == removed) { if (selection.get() == removed) {
selection.set(null); selection.set(null);
} }
@@ -1310,18 +1324,27 @@ public class Table extends VBox {
* @return the Row * @return the Row
*/ */
private Node createRow(Object element) { private Node createRow(Object element) {
Object component = Components.fresh(rowType, context); ViewLifetime rowLifetime = lifetime.child();
Components.setModel(component, element); try {
if (!(component instanceof Node node)) { Object component = Components.fresh(rowType, context, rowLifetime);
throw new IllegalArgumentException("Row is not a node: " + rowType.getName()); Components.setModel(component, element, rowLifetime);
} if (!(component instanceof Node node)) {
node.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> { throw new IllegalArgumentException("Row is not a node: " + rowType.getName());
if (event.getButton() == MouseButton.PRIMARY) {
selection.set(element);
} }
}); EventHandler<MouseEvent> select = event -> {
watchEdits(node); if (event.getButton() == MouseButton.PRIMARY) {
return node; selection.set(element);
}
};
node.addEventFilter(MouseEvent.MOUSE_CLICKED, select);
rowLifetime.own(() -> node.removeEventFilter(MouseEvent.MOUSE_CLICKED, select));
watchEdits(node, rowLifetime);
if (rowLifetime.managed()) rowLifetimes.put(element, rowLifetime);
return node;
} catch (RuntimeException | Error failure) {
rowLifetime.rollback(failure);
throw failure;
}
} }
/** /**
@@ -1329,13 +1352,13 @@ public class Table extends VBox {
* *
* @param node the Row or one of its fields * @param node the Row or one of its fields
*/ */
private void watchEdits(Node node) { private void watchEdits(Node node, ViewLifetime rowLifetime) {
if (node instanceof javafx.scene.control.TextInputControl input) { if (node instanceof javafx.scene.control.TextInputControl input) {
input.textProperty().addListener((observable, previous, current) -> refresh()); rowLifetime.listen(input.textProperty(), (observable, previous, current) -> refresh());
} }
if (node instanceof Parent parent) { if (node instanceof Parent parent) {
for (Node child : parent.getChildrenUnmodifiable()) { for (Node child : parent.getChildrenUnmodifiable()) {
watchEdits(child); watchEdits(child, rowLifetime);
} }
} }
} }
@@ -1543,18 +1566,20 @@ public class Table extends VBox {
* @param viewModel the ViewModel for this View * @param viewModel the ViewModel for this View
* @param context the container that creates each Row * @param context the container that creates each Row
*/ */
private static void walk(Node node, Object viewModel, ApplicationContext context) { private static void walk(Node node, Parent root, Object viewModel, ApplicationContext context,
ViewLifetime lifetime) {
if (node != root && Components.ownsBindings(node)) return;
if (node instanceof Table table) { if (node instanceof Table table) {
table.open(viewModel, context); table.open(viewModel, context, lifetime);
} }
if (!(node instanceof Parent parent)) { if (!(node instanceof Parent parent)) {
return; return;
} }
for (Node child : parent.getChildrenUnmodifiable()) { for (Node child : parent.getChildrenUnmodifiable()) {
walk(child, viewModel, context); walk(child, root, viewModel, context, lifetime);
} }
if (parent instanceof ScrollPane pane && pane.getContent() != null) { if (parent instanceof ScrollPane pane && pane.getContent() != null) {
walk(pane.getContent(), viewModel, context); walk(pane.getContent(), root, viewModel, context, lifetime);
} }
} }
@@ -0,0 +1,99 @@
package de.neitzel.fx.view;
import java.util.LinkedHashSet;
import java.util.SequencedSet;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
/** Tracks the resources installed by one View or one of its dynamic children. */
final class ViewLifetime implements AutoCloseable {
private final ViewModelContext models;
private final SequencedSet<Runnable> cleanup = new LinkedHashSet<>();
private boolean closed;
ViewLifetime(ViewModelContext models) {
this.models = models;
}
ViewModelContext models() {
return models;
}
boolean managed() {
return models != ViewModels.LEGACY;
}
void own(Runnable removal) {
if (managed()) {
if (closed) {
removal.run();
} else {
cleanup.addLast(removal);
}
}
}
void ownController(Object controller) {
if (controller instanceof AutoCloseable closeable) {
own(() -> {
try {
closeable.close();
} catch (RuntimeException failure) {
throw failure;
} catch (Exception failure) {
throw new IllegalStateException("Could not close " + controller.getClass().getName(), failure);
}
});
}
}
<T> void listen(ObservableValue<T> observable, ChangeListener<? super T> listener) {
observable.addListener(listener);
own(() -> observable.removeListener(listener));
}
<T> void listen(ObservableList<T> observable, ListChangeListener<? super T> listener) {
observable.addListener(listener);
own(() -> observable.removeListener(listener));
}
ViewLifetime child() {
ViewLifetime child = new ViewLifetime(models);
Runnable closeChild = child::close;
own(closeChild);
child.own(() -> cleanup.remove(closeChild));
return child;
}
@Override
public void close() {
if (closed) return;
closed = true;
Throwable failure = null;
while (!cleanup.isEmpty()) {
try {
cleanup.removeLast().run();
} catch (RuntimeException | Error next) {
if (failure == null) {
failure = next;
} else if (failure != next) {
failure.addSuppressed(next);
}
}
}
if (failure instanceof RuntimeException runtime) throw runtime;
if (failure instanceof Error error) throw error;
}
/** Cleans up an incomplete load while preserving its original failure. */
void rollback(Throwable failure) {
try {
close();
} catch (RuntimeException | Error cleanupFailure) {
if (failure != cleanupFailure) failure.addSuppressed(cleanupFailure);
}
}
}
@@ -77,14 +77,33 @@ public final class ViewLoader {
* @throws IllegalArgumentException when a Direct binding names a path that is not a read-write Attribute * @throws IllegalArgumentException when a Direct binding names a path that is not a read-write Attribute
*/ */
public static LoadedView load(URL fxml, Object model, ApplicationContext context) { public static LoadedView load(URL fxml, Object model, ApplicationContext context) {
Class<?> controllerType = FxmlControllers.controllerClass(fxml); return load(fxml, model, context, new ViewLifetime(ViewModels.LEGACY));
Class<?> viewModelClass = ViewModels.namedOn(controllerType); }
Object viewModel = ViewModels.of(model, viewModelClass);
LoadSession session = LoadSession.open(); /**
* Loads a View with a fresh Controller and Components in an explicitly owned Model context.
* Close the result when its UI is removed, or close the Model context to close all its Views.
*
* @param fxml the FXML document
* @param model the Model instance
* @param context the container for Controllers and services
* @param models the Model context shared by this View and related Views
* @return the loaded View
*/
public static LoadedView load(URL fxml, Object model, ApplicationContext context, ViewModelContext models) {
return load(fxml, model, context, models.openView());
}
private static LoadedView load(URL fxml, Object model, ApplicationContext context, ViewLifetime lifetime) {
LoadSession session = LoadSession.nest();
try { try {
Class<?> controllerType = FxmlControllers.controllerClass(fxml);
Class<?> viewModelClass = ViewModels.namedOn(controllerType);
Object viewModel = ViewModels.of(lifetime.models(), model, viewModelClass);
FXMLLoader loader = new FXMLLoader(fxml, resources(context, fxml, controllerType)); FXMLLoader loader = new FXMLLoader(fxml, resources(context, fxml, controllerType));
loader.setControllerFactory(type -> controller(context, type)); FxmlHandlers.observe(loader, lifetime);
loader.setBuilderFactory(type -> Components.builder(type, context)); loader.setControllerFactory(type -> createController(context, type, lifetime));
loader.setBuilderFactory(type -> Components.builder(type, context, lifetime));
Object loaded = loader.load(); Object loaded = loader.load();
if (!(loaded instanceof Parent root)) { if (!(loaded instanceof Parent root)) {
throw new IllegalArgumentException("View root must be a parent"); throw new IllegalArgumentException("View root must be a parent");
@@ -97,17 +116,29 @@ public final class ViewLoader {
hasViewModel.setViewModel(bound); hasViewModel.setViewModel(bound);
} }
for (BindingList bindingList : session.bindingLists()) { for (BindingList bindingList : session.bindingLists()) {
bindingList.apply(loader.getNamespace(), viewModel, controller, root, context); bindingList.apply(loader.getNamespace(), viewModel, controller, root, context, lifetime);
} }
Table.openAll(root, viewModel, context); Table.openAll(root, viewModel, context, lifetime);
return new LoadedView(root, viewModel); session.checkFailure();
return new LoadedView(root, viewModel, lifetime);
} catch (IOException failure) { } catch (IOException failure) {
lifetime.rollback(failure);
throw new IllegalStateException("Could not load view " + fxml, failure); throw new IllegalStateException("Could not load view " + fxml, failure);
} catch (RuntimeException | Error failure) {
lifetime.rollback(failure);
throw failure;
} finally { } finally {
LoadSession.close(); LoadSession.unnest();
} }
} }
static Object createController(ApplicationContext context, Class<?> type, ViewLifetime lifetime) {
if (!lifetime.managed()) return context.getComponent(type);
Object controller = context.createComponent(type);
lifetime.ownController(controller);
return controller;
}
static Messages resources(ApplicationContext context, URL fxml, Class<?> type) { static Messages resources(ApplicationContext context, URL fxml, Class<?> type) {
Localizer languages; Localizer languages;
try { try {
@@ -118,14 +149,4 @@ public final class ViewLoader {
return languages.forView(fxml, type); return languages.forView(fxml, type);
} }
/**
* Asks the container for the Controller class named by the document.
*
* @param context the container
* @param type the Controller class
* @return the Controller
*/
private static Object controller(ApplicationContext context, Class<?> type) {
return context.getComponent(type.asSubclass(Object.class));
}
} }
@@ -80,6 +80,7 @@ public class ViewModel {
* The Model instance this ViewModel was built for. * The Model instance this ViewModel was built for.
*/ */
private final Object model; private final Object model;
private final ViewModelContext models;
/** /**
* JavaFX properties keyed by Attribute name. * JavaFX properties keyed by Attribute name.
@@ -136,7 +137,8 @@ public class ViewModel {
*/ */
protected ViewModel(Object model) { protected ViewModel(Object model) {
this.model = model; this.model = model;
ViewModels.register(model, this); models = ViewModels.constructingContext();
models.viewModels().put(model, this);
for (PropertyDescriptor descriptor : descriptors(model.getClass())) { for (PropertyDescriptor descriptor : descriptors(model.getClass())) {
Method getter = descriptor.getReadMethod(); Method getter = descriptor.getReadMethod();
Method setter = descriptor.getWriteMethod(); Method setter = descriptor.getWriteMethod();
@@ -218,9 +220,9 @@ public class ViewModel {
* @param listener the listener * @param listener the listener
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
void addAttributeListener(ChangeListener<Object> listener) { void addAttributeListener(ViewLifetime lifetime, ChangeListener<Object> listener) {
for (Property<?> property : properties.values()) { for (Property<?> property : properties.values()) {
((Property<Object>) property).addListener(listener); lifetime.listen((Property<Object>) property, listener);
} }
} }
@@ -429,7 +431,7 @@ public class ViewModel {
* Attaching the change listener reads the value. That read is ignored until * Attaching the change listener reads the value. That read is ignored until
* {@link #attached()} so a Component annotation can name the class first. * {@link #attached()} so a Component annotation can name the class first.
*/ */
private static final class LazyComplex extends SimpleObjectProperty<Object> { private final class LazyComplex extends SimpleObjectProperty<Object> {
/** /**
* The Model instance, kept until the nested ViewModel is built. * The Model instance, kept until the nested ViewModel is built.
@@ -464,7 +466,7 @@ public class ViewModel {
public Object get() { public Object get() {
if (!attaching && !realized) { if (!attaching && !realized) {
realized = true; realized = true;
super.set(current == null ? null : ViewModels.of(current)); super.set(current == null ? null : ViewModels.of(models, current, null));
} }
return super.get(); return super.get();
} }
@@ -0,0 +1,42 @@
package de.neitzel.fx.view;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* Owns the ViewModel identity and loaded Views for a window, document or archive session.
* Use this context on the JavaFX application thread. Closing it closes its remaining Views and
* releases its Model registrations. Close an individual {@link LoadedView} earlier to detach it
* while its Model remains available to other Views in this context.
*/
public final class ViewModelContext implements AutoCloseable {
private final Map<Object, Object> viewModels = new IdentityHashMap<>();
private final ViewLifetime views = new ViewLifetime(this);
private boolean closed;
ViewLifetime openView() {
checkOpen();
return views.child();
}
Map<Object, Object> viewModels() {
checkOpen();
return viewModels;
}
private void checkOpen() {
if (closed) throw new IllegalStateException("ViewModelContext is closed");
}
@Override
public void close() {
if (closed) return;
closed = true;
try {
views.close();
} finally {
viewModels.clear();
}
}
}
@@ -2,7 +2,6 @@ package de.neitzel.fx.view;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.IdentityHashMap;
import java.util.Map; import java.util.Map;
/** /**
@@ -15,7 +14,10 @@ final class ViewModels {
/** /**
* ViewModels already built, keyed by Model identity. * ViewModels already built, keyed by Model identity.
*/ */
private static final Map<Object, Object> BY_INSTANCE = new IdentityHashMap<>(); static final ViewModelContext LEGACY = new ViewModelContext();
// Preserve the single-argument constructor used by custom and generated ViewModels.
private static final ThreadLocal<ViewModelContext> CONSTRUCTING = new ThreadLocal<>();
/** /**
* Prevents instantiation. * Prevents instantiation.
@@ -23,32 +25,26 @@ final class ViewModels {
private ViewModels() { private ViewModels() {
} }
/**
* Returns the ViewModel for a Model instance, building the generic one when none exists yet.
*
* @param model the Model instance
* @return the ViewModel for that instance, or a replacement that exposes JavaFX properties by name
*/
static Object of(Object model) { static Object of(Object model) {
return of(model, null); return of(model, null);
} }
/**
* Returns the ViewModel for a Model instance.
* <p>
* Selects a registered default or compatible explicit class before construction. Without
* a registered default, a null class or {@link ViewModel} itself uses the generic ViewModel.
* An unregistered replacement may expose JavaFX properties by name. The container does not
* create it. The first View fixes the instance; later compatible superclass/interface requests
* reuse it, while incompatible requests fail. A View naming no class reuses the instance.
*
* @param model the Model instance
* @param viewModelClass the class named by {@link ViewModelClass}, or {@code null}
* @return the ViewModel for that instance, or the replacement
*/
static Object of(Object model, Class<?> viewModelClass) { static Object of(Object model, Class<?> viewModelClass) {
return of(LEGACY, model, viewModelClass);
}
static ViewModelContext constructingContext() {
ViewModelContext context = CONSTRUCTING.get();
return context == null ? LEGACY : context;
}
/**
* Gets or builds the ViewModel for this Model identity in the caller's context.
*/
static Object of(ViewModelContext context, Object model, Class<?> viewModelClass) {
Map<Object, Object> instances = context.viewModels();
Class<?> selected = ViewModelDefaults.select(model.getClass(), viewModelClass, model.getClass().getClassLoader()); Class<?> selected = ViewModelDefaults.select(model.getClass(), viewModelClass, model.getClass().getClassLoader());
Object existing = BY_INSTANCE.get(model); Object existing = instances.get(model);
if (existing != null) { if (existing != null) {
if (viewModelClass != null && viewModelClass != ViewModel.class if (viewModelClass != null && viewModelClass != ViewModel.class
&& !selected.isInstance(existing)) { && !selected.isInstance(existing)) {
@@ -58,8 +54,22 @@ final class ViewModels {
} }
return existing; return existing;
} }
if (selected == ViewModel.class) return new ViewModel(model); ViewModelContext previous = CONSTRUCTING.get();
return construct(model, selected); CONSTRUCTING.set(context);
try {
Object created = selected == ViewModel.class ? new ViewModel(model) : construct(model, selected);
instances.put(model, created);
return created;
} catch (RuntimeException | Error failure) {
instances.remove(model);
throw failure;
} finally {
if (previous == null) {
CONSTRUCTING.remove();
} else {
CONSTRUCTING.set(previous);
}
}
} }
/** /**
@@ -83,8 +93,7 @@ final class ViewModels {
/** /**
* Constructs a ViewModel or a replacement with the Model instance. * Constructs a ViewModel or a replacement with the Model instance.
* <p> * <p>
* A result that is not a {@link ViewModel} is registered here. A {@link ViewModel} registers * A {@link ViewModel} registers itself from its constructor, before its Attributes are walked.
* itself from its constructor, before its Attributes are walked.
* *
* @param model the Model instance * @param model the Model instance
* @param viewModelClass the class to construct * @param viewModelClass the class to construct
@@ -94,13 +103,8 @@ final class ViewModels {
Constructor<?> constructor = constructor(model, viewModelClass); Constructor<?> constructor = constructor(model, viewModelClass);
constructor.setAccessible(true); constructor.setAccessible(true);
try { try {
Object created = constructor.newInstance(model); return constructor.newInstance(model);
if (!(created instanceof ViewModel)) {
register(model, created);
}
return created;
} catch (InvocationTargetException failure) { } catch (InvocationTargetException failure) {
BY_INSTANCE.remove(model);
if (failure.getCause() instanceof RuntimeException runtime) { if (failure.getCause() instanceof RuntimeException runtime) {
throw runtime; throw runtime;
} }
@@ -138,13 +142,4 @@ final class ViewModels {
return chosen; return chosen;
} }
/**
* Records a ViewModel before its Attributes are walked, so a cycle reuses it.
*
* @param model the Model instance
* @param viewModel the ViewModel under construction
*/
static void register(Object model, Object viewModel) {
BY_INSTANCE.put(model, viewModel);
}
} }
@@ -0,0 +1,154 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Address;
import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Person;
import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.fx.view.managed.ViewController;
import de.neitzel.injection.ApplicationContext;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ManagedViewTest {
@BeforeAll
static void start() throws InterruptedException {
FxThread.start();
}
@Test
void sharesViewModelWithinContextAndClosesOnlyTheRequestedView() throws Exception {
FxThread.onFx(() -> {
var model = new Person("Ada");
var injection = new ApplicationContext("de.neitzel.fx.view.managed");
try (var models = new ViewModelContext(); var otherModels = new ViewModelContext()) {
var first = ViewLoader.load(fxml("managed-view.fxml"), model, injection, models);
var second = ViewLoader.load(fxml("managed-view.fxml"), model, injection, models);
var other = ViewLoader.load(fxml("managed-view.fxml"), model, injection, otherModels);
assertSame(first.getViewModel(), second.getViewModel());
assertNotSame(first.getViewModel(), other.getViewModel());
var firstInput = field(first.getRoot(), "#name");
var secondInput = field(second.getRoot(), "#name");
assertNotSame(firstInput, secondInput);
var firstController = (ViewController) firstInput.getUserData();
var secondController = (ViewController) secondInput.getUserData();
assertNotSame(firstController, secondController);
firstInput.setText("Grace");
assertEquals("Grace", secondInput.getText());
first.close();
first.close();
firstInput.setText("Detached");
assertEquals("Grace", model.getName());
secondInput.setText("Lin");
assertEquals("Lin", model.getName());
assertEquals("Detached", firstInput.getText());
assertEquals(1, firstController.getCloseCount());
assertEquals(0, secondController.getCloseCount());
models.close();
secondInput.setText("Also detached");
assertEquals("Lin", model.getName());
assertEquals(1, secondController.getCloseCount());
assertThrows(IllegalStateException.class,
() -> ViewLoader.load(fxml("managed-view.fxml"), model, injection, models));
}
});
}
@Test
void failedBindingClosesControllerAndRollsBackEarlierBinding() throws Exception {
FxThread.onFx(() -> {
var model = new Person("Ada");
var injection = new ApplicationContext("de.neitzel.fx.view.managed");
try (var models = new ViewModelContext()) {
var registry = injection.getComponent(ViewController.Registry.class);
assertThrows(IllegalArgumentException.class,
() -> ViewLoader.load(fxml("managed-invalid.fxml"), model, injection, models));
var abandoned = registry.getLastCreated();
assertEquals(1, abandoned.getCloseCount());
assertNull(abandoned.getInput().getOnAction());
abandoned.getInput().setText("Detached");
assertEquals("Ada", model.getName());
var loaded = ViewLoader.load(fxml("managed-view.fxml"), model, injection, models);
field(loaded.getRoot(), "#name").setText("Working");
assertEquals("Detached", abandoned.getInput().getText());
assertEquals("Working", model.getName());
}
});
}
@Test
void removingARepeatChildDetachesItsBindings() throws Exception {
FxThread.onFx(() -> {
var person = new Person("Ada");
var first = new Address("Main");
var second = new Address("Water");
person.setAddresses(new ArrayList<>(List.of(first, second)));
try (var models = new ViewModelContext()) {
var context = new ApplicationContext("de.neitzel.fx.view.component");
var loaded = ViewLoader.load(fxml("repeat-addresses.fxml"), person, context, models);
var pane = (VBox) loaded.getRoot().lookup("#addressPane");
var detached = field(pane.getChildren().getFirst(), "#streetField");
var active = field(pane.getChildren().getLast(), "#streetField");
person.getAddresses().removeFirst();
detached.setText("Detached");
active.setText("Still active");
assertEquals("Main", first.getStreet());
assertEquals("Still active", second.getStreet());
loaded.close();
person.getAddresses().add(new Address("New"));
assertEquals(0, pane.getChildren().size());
active.setText("Also detached");
assertEquals("Still active", second.getStreet());
}
});
}
@Test
void removingATableRowDetachesItsBindings() throws Exception {
FxThread.onFx(() -> {
var host = new Host();
var visit = new Visit("Main", "Darmstadt");
host.setVisits(new ArrayList<>(List.of(visit)));
try (var models = new ViewModelContext()) {
var context = new ApplicationContext("de.neitzel.fx.view.component");
var loaded = ViewLoader.load(fxml("show-visits.fxml"), host, context, models);
var table = (Table) loaded.getRoot().lookup("#visitsTable");
var scroll = (ScrollPane) table.lookup("." + Table.SCROLL_STYLE);
var input = field(scroll.getContent(), "#streetField");
host.getVisits().clear();
input.setText("Detached");
assertEquals("Main", visit.getStreet());
loaded.close();
host.getVisits().add(visit);
assertEquals(0, ((VBox) scroll.getContent()).getChildren().size());
}
});
}
private static URL fxml(String path) {
return ManagedViewTest.class.getResource(path);
}
private static TextField field(javafx.scene.Node root, String id) {
return (TextField) root.lookup(id);
}
}
@@ -0,0 +1,52 @@
package de.neitzel.fx.view.managed;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import lombok.Getter;
@Singleton
public class ViewController implements AutoCloseable {
@Singleton
public static class Registry {
@Getter
private ViewController lastCreated;
@Inject
public Registry() {
}
}
private final Registry registry;
@FXML
@Getter
private TextField input;
@Getter
private int closeCount;
@Inject
public ViewController(Registry registry) {
this.registry = registry;
}
@FXML
public void initialize() {
registry.lastCreated = this;
input.setUserData(this);
}
@FXML
public void onAction() {
input.setText("Handled");
}
@Override
public void close() {
closeCount++;
}
}
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.view.managed.ViewController">
<fx:define>
<BindingList>
<DirectBinding control="input" property="text" path="name" direction="both"/>
<DirectBinding control="missing" property="text" path="name" direction="both"/>
</BindingList>
</fx:define>
<TextField fx:id="input" id="name" onAction="#onAction"/>
</VBox>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.view.managed.ViewController">
<fx:define>
<BindingList>
<DirectBinding control="input" property="text" path="name" direction="both"/>
</BindingList>
</fx:define>
<TextField fx:id="input" id="name" onAction="#onAction"/>
</VBox>