From 20249f5790d7ead56c6907244cead29bd57613f1 Mon Sep 17 00:00:00 2001 From: Konrad Neitzel Date: Thu, 26 Nov 2026 16:01:19 +0100 Subject: [PATCH] Separate JavaFX loading from the Neitzel injection container --- README.md | 16 +- core/pom.xml | 5 - fx-example/README.md | 6 +- fx-example/docs/docking-mvvm.md | 5 +- fx-example/pom.xml | 2 +- .../preview/AddressPreviewProvider.java | 14 +- .../example/preview/DeskPreviewProvider.java | 9 +- .../example/preview/NotePreviewProvider.java | 10 +- .../example/preview/PreviewProvidersTest.java | 24 ++- .../fx/example/preview/SampleSession.java | 6 +- .../java/de/neitzel/fx/example/DeskApp.java | 23 +- .../fx/example/docking/mvvm/MvvmEditor.java | 12 +- .../fx/example/view/DeskController.java | 12 -- .../neitzel/fx/example/view/VisitActions.java | 17 ++ .../de/neitzel/fx/example/view/VisitRow.java | 6 +- .../de/neitzel/fx/example/DeskLoadsTest.java | 35 ++-- fx-injection/README.md | 64 ++++++ fx-injection/pom.xml | 54 +++++ .../fx/injection/NeitzelViewDependencies.java | 53 +++++ .../NeitzelViewDependenciesTest.java | 126 +++++++++++ .../de/neitzel/fx/injection/fixture/Card.java | 28 +++ .../fx/injection/fixture/Controller.java | 32 +++ .../neitzel/fx/injection/fixture/Entry.java | 12 ++ .../fx/injection/fixture/FormatName.java | 13 ++ .../fx/injection/fixture/Lifecycle.java | 16 ++ .../de/neitzel/fx/injection/fixture/Card.fxml | 10 + .../neitzel/fx/injection/fixture/Invalid.fxml | 7 + .../de/neitzel/fx/injection/fixture/View.fxml | 23 ++ .../fx/injection/fixture/View.properties | 1 + .../java/de/neitzel/fx/test/FxFixture.java | 10 +- .../de/neitzel/fx/test/FxFixtureTest.java | 12 +- fx/README.md | 128 +++++++---- fx/docs/architecture.md | 42 ++-- fx/docs/fxml-controls.md | 2 +- fx/docs/i18n.md | 2 +- fx/docs/quick-start.md | 12 +- fx/pom.xml | 5 - .../java/de/neitzel/fx/view/BindingList.java | 3 +- .../fx/view/CommandBindingApplier.java | 3 - .../java/de/neitzel/fx/view/Components.java | 74 ++----- .../neitzel/fx/view/DirectBindingApplier.java | 9 +- .../java/de/neitzel/fx/view/FxmlHandlers.java | 2 +- .../java/de/neitzel/fx/view/LoadSession.java | 24 --- .../de/neitzel/fx/view/RepeatApplier.java | 15 +- .../main/java/de/neitzel/fx/view/Table.java | 11 +- .../de/neitzel/fx/view/ViewDependencies.java | 22 ++ .../de/neitzel/fx/view/ViewInstances.java | 66 ++++++ .../java/de/neitzel/fx/view/ViewLifetime.java | 28 +-- .../java/de/neitzel/fx/view/ViewLoader.java | 128 +++-------- .../java/de/neitzel/fx/view/ViewObject.java | 15 ++ .../de/neitzel/fx/view/BindCommandTest.java | 11 +- .../fx/view/BindReadOnlySourcesTest.java | 11 +- .../fx/view/CarryChildMessageTest.java | 39 ++-- .../ChooseControllerAndViewModelTest.java | 35 ++-- .../de/neitzel/fx/view/ComputeAValueTest.java | 17 +- .../fx/view/ConvertAndRecordFailureTest.java | 41 ++-- .../de/neitzel/fx/view/DataGridFxmlTest.java | 5 +- .../fx/view/EditAddressInAComponentTest.java | 31 ++- .../fx/view/FilterByChecklistTest.java | 3 +- .../fx/view/FilterByComparisonTest.java | 3 +- .../view/KeepAControlAfterTheColumnsTest.java | 3 +- .../fx/view/ListSourceBindingTest.java | 4 +- .../de/neitzel/fx/view/ManagedViewTest.java | 35 ++-- .../fx/view/ObserveGridSelectionTest.java | 5 +- .../fx/view/OpenAtAGivenWidthTest.java | 5 +- .../fx/view/ReachNestedAttributeTest.java | 59 +++--- .../fx/view/RepeatAddressComponentsTest.java | 27 +-- .../de/neitzel/fx/view/ResizeAColumnTest.java | 3 +- .../fx/view/SearchTheChecklistTest.java | 3 +- .../de/neitzel/fx/view/SelectARowTest.java | 3 +- .../fx/view/ShowAListOfSimpleValuesTest.java | 5 +- .../neitzel/fx/view/ShowATableOfRowsTest.java | 11 +- .../fx/view/ShowAndEditOneAttributeTest.java | 29 ++- .../fx/view/ShowMessagesWhenAskedTest.java | 17 +- .../de/neitzel/fx/view/SortOneColumnTest.java | 3 +- .../java/de/neitzel/fx/view/TestViews.java | 87 ++++++++ .../neitzel/fx/view/ViewDependenciesTest.java | 198 ++++++++++++++++++ .../fx/view/chosen/BadgeController.java | 3 +- .../fx/view/chosen/CaptionAddressForm.java | 3 +- .../fx/view/chosen/DeskController.java | 6 +- .../neitzel/fx/view/chosen/DeskGreeting.java | 3 +- .../fx/view/chosen/HandedNameController.java | 3 +- .../fx/view/chosen/TitledController.java | 3 +- .../fx/view/command/CommandController.java | 3 +- .../neitzel/fx/view/component/ActionRow.java | 6 +- .../fx/view/component/AddressForm.java | 6 +- .../fx/view/component/CityFirstRow.java | 6 +- .../fx/view/component/EnvelopeForm.java | 3 +- .../fx/view/component/StreetCaption.java | 3 +- .../neitzel/fx/view/component/VisitRow.java | 6 +- .../view/computed/WorkingAgeController.java | 3 +- .../de/neitzel/fx/view/fixture/AgeUnit.java | 3 +- .../view/fixture/CheckedStreetConverter.java | 3 +- .../fx/view/fixture/PrefixedAgeConverter.java | 6 +- .../fx/view/fixture/ShownAgeConverter.java | 3 +- .../fx/view/managed/ViewController.java | 10 +- .../readable/ReadableSourcesController.java | 5 +- .../selection/SelectionSummaryController.java | 3 +- .../de/neitzel/fx/view/adapter-include.fxml | 5 + .../de/neitzel/fx/view/adapter-invalid.fxml | 7 + .../de/neitzel/fx/view/adapter-localized.fxml | 2 + .../de/neitzel/fx/view/adapter-view.fxml | 6 + injection/README.md | 27 ++- .../neitzel/injection/ApplicationContext.java | 2 +- .../injection/MissingComponentException.java | 15 ++ pom.xml | 1 + 106 files changed, 1428 insertions(+), 674 deletions(-) create mode 100644 fx-example/src/main/java/de/neitzel/fx/example/view/VisitActions.java create mode 100644 fx-injection/README.md create mode 100644 fx-injection/pom.xml create mode 100644 fx-injection/src/main/java/de/neitzel/fx/injection/NeitzelViewDependencies.java create mode 100644 fx-injection/src/test/java/de/neitzel/fx/injection/NeitzelViewDependenciesTest.java create mode 100644 fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Card.java create mode 100644 fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Controller.java create mode 100644 fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Entry.java create mode 100644 fx-injection/src/test/java/de/neitzel/fx/injection/fixture/FormatName.java create mode 100644 fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Lifecycle.java create mode 100644 fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/Card.fxml create mode 100644 fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/Invalid.fxml create mode 100644 fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/View.fxml create mode 100644 fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/View.properties create mode 100644 fx/src/main/java/de/neitzel/fx/view/ViewDependencies.java create mode 100644 fx/src/main/java/de/neitzel/fx/view/ViewInstances.java create mode 100644 fx/src/main/java/de/neitzel/fx/view/ViewObject.java create mode 100644 fx/src/test/java/de/neitzel/fx/view/TestViews.java create mode 100644 fx/src/test/java/de/neitzel/fx/view/ViewDependenciesTest.java create mode 100644 fx/src/test/resources/de/neitzel/fx/view/adapter-include.fxml create mode 100644 fx/src/test/resources/de/neitzel/fx/view/adapter-invalid.fxml create mode 100644 fx/src/test/resources/de/neitzel/fx/view/adapter-localized.fxml create mode 100644 fx/src/test/resources/de/neitzel/fx/view/adapter-view.fxml create mode 100644 injection/src/main/java/de/neitzel/injection/MissingComponentException.java diff --git a/README.md b/README.md index 6d091e8..7ed4c0e 100644 --- a/README.md +++ b/README.md @@ -56,17 +56,22 @@ JavaFX docking, saved HTML/SingleFile viewing, standalone bars and optional MVVM ### fx-test -JavaFX fixtures for JUnit Jupiter. Add `de.neitzel.lib:fx-test` at the same version as `fx` with Maven scope `test`. Annotate the class with `@FxTest` and accept an `FxFixture` parameter in each test. Use `fx.run` for actions, `fx.call` for values and `fx.await("dialog closed", () -> !dialog.isShowing())` to wait from the test thread. `fx.load(fxml, model, services)` uses the production ViewLoader and a fresh ViewModelContext per test. +JavaFX fixtures for JUnit Jupiter. Add `de.neitzel.lib:fx-test` at the same version as `fx` with Maven scope `test`. Annotate the class with `@FxTest` and accept an `FxFixture` parameter in each test. Use `fx.run` for actions, `fx.call` for values and `fx.await("dialog closed", () -> !dialog.isShowing())` to wait from the test thread. `fx.loadWithDependencies(fxml, model, dependencies)` uses the production ViewLoader and a fresh ViewModelContext per test. The extension keeps JavaFX running between tests, isolates the class with JUnit's `@Isolated`, hides windows opened by each test, closes its view context and reports unhandled FX callbacks at teardown. Complete background work before the test ends. Select the backend in the test JVM before toolkit startup, for example `-Dglass.platform=Headless`. +### fx-injection + +Optional adapter in the separated `1.0.7-SNAPSHOT` for applications using Neitzel's `ApplicationContext`. +It brings in `fx` and `injection`. See [adapter setup and migration](fx-injection/README.md). + ### injection -Package scanner and type-based container used by `fx`. See [injection/README.md](injection/README.md). +Standalone package scanner and type-based container. See [injection/README.md](injection/README.md). ### fx-example -Person desk that shows how to use `fx` and `injection`. Build with `./mvnw -pl fx-example -am install`, then run `./mvnw -f fx-example/pom.xml javafx:run`. See [fx-example/README.md](fx-example/README.md). +Person desk that shows how to use FX with `fx-injection`. Build with `./mvnw -pl fx-example -am install`, then run `./mvnw -f fx-example/pom.xml javafx:run`. See [fx-example/README.md](fx-example/README.md). ### gson @@ -90,6 +95,11 @@ The [complete quick start](fx/docs/quick-start.md) includes local installation, Build with Java 25. Maven wrapper version is 3.9.11; the project requires Maven 3.9.11 or later. Surefire fails the build if tests fail. +## Changes in 1.0.7-SNAPSHOT + +- Use `fx` and `fx-test` with an application-supplied `ViewDependencies` adapter. +- Add `fx-injection` to keep using Neitzel's `ApplicationContext` from the new loaders. See [migration](fx-injection/README.md#migrate-an-existing-fx-application). + ## Changes in 1.0.6 - Load managed FXML Components independently and bind read-only observables, HTML and replaceable suggestion lists toward the view. diff --git a/core/pom.xml b/core/pom.xml index 1e51356..b93280b 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -29,11 +29,6 @@ jna ${jna.version} - - org.reflections - reflections - ${reflections.version} - diff --git a/fx-example/README.md b/fx-example/README.md index c737786..62f267d 100644 --- a/fx-example/README.md +++ b/fx-example/README.md @@ -1,6 +1,6 @@ # Person desk reference application -This runnable application demonstrates [NeitzelLib FX](../fx/README.md) and [injection](../injection/README.md) together. It edits one Person with a home Address, nested Note, visit list, selected visit and tags. Use it as a reference for wiring a real screen; the [minimal quick start](../fx/docs/quick-start.md) is the smaller starting point for a new project. +This runnable application demonstrates [NeitzelLib FX](../fx/README.md) with the [optional Neitzel adapter](../fx-injection/README.md). It edits one Person with a home Address, nested Note, visit list, selected visit and tags. Use it as a reference for wiring a real screen; the [minimal quick start](../fx/docs/quick-start.md) is the smaller starting point for a new project. Separate Java/FXML launchers demonstrate [standalone bars](../fx/docs/bars.md) and [docking](../fx/docs/docking.md) without initializing MVVM or injection. @@ -47,7 +47,7 @@ Paths below are relative to this module. Java sources share `src/main/java/de/ne | File/type | Responsibility | | --- | --- | | `Main` | Plain Java launcher calling `Application.launch` | -| `DeskApp` | Scan configuration, fresh sample Model, ViewLoader, Scene and message popup registration | +| `DeskApp` | Scan configuration, sample Model, Component registrations in `DeskApp.dependencies(person)`, ViewLoader and window-owned Model context | | `model/Person`, `Address`, `Note`, `Role` | JavaBean data and enum; no JavaFX properties required | | `view/DeskController` and `Desk.fxml` | Screen handlers, computed greeting, controls and binding declarations | | `view/PersonViewModel` | Handwritten ViewModel subclass with a derived title | @@ -81,7 +81,7 @@ normal build needs no Designer processor; Lombok still runs. 2. Edit Age using its `years ` text format. An invalid value stays visible while the previous Model value is retained. A message explains the failure; a valid value clears that conversion failure. 3. Edit the home street. The path-bound label follows. Empty street input fails through `StreetConverter`; the parent receives the child message with the `home.street` source prefix. 4. Edit the nested note. AddressForm's inner NoteForm binds to its own Model. The `Opened as ...` label records initial setup rather than tracking every later city edit. -5. Add a visit. Both the repeated forms and Table gain a row. Edit a street in one representation and observe the same Address in the other. The Table's Remove button delegates to the controller. +5. Add a visit. Both the repeated forms and Table gain a row. Edit a street in one representation and observe the same Address in the other. The Table's Remove button uses the desk's shared `VisitActions` service. 6. Select a visit in the ComboBox or Table. Both use the `selectedVisit` Attribute. Resize, sort and filter Table columns; filtering and sorting affect displayed rows without reordering the Model's list. 7. Edit the visited date in ISO form (`yyyy-MM-dd`). Invalid text keeps the old date. Add a tag to see a shared ObservableList of simple values. 8. Try the information, warning and fatal message buttons. Severity is data and logging behavior; a fatal message does not itself exit the application. Close each non-blocking popup normally. diff --git a/fx-example/docs/docking-mvvm.md b/fx-example/docs/docking-mvvm.md index dcf1c4c..a696bb5 100644 --- a/fx-example/docs/docking-mvvm.md +++ b/fx-example/docs/docking-mvvm.md @@ -41,8 +41,9 @@ The application adapter owns its change listener and derived bindings. Its `onClosed` and `onDiscarded` hooks release those resources explicitly. Moves, collapse and veto do not run those hooks. A rejected factory-created editor is discarded; rejection of a directly supplied Dockable leaves cleanup to its caller. -This does not dispose the LoadedView or evict the runtime's strong Model-to-ViewModel -identity cache. See the [MVVM lifetime contract](../../fx/docs/architecture.md). +The same hooks close the editor's `ViewModelContext`, which closes the +`LoadedView` and clears its Model-to-ViewModel registrations. See the +[MVVM lifetime contract](../../fx/docs/architecture.md). `MvvmDockingTest` loads the actual example FXML and checks model/property/control edits before and after moves, object identity, bar ownership, global toolbar diff --git a/fx-example/pom.xml b/fx-example/pom.xml index 0994e23..a388ffd 100644 --- a/fx-example/pom.xml +++ b/fx-example/pom.xml @@ -31,7 +31,7 @@ com.h2databaseh2${h2.version} de.neitzel.lib - fx + fx-injection ${project.version} diff --git a/fx-example/src/designer/java/de/neitzel/fx/example/preview/AddressPreviewProvider.java b/fx-example/src/designer/java/de/neitzel/fx/example/preview/AddressPreviewProvider.java index 3e7170d..53d7689 100644 --- a/fx-example/src/designer/java/de/neitzel/fx/example/preview/AddressPreviewProvider.java +++ b/fx-example/src/designer/java/de/neitzel/fx/example/preview/AddressPreviewProvider.java @@ -2,29 +2,23 @@ package de.neitzel.fx.example.preview; import de.neitzel.fx.example.DeskApp; import de.neitzel.fx.example.model.Address; -import de.neitzel.fx.example.view.DeskController; -import de.neitzel.fx.example.view.PersonViewModel; import de.neitzel.fxdesigner.preview.PreviewProvider; import de.neitzel.fxdesigner.preview.PreviewSession; -import de.neitzel.injection.ApplicationContext; +import de.neitzel.fx.view.ViewDependencies; /** Independent samples for the nested, repeated and table-row Address components. */ -public final class AddressPreviewProvider implements PreviewProvider { +public final class AddressPreviewProvider implements PreviewProvider { @Override public Class
modelType() { return Address.class; } @Override - public PreviewSession open(String id) { + public PreviewSession open(String id) { if (!java.util.Set.of("address", "visit", "row").contains(id)) throw new IllegalArgumentException("Unknown address example: " + id); var person = DeskApp.sample(); - var context = new ApplicationContext(DeskApp.class); - // An independently previewed row still needs the parent action's state. - // No Desk.fxml is loaded and no popup listener is installed. - if ("row".equals(id)) - context.getComponent(DeskController.class).setViewModel(new PersonViewModel(person)); + var context = DeskApp.dependencies(person); return new SampleSession<>( "address".equals(id) ? person.getHome() : person.getVisits().getFirst(), context); } diff --git a/fx-example/src/designer/java/de/neitzel/fx/example/preview/DeskPreviewProvider.java b/fx-example/src/designer/java/de/neitzel/fx/example/preview/DeskPreviewProvider.java index a3811fe..a8f91ef 100644 --- a/fx-example/src/designer/java/de/neitzel/fx/example/preview/DeskPreviewProvider.java +++ b/fx-example/src/designer/java/de/neitzel/fx/example/preview/DeskPreviewProvider.java @@ -4,18 +4,19 @@ import de.neitzel.fx.example.DeskApp; import de.neitzel.fx.example.model.Person; import de.neitzel.fxdesigner.preview.PreviewProvider; import de.neitzel.fxdesigner.preview.PreviewSession; -import de.neitzel.injection.ApplicationContext; +import de.neitzel.fx.view.ViewDependencies; /** Optional test-source preview adapter; it never enters the application distribution. */ -public final class DeskPreviewProvider implements PreviewProvider { +public final class DeskPreviewProvider implements PreviewProvider { @Override public Class modelType() { return Person.class; } @Override - public PreviewSession open(String id) { + public PreviewSession open(String id) { if (!"desk".equals(id)) throw new IllegalArgumentException("Unknown desk example: " + id); - return new SampleSession<>(DeskApp.sample(), new ApplicationContext(DeskApp.class)); + var person = DeskApp.sample(); + return new SampleSession<>(person, DeskApp.dependencies(person)); } } diff --git a/fx-example/src/designer/java/de/neitzel/fx/example/preview/NotePreviewProvider.java b/fx-example/src/designer/java/de/neitzel/fx/example/preview/NotePreviewProvider.java index 23db4f4..aaf6210 100644 --- a/fx-example/src/designer/java/de/neitzel/fx/example/preview/NotePreviewProvider.java +++ b/fx-example/src/designer/java/de/neitzel/fx/example/preview/NotePreviewProvider.java @@ -4,19 +4,19 @@ import de.neitzel.fx.example.DeskApp; import de.neitzel.fx.example.model.Note; import de.neitzel.fxdesigner.preview.PreviewProvider; import de.neitzel.fxdesigner.preview.PreviewSession; -import de.neitzel.injection.ApplicationContext; +import de.neitzel.fx.view.ViewDependencies; /** Independent sample for the nested note editor. */ -public final class NotePreviewProvider implements PreviewProvider { +public final class NotePreviewProvider implements PreviewProvider { @Override public Class modelType() { return Note.class; } @Override - public PreviewSession open(String id) { + public PreviewSession open(String id) { if (!"note".equals(id)) throw new IllegalArgumentException("Unknown note example: " + id); - return new SampleSession<>( - DeskApp.sample().getHome().getNote(), new ApplicationContext(DeskApp.class)); + var person = DeskApp.sample(); + return new SampleSession<>(person.getHome().getNote(), DeskApp.dependencies(person)); } } diff --git a/fx-example/src/designer/java/de/neitzel/fx/example/preview/PreviewProvidersTest.java b/fx-example/src/designer/java/de/neitzel/fx/example/preview/PreviewProvidersTest.java index 2c3daa2..b174740 100644 --- a/fx-example/src/designer/java/de/neitzel/fx/example/preview/PreviewProvidersTest.java +++ b/fx-example/src/designer/java/de/neitzel/fx/example/preview/PreviewProvidersTest.java @@ -3,7 +3,9 @@ package de.neitzel.fx.example.preview; import static org.junit.jupiter.api.Assertions.*; import de.neitzel.fx.example.view.DeskController; +import de.neitzel.fx.example.view.VisitRow; import de.neitzel.fx.view.ViewLoader; +import de.neitzel.fx.view.ViewModelContext; import javafx.application.Platform; @@ -48,12 +50,12 @@ class PreviewProvidersTest { assertNotSame(first.model(), second.model()); assertNotSame(first.model().getHome(), second.model().getHome()); assertNotSame(first.context(), second.context()); - var view = - ViewLoader.load( - DeskController.class.getResource("Desk.fxml"), - first.model(), - first.context()); - assertNotNull(view.getRoot().lookup("#nameField")); + try (var models = new ViewModelContext()) { + var view = ViewLoader.loadWithDependencies( + DeskController.class.getResource("Desk.fxml"), + first.model(), first.context(), models); + assertNotNull(view.getRoot().lookup("#nameField")); + } assertEquals("Ada Lovelace", first.model().getName()); assertTrue(first.ready().toCompletableFuture().isDone()); assertThrows(IllegalArgumentException.class, () -> provider.open("unknown")); @@ -70,11 +72,11 @@ class PreviewProvidersTest { var visit = addresses.open("visit"); assertNotNull(visit.model().getVisitedOn()); var row = addresses.open("row"); - assertDoesNotThrow( - () -> - row.context() - .getComponent(DeskController.class) - .removeVisit(row.model())); + try (var models = new ViewModelContext()) { + var view = ViewLoader.loadComponentWithDependencies( + VisitRow.class, row.model(), row.context(), models); + assertDoesNotThrow(((VisitRow) view.getRoot())::remove); + } var note = new NotePreviewProvider().open("note"); assertEquals("Kept at home", note.model().getText()); assertThrows(IllegalArgumentException.class, () -> addresses.open("desk")); diff --git a/fx-example/src/designer/java/de/neitzel/fx/example/preview/SampleSession.java b/fx-example/src/designer/java/de/neitzel/fx/example/preview/SampleSession.java index 8e29aa7..a97046b 100644 --- a/fx-example/src/designer/java/de/neitzel/fx/example/preview/SampleSession.java +++ b/fx-example/src/designer/java/de/neitzel/fx/example/preview/SampleSession.java @@ -1,11 +1,11 @@ package de.neitzel.fx.example.preview; import de.neitzel.fxdesigner.preview.PreviewSession; -import de.neitzel.injection.ApplicationContext; +import de.neitzel.fx.view.ViewDependencies; /** The sample owns no timers, network connections or background work to release. */ -record SampleSession(M model, ApplicationContext context) - implements PreviewSession { +record SampleSession(M model, ViewDependencies context) + implements PreviewSession { @Override public void close() {} } diff --git a/fx-example/src/main/java/de/neitzel/fx/example/DeskApp.java b/fx-example/src/main/java/de/neitzel/fx/example/DeskApp.java index f0cbb25..8980384 100644 --- a/fx-example/src/main/java/de/neitzel/fx/example/DeskApp.java +++ b/fx-example/src/main/java/de/neitzel/fx/example/DeskApp.java @@ -4,19 +4,28 @@ import de.neitzel.fx.example.model.Address; import de.neitzel.fx.example.model.Note; import de.neitzel.fx.example.model.Person; import de.neitzel.fx.example.model.Role; +import de.neitzel.fx.example.view.AddressForm; import de.neitzel.fx.example.view.DeskController; +import de.neitzel.fx.example.view.NoteForm; +import de.neitzel.fx.example.view.VisitActions; +import de.neitzel.fx.example.view.VisitForm; +import de.neitzel.fx.example.view.VisitRow; +import de.neitzel.fx.injection.NeitzelViewDependencies; import de.neitzel.fx.view.LoadedView; import de.neitzel.fx.view.MessagePopup; import de.neitzel.fx.view.ViewLoader; +import de.neitzel.fx.view.ViewModelContext; import de.neitzel.injection.ApplicationContext; import de.neitzel.injection.annotation.Config; import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; +import javafx.stage.WindowEvent; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; +import java.util.Set; /** * Opens the person desk for one ordinary {@link Person}. @@ -60,6 +69,14 @@ public class DeskApp extends Application { return person; } + /** Configures one Model and shared service context for the app or a preview. */ + public static NeitzelViewDependencies dependencies(Person person) { + var context = new ApplicationContext(DeskApp.class); + context.getComponent(VisitActions.class).setPerson(person); + return new NeitzelViewDependencies(context, + Set.of(AddressForm.class, NoteForm.class, VisitForm.class, VisitRow.class)); + } + /** * Launches the desk. * @@ -76,9 +93,11 @@ public class DeskApp extends Application { */ @Override public void start(Stage stage) { - ApplicationContext context = new ApplicationContext(DeskApp.class); Person person = sample(); - LoadedView loaded = ViewLoader.load(DeskController.class.getResource("Desk.fxml"), person, context); + var models = new ViewModelContext(); + LoadedView loaded = ViewLoader.loadWithDependencies( + DeskController.class.getResource("Desk.fxml"), person, dependencies(person), models); + stage.addEventHandler(WindowEvent.WINDOW_HIDDEN, event -> models.close()); MessagePopup.showNewMessages(loaded.getViewModel()); stage.setTitle("fx example"); stage.setScene(new Scene(loaded.getRoot())); diff --git a/fx-example/src/main/java/de/neitzel/fx/example/docking/mvvm/MvvmEditor.java b/fx-example/src/main/java/de/neitzel/fx/example/docking/mvvm/MvvmEditor.java index 18211b2..ceb4bb2 100644 --- a/fx-example/src/main/java/de/neitzel/fx/example/docking/mvvm/MvvmEditor.java +++ b/fx-example/src/main/java/de/neitzel/fx/example/docking/mvvm/MvvmEditor.java @@ -3,9 +3,12 @@ package de.neitzel.fx.example.docking.mvvm; import de.neitzel.fx.docking.Dockable; import de.neitzel.fx.docking.DockableId; import de.neitzel.fx.example.model.Note; +import de.neitzel.fx.injection.NeitzelViewDependencies; import de.neitzel.fx.view.LoadedView; import de.neitzel.fx.view.ViewLoader; +import de.neitzel.fx.view.ViewModelContext; import de.neitzel.injection.ApplicationContext; +import java.util.Set; import javafx.beans.binding.Bindings; import javafx.beans.binding.StringBinding; import javafx.beans.property.Property; @@ -21,6 +24,7 @@ import lombok.Getter; /** Application adapter: one loaded View becomes ordinary Dockable content. */ public final class MvvmEditor implements AutoCloseable { @Getter private final Note model = new Note("Edit this note, then move or float its tab."); + private final ViewModelContext models = new ViewModelContext(); @Getter private final LoadedView view; @Getter private final Dockable dockable; private final Property text; @@ -35,8 +39,9 @@ public final class MvvmEditor implements AutoCloseable { @SuppressWarnings("unchecked") public MvvmEditor(String id) { - view = ViewLoader.load(MvvmEditor.class.getResource("MvvmEditor.fxml"), model, - new ApplicationContext(MvvmEditor.class)); + var dependencies = new NeitzelViewDependencies(new ApplicationContext(MvvmEditor.class), Set.of()); + view = ViewLoader.loadWithDependencies( + MvvmEditor.class.getResource("MvvmEditor.fxml"), model, dependencies, models); text = (Property) view.property("text"); TextArea input = (TextArea) view.getRoot().lookup("#text"); dockable = new Dockable(new DockableId(id), view.getRoot()); @@ -64,7 +69,7 @@ public final class MvvmEditor implements AutoCloseable { dirty.set(false); } - /** Releases this adapter's resources, not the LoadedView or global ViewModel identity cache. */ + /** Releases the editor's bindings and its managed View. */ @Override public void close() { if (released) return; released = true; @@ -76,5 +81,6 @@ public final class MvvmEditor implements AutoCloseable { status.setText("Released application listeners"); clear.setOnAction(null); clear.setDisable(true); + models.close(); } } diff --git a/fx-example/src/main/java/de/neitzel/fx/example/view/DeskController.java b/fx-example/src/main/java/de/neitzel/fx/example/view/DeskController.java index fc4b2a9..461c40a 100644 --- a/fx-example/src/main/java/de/neitzel/fx/example/view/DeskController.java +++ b/fx-example/src/main/java/de/neitzel/fx/example/view/DeskController.java @@ -95,18 +95,6 @@ public class DeskController implements HasViewModel { visits().add(created); } - /** - * Removes a visit from the list the table and Repeat are watching. - * - * @param visit the visit - */ - public void removeVisit(Address visit) { - if (visit == null) { - return; - } - visits().remove(visit); - } - /** * Adds the tag field's text to the tag list and clears the field. */ diff --git a/fx-example/src/main/java/de/neitzel/fx/example/view/VisitActions.java b/fx-example/src/main/java/de/neitzel/fx/example/view/VisitActions.java new file mode 100644 index 0000000..5421505 --- /dev/null +++ b/fx-example/src/main/java/de/neitzel/fx/example/view/VisitActions.java @@ -0,0 +1,17 @@ +package de.neitzel.fx.example.view; + +import de.neitzel.fx.example.model.Address; +import de.neitzel.fx.example.model.Person; +import jakarta.inject.Singleton; +import lombok.Setter; + +/** Removes a visit from the Model that owns the repeated forms and table rows. */ +@Singleton +public final class VisitActions { + @Setter + private Person person; + + public void remove(Address visit) { + person.getVisits().remove(visit); + } +} diff --git a/fx-example/src/main/java/de/neitzel/fx/example/view/VisitRow.java b/fx-example/src/main/java/de/neitzel/fx/example/view/VisitRow.java index 78e0926..05975d7 100644 --- a/fx-example/src/main/java/de/neitzel/fx/example/view/VisitRow.java +++ b/fx-example/src/main/java/de/neitzel/fx/example/view/VisitRow.java @@ -21,9 +21,9 @@ import lombok.RequiredArgsConstructor; public class VisitRow extends HBox { /** - * The desk controller that removes a visit from the person. + * The shared action that removes a visit from the person. */ - private final DeskController desk; + private final VisitActions visits; /** * The visit this row edits. The table sets it once. @@ -63,7 +63,7 @@ public class VisitRow extends HBox { @FXML public void remove() { if (getModel() instanceof Address address) { - desk.removeVisit(address); + visits.remove(address); } } } diff --git a/fx-example/src/test/java/de/neitzel/fx/example/DeskLoadsTest.java b/fx-example/src/test/java/de/neitzel/fx/example/DeskLoadsTest.java index 867dc31..1824256 100644 --- a/fx-example/src/test/java/de/neitzel/fx/example/DeskLoadsTest.java +++ b/fx-example/src/test/java/de/neitzel/fx/example/DeskLoadsTest.java @@ -9,7 +9,8 @@ import de.neitzel.fx.example.view.VisitForm; import de.neitzel.fx.example.view.VisitRow; import de.neitzel.fx.view.LoadedView; import de.neitzel.fx.view.ViewLoader; -import de.neitzel.injection.ApplicationContext; +import de.neitzel.fx.view.ViewDependencies; +import de.neitzel.fx.view.ViewModelContext; import javafx.application.Platform; import javafx.scene.Node; import javafx.scene.Parent; @@ -122,16 +123,13 @@ class DeskLoadsTest { /** * A second view of the same person reuses the view model, so a name edit shows on both. - *

- * The second document is only a name field. Loading the desk again would rebuild the home - * address form, and that form is the cached singleton already showing. */ @Test void secondViewReusesTheViewModel() throws Exception { onFx(() -> { Loaded first = load(); - LoadedView second = ViewLoader.load( - DeskLoadsTest.class.getResource("NameLine.fxml"), first.person(), first.context()); + LoadedView second = ViewLoader.loadWithDependencies( + DeskLoadsTest.class.getResource("NameLine.fxml"), first.person(), first.context(), first.models()); assertSame(first.view().getViewModel(), second.getViewModel()); textField(first.root(), "nameField").setText("Grace"); assertEquals("Grace", first.person().getName()); @@ -261,16 +259,15 @@ class DeskLoadsTest { onFx(() -> { Loaded loaded = load(); Parent root = loaded.root(); - DeskController desk = loaded.context().getComponent(DeskController.class); - desk.leaveNote(); + fire(root, "Leave a note"); assertEquals(de.neitzel.fx.view.Message.Severity.INFO, loaded.view().getViewModel().getLatestMessage().getSeverity()); assertEquals("The model already has the name Ada Lovelace.", text(root, "noticeLabel")); - desk.leaveWarning(); + fire(root, "Leave a warning"); assertEquals(de.neitzel.fx.view.Message.Severity.WARN, loaded.view().getViewModel().getLatestMessage().getSeverity()); assertEquals("Check the age before leaving the desk.", text(root, "noticeLabel")); - desk.leaveFatal(); + fire(root, "Leave a fatal notice"); assertEquals(de.neitzel.fx.view.Message.Severity.FATAL, loaded.view().getViewModel().getLatestMessage().getSeverity()); assertEquals("The desk cannot store this person.", text(root, "noticeLabel")); @@ -300,9 +297,10 @@ class DeskLoadsTest { * * @param person the model * @param view the loaded view - * @param context the container + * @param context the adapter + * @param models the ViewModel context */ - private record Loaded(Person person, LoadedView view, ApplicationContext context) { + private record Loaded(Person person, LoadedView view, ViewDependencies context, ViewModelContext models) { /** * Returns the scene-graph root. @@ -321,9 +319,16 @@ class DeskLoadsTest { */ private static Loaded load() { Person person = DeskApp.sample(); - ApplicationContext context = new ApplicationContext(DeskApp.class); - LoadedView view = ViewLoader.load(DeskController.class.getResource("Desk.fxml"), person, context); - return new Loaded(person, view, context); + var context = DeskApp.dependencies(person); + var models = new ViewModelContext(); + var view = ViewLoader.loadWithDependencies( + DeskController.class.getResource("Desk.fxml"), person, context, models); + return new Loaded(person, view, context, models); + } + + private static void fire(Parent root, String text) { + root.lookupAll(".button").stream().filter(Button.class::isInstance).map(Button.class::cast) + .filter(button -> text.equals(button.getText())).findFirst().orElseThrow().fire(); } /** diff --git a/fx-injection/README.md b/fx-injection/README.md new file mode 100644 index 0000000..56b7725 --- /dev/null +++ b/fx-injection/README.md @@ -0,0 +1,64 @@ +# Neitzel DI adapter for FX + +The adapter is available in the separated `1.0.7-SNAPSHOT` development +checkout. Install it with `./mvnw -pl fx-injection -am install` from the +NeitzelLib root, using JDK 25 and the same local Maven repository as your +application. + +```xml + + de.neitzel.lib + fx-injection + 1.0.7-SNAPSHOT + +``` + +Use the same version for all NeitzelLib modules. The adapter resolves `fx`, +`injection` and its scanner dependencies. Applications with their own +`ViewDependencies` can depend on `fx` directly. + +Import the adapter from `de.neitzel.fx.injection`, the container from +`de.neitzel.injection` and the loader and Model context from +`de.neitzel.fx.view`. + +```java +var services = new ApplicationContext(MyApplication.class); +var dependencies = new NeitzelViewDependencies(services, Set.of(AddressForm.class, VisitRow.class)); +var models = new ViewModelContext(); +var view = ViewLoader.loadWithDependencies(fxml, model, dependencies, models); +stage.setScene(new Scene(view.getRoot())); +stage.addEventHandler(WindowEvent.WINDOW_HIDDEN, event -> models.close()); +``` + +The registration set contains the exact FXML Component classes, including +those used by Repeat and Table. The adapter asks the context for a fresh +controller or Component and gives FX the corresponding release action. +The release action closes UI instances that implement `AutoCloseable`. +Converters and Localizer come from the context's ordinary lookup. The adapter +reports a missing service as an empty result and propagates lookup or +creation errors. The application owns the context and its shared services. + +The JPMS module name is `de.neitzel.fx.injection`. Named applications +keep the package access needed by FXML and Neitzel's package scanner. +Declare `requires de.neitzel.fx.injection` for the adapter and `requires fx` and +`requires injection` for their directly imported types. The Neitzel package +scanner still needs access to its scanned packages in named applications. + +## Migrate an existing FX application + +Use `ViewLoader.loadWithDependencies(..., dependencies, models)`, +`ViewLoader.loadComponentWithDependencies(..., dependencies, models)`, +and `FxFixture.loadWithDependencies(..., dependencies)` for the new +FX artifacts. Replace the previous public `ApplicationContext` loader +calls and recompile. Retain the Model context with its window or +dockable and close it when that owner ends. Each View load gets its own +controller and Components. If a row previously called a cached controller, +inject the shared action it needs. The [Person Desk](../fx-example/README.md) +does this with `VisitActions`. + +A Designer provider on the new artifacts returns the configured adapter +from `PreviewSession.context()` and declares `ViewDependencies` as its +context type. Existing providers returning `ApplicationContext` continue to +run with compatible older FX artifacts such as 1.0.6. Consumers of the standalone +[Neitzel injection container](../injection/README.md) can keep using its +existing API. diff --git a/fx-injection/pom.xml b/fx-injection/pom.xml new file mode 100644 index 0000000..bfc2640 --- /dev/null +++ b/fx-injection/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + de.neitzel.lib + neitzellib + 1.0.7-SNAPSHOT + + fx-injection + + + de.neitzel.lib + fx + ${project.version} + + + de.neitzel.lib + injection + ${project.version} + + + de.neitzel.lib + fx-test + ${project.version} + test + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + de.neitzel.fx.injection + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + Headless + + + + + + diff --git a/fx-injection/src/main/java/de/neitzel/fx/injection/NeitzelViewDependencies.java b/fx-injection/src/main/java/de/neitzel/fx/injection/NeitzelViewDependencies.java new file mode 100644 index 0000000..bca6a91 --- /dev/null +++ b/fx-injection/src/main/java/de/neitzel/fx/injection/NeitzelViewDependencies.java @@ -0,0 +1,53 @@ +package de.neitzel.fx.injection; + +import de.neitzel.fx.view.ViewDependencies; +import de.neitzel.fx.view.ViewObject; +import de.neitzel.injection.ApplicationContext; +import de.neitzel.injection.MissingComponentException; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + +/** Connects managed FX Views to an application-owned Neitzel injection context. */ +public record NeitzelViewDependencies(ApplicationContext context, Set> components) + implements ViewDependencies { + + /** Creates an adapter with the concrete classes used as FXML Components and rows. */ + public NeitzelViewDependencies { + Objects.requireNonNull(context, "Application context"); + components = Set.copyOf(components); + } + + @Override + public boolean isComponent(Class type) { + return components.contains(type); + } + + @Override + public Optional findService(Class type) { + try { + return Optional.of(context.getComponent(type)); + } catch (MissingComponentException missing) { + if (missing.getComponentType() == type) return Optional.empty(); + throw missing; + } + } + + @Override + public ViewObject createViewObject(Class type) { + T instance = context.createComponent(type); + return new ViewObject<>(instance, () -> release(instance)); + } + + private static void release(Object instance) { + if (instance instanceof AutoCloseable closeable) { + try { + closeable.close(); + } catch (RuntimeException failure) { + throw failure; + } catch (Exception failure) { + throw new IllegalStateException("Could not close " + instance.getClass().getName(), failure); + } + } + } +} diff --git a/fx-injection/src/test/java/de/neitzel/fx/injection/NeitzelViewDependenciesTest.java b/fx-injection/src/test/java/de/neitzel/fx/injection/NeitzelViewDependenciesTest.java new file mode 100644 index 0000000..ecd4dcd --- /dev/null +++ b/fx-injection/src/test/java/de/neitzel/fx/injection/NeitzelViewDependenciesTest.java @@ -0,0 +1,126 @@ +package de.neitzel.fx.injection; + +import de.neitzel.fx.i18n.Localizer; +import de.neitzel.fx.injection.fixture.Card; +import de.neitzel.fx.injection.fixture.Controller; +import de.neitzel.fx.injection.fixture.Entry; +import de.neitzel.fx.injection.fixture.Lifecycle; +import de.neitzel.fx.test.FxFixture; +import de.neitzel.fx.test.FxTest; +import de.neitzel.fx.view.ViewLoader; +import de.neitzel.fx.view.ViewModelContext; +import de.neitzel.injection.ApplicationContext; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import javafx.scene.control.Label; +import javafx.scene.control.ScrollPane; +import javafx.scene.layout.VBox; +import lombok.Getter; +import lombok.Setter; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@FxTest +class NeitzelViewDependenciesTest { + @Getter + @Setter + public static final class Model { + private String name = "Ada"; + private List entries = new ArrayList<>(List.of(new Entry())); + } + + @Test + void loadsRepeatTableAndStandaloneComponentWithOneApplicationContext(FxFixture fx) throws Exception { + fx.run(() -> { + var context = new ApplicationContext(Controller.class); + var lifecycle = context.getComponent(Lifecycle.class); + context.addSingleton(Localizer.class, new Localizer(Locale.ENGLISH, Locale.ENGLISH, + new Localizer.Catalog(Controller.class, "View"))); + var dependencies = new NeitzelViewDependencies(context, Set.of(Card.class)); + var cached = context.getComponent(Card.class); + assertSame(cached, context.getComponent(VBox.class)); + assertFalse(dependencies.isComponent(VBox.class)); + try (var models = new ViewModelContext()) { + var model = new Model(); + var fxml = Controller.class.getResource("View.fxml"); + var first = ViewLoader.loadWithDependencies(fxml, model, dependencies, models); + var second = ViewLoader.loadWithDependencies(fxml, new Model(), dependencies, models); + assertEquals(VBox.class, first.getRoot().getClass()); + var caption = (Label) first.getRoot().lookup("#caption"); + assertEquals("[Ada]", caption.getText()); + assertEquals("Localized", caption.getAccessibleText()); + var controller = (Controller) caption.getUserData(); + var other = (Controller) second.getRoot().lookup("#caption").getUserData(); + assertNotSame(controller, other); + assertSame(lifecycle, controller.getLifecycle()); + assertSame(lifecycle, other.getLifecycle()); + var embedded = (Card) first.getRoot().lookup("#card"); + var repeated = (Card) ((VBox) first.getRoot().lookup("#repeat")).getChildren().getFirst(); + var table = first.getRoot().lookup("#table"); + var rows = (VBox) ((ScrollPane) table.lookup(".table-scroll")).getContent(); + var row = (Card) rows.getChildren().getFirst(); + assertNotSame(cached, embedded); + assertNotSame(embedded, repeated); + assertNotSame(repeated, row); + model.getEntries().clear(); + assertEquals(1, lifecycle.closeCount(repeated)); + assertEquals(1, lifecycle.closeCount(row)); + + var separate = ViewLoader.loadComponentWithDependencies(Card.class, new Entry(), dependencies, models); + assertEquals("Ada", ((Label) separate.getRoot().lookup("#name")).getText()); + separate.close(); + assertEquals(1, lifecycle.closeCount(separate.getRoot())); + first.close(); + first.close(); + assertEquals(1, lifecycle.closeCount(embedded)); + assertEquals(1, lifecycle.closeCount(controller)); + assertEquals(0, lifecycle.closeCount(other)); + assertSame(cached, context.getComponent(Card.class)); + } + }); + } + + @Test + void rollsBackAndDistinguishesMissingServicesFromOverrides(FxFixture fx) throws Exception { + fx.run(() -> { + var failedLookup = new IllegalArgumentException("Lookup override failed"); + var context = new ApplicationContext(Controller.class) { + @Override + public T getComponent(Class type) { + if (type == String.class) return type.cast("override"); + if (type == Integer.class) throw failedLookup; + return super.getComponent(type); + } + }; + var dependencies = new NeitzelViewDependencies(context, Set.of(Card.class)); + assertTrue(dependencies.findService(Localizer.class).isEmpty()); + assertEquals("override", dependencies.findService(String.class).orElseThrow()); + assertSame(failedLookup, assertThrows(IllegalArgumentException.class, + () -> dependencies.findService(Integer.class))); + var acquired = new ArrayList<>(); + var tracking = new de.neitzel.fx.view.ViewDependencies() { + public boolean isComponent(Class type) { return dependencies.isComponent(type); } + + public java.util.Optional findService(Class type) { + return dependencies.findService(type); + } + + public de.neitzel.fx.view.ViewObject createViewObject(Class type) { + var found = dependencies.createViewObject(type); + acquired.add(found.instance()); + return found; + } + }; + try (var models = new ViewModelContext()) { + assertThrows(IllegalStateException.class, () -> ViewLoader.loadWithDependencies( + Controller.class.getResource("Invalid.fxml"), new Model(), tracking, models)); + } + var lifecycle = context.getComponent(Lifecycle.class); + assertEquals(2, acquired.size()); + assertTrue(acquired.stream().allMatch(value -> lifecycle.closeCount(value) == 1)); + }); + } +} diff --git a/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Card.java b/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Card.java new file mode 100644 index 0000000..f921c48 --- /dev/null +++ b/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Card.java @@ -0,0 +1,28 @@ +package de.neitzel.fx.injection.fixture; + +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import javafx.beans.property.ObjectProperty; +import javafx.beans.property.SimpleObjectProperty; +import javafx.scene.layout.VBox; + +@Singleton +public final class Card extends VBox implements AutoCloseable { + private final Lifecycle lifecycle; + private final ObjectProperty model = new SimpleObjectProperty<>(this, "model"); + + @Inject + public Card(Lifecycle lifecycle) { + this.lifecycle = lifecycle; + lifecycle.opened(this); + } + + public ObjectProperty modelProperty() { return model; } + + public Entry getModel() { return model.get(); } + + public void setModel(Entry entry) { model.set(entry); } + + @Override + public void close() { lifecycle.closed(this); } +} diff --git a/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Controller.java b/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Controller.java new file mode 100644 index 0000000..1573829 --- /dev/null +++ b/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Controller.java @@ -0,0 +1,32 @@ +package de.neitzel.fx.injection.fixture; + +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import javafx.scene.control.Label; +import javafx.fxml.FXML; +import lombok.Getter; + +@Singleton +public final class Controller implements AutoCloseable { + @Getter + private final Lifecycle lifecycle; + + @FXML + private Label caption; + + @Inject + public Controller(Lifecycle lifecycle) { + this.lifecycle = lifecycle; + lifecycle.opened(this); + } + + @FXML + private void initialize() { + caption.setUserData(this); + } + + @Override + public void close() { + lifecycle.closed(this); + } +} diff --git a/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Entry.java b/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Entry.java new file mode 100644 index 0000000..8fe1caf --- /dev/null +++ b/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Entry.java @@ -0,0 +1,12 @@ +package de.neitzel.fx.injection.fixture; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@RequiredArgsConstructor +public final class Entry { + private String name = "Ada"; +} diff --git a/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/FormatName.java b/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/FormatName.java new file mode 100644 index 0000000..32b9fdd --- /dev/null +++ b/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/FormatName.java @@ -0,0 +1,13 @@ +package de.neitzel.fx.injection.fixture; + +import de.neitzel.fx.view.Converter; +import jakarta.inject.Singleton; + +@Singleton +public final class FormatName implements Converter { + @Override + public Object toControlValue(Object value) { return "[" + value + "]"; } + + @Override + public Object toAttributeValue(Object value) { return value; } +} diff --git a/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Lifecycle.java b/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Lifecycle.java new file mode 100644 index 0000000..ec169c6 --- /dev/null +++ b/fx-injection/src/test/java/de/neitzel/fx/injection/fixture/Lifecycle.java @@ -0,0 +1,16 @@ +package de.neitzel.fx.injection.fixture; + +import jakarta.inject.Singleton; +import java.util.IdentityHashMap; +import java.util.Map; + +@Singleton +public final class Lifecycle { + private final Map counts = new IdentityHashMap<>(); + + public void opened(Object instance) { counts.put(instance, 0); } + + public void closed(Object instance) { counts.computeIfPresent(instance, (key, count) -> count + 1); } + + public int closeCount(Object instance) { return counts.get(instance); } +} diff --git a/fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/Card.fxml b/fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/Card.fxml new file mode 100644 index 0000000..854f7fe --- /dev/null +++ b/fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/Card.fxml @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/Invalid.fxml b/fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/Invalid.fxml new file mode 100644 index 0000000..7fda66d --- /dev/null +++ b/fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/Invalid.fxml @@ -0,0 +1,7 @@ + + + + + diff --git a/fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/View.fxml b/fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/View.fxml new file mode 100644 index 0000000..fbe357b --- /dev/null +++ b/fx-injection/src/test/resources/de/neitzel/fx/injection/fixture/View.fxml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + +

- * An unknown type, such as a JavaFX control, makes {@link ApplicationContext#getComponent} - * throw {@link IllegalArgumentException}. This method returns null so FXML constructs that - * type itself. A Component that extends a JavaFX class is also left to FXML when the document - * names that JavaFX class: the container would otherwise hand back the Component. A failure - * while creating a known Component is not caught. The first Component of a class in one load - * is the cached singleton. A second Component of that class is a new injected instance, so the - * document can show two of them. - * - * @param type the type FXML is about to construct - * @param context the container that creates Components - * @return a builder for a Component, or {@code null} when the type is not a Component - */ - static Builder builder(Class type, ApplicationContext context, ViewLifetime owner) { - Object component; - try { - component = owner.managed() ? context.createComponent(type) : context.getComponent(type); - } catch (IllegalArgumentException notAComponent) { - return null; - } - if (component.getClass() != type) { - return null; - } - if (!owner.managed() && !LoadSession.claimFirst(type)) { - component = context.createComponent(type.asSubclass(Object.class)); - } - return new ComponentBuilder(component, context, owner.child()); + /** Returns a Component builder or leaves the requested type to JavaFX. */ + static Builder builder(Class type, ViewInstances context, ViewLifetime owner) { + return context.isComponent(type) ? new ComponentBuilder(type, context, owner.child()) : null; } /** @@ -74,10 +47,10 @@ final class Components { */ @RequiredArgsConstructor(access = AccessLevel.PRIVATE) private static final class ComponentBuilder extends AbstractMap implements Builder { - /** The injected instance. */ - private final Object component; + /** The exact Component class declared by FXML. */ + private final Class type; /** The context used to load its document. */ - private final ApplicationContext context; + private final ViewInstances context; private final ViewLifetime lifetime; /** Values already resolved by the containing FXMLLoader. */ private final Map values = new LinkedHashMap<>(); @@ -108,7 +81,7 @@ final class Components { */ @Override public Object build() { - Object result = load(component, context, lifetime); + Object result = load(context.createComponent(type, lifetime), context, lifetime); if (!values.isEmpty()) { // A second fx:root load uses the public FXMLLoader API for bean setters, // enum/numeric coercion and diagnostics, without depending on BeanAdapter @@ -137,19 +110,9 @@ final class Components { } } - /** - * Creates a new Component and loads its document. - *

- * The instance is not the cached singleton. Its dependencies still come from - * {@link ApplicationContext#getComponent}. Bindings wait until {@link #setModel} runs. - * - * @param type the Component class - * @param context the container that creates the instance and its dependencies - * @return the loaded Component - */ - static Object fresh(Class type, ApplicationContext context, ViewLifetime lifetime) { - Object component = context.createComponent(type.asSubclass(Object.class)); - return load(component, context, lifetime); + /** Creates a fresh Component and loads its document before setting its Model. */ + static Object fresh(Class type, ViewInstances context, ViewLifetime lifetime) { + return load(context.component(type, lifetime), context, lifetime); } /** @@ -161,10 +124,6 @@ final class Components { * @param model the Model instance */ static void setModel(Object component, Object model, ViewLifetime lifetime) { - if (!lifetime.managed()) { - modelProperty(component).setValue(model); - return; - } LoadSession session = LoadSession.nest(); try { modelProperty(component).setValue(model); @@ -181,8 +140,7 @@ final class Components { * @param context the container that creates nested Components * @return the loaded Component */ - private static Object load(Object component, ApplicationContext context, ViewLifetime lifetime) { - lifetime.ownController(component); + private static Object load(Object component, ViewInstances context, ViewLifetime lifetime) { Class type = component.getClass(); String document = type.getSimpleName() + ".fxml"; URL fxml = type.getResource(document); @@ -195,11 +153,11 @@ final class Components { FxmlHandlers.observe(loader, lifetime); loader.setRoot(component); loader.setController(component); - loader.setControllerFactory(nestedType -> ViewLoader.createController(context, nestedType, lifetime)); + loader.setControllerFactory(nestedType -> context.controller(nestedType, lifetime)); loader.setBuilderFactory(nestedType -> builder(nestedType, context, lifetime)); loader.load(); nested.checkFailure(); - if (lifetime.managed() && component instanceof Node node) { + if (component instanceof Node node) { node.getProperties().put(Components.class, Boolean.TRUE); lifetime.own(() -> node.getProperties().remove(Components.class)); } @@ -221,7 +179,7 @@ final class Components { * @param context the container that creates a named Converter */ private static void watchModel(Object component, List lists, Map namespace, - ApplicationContext context, ViewLifetime lifetime) { + ViewInstances context, ViewLifetime lifetime) { Property model = modelProperty(component); boolean[] applied = {false}; lifetime.listen(model, (observable, oldValue, newValue) -> { @@ -239,10 +197,10 @@ final class Components { for (BindingList list : lists) { list.apply(namespace, viewModel, component, root, context, lifetime); } - if (lifetime.managed()) Table.openAll(root, viewModel, context, lifetime); + Table.openAll(root, viewModel, context, lifetime); } catch (RuntimeException | Error failure) { lifetime.rollback(failure); - if (!lifetime.managed() || !LoadSession.recordFailure(failure)) { + if (!LoadSession.recordFailure(failure)) { throw failure; } } diff --git a/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java b/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java index 564d161..0f36a6d 100644 --- a/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java +++ b/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java @@ -1,6 +1,5 @@ package de.neitzel.fx.view; -import de.neitzel.injection.ApplicationContext; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; @@ -33,7 +32,7 @@ final class DirectBindingApplier { * @param context the container that creates a named Converter */ static void apply(Map namespace, Object viewModel, DirectBinding binding, - ApplicationContext context, ViewLifetime lifetime) { + ViewInstances context, ViewLifetime lifetime) { Object control = namespace.get(binding.getControl()); if (control == null) { throw new IllegalArgumentException("No control \"" + binding.getControl() + "\""); @@ -82,7 +81,7 @@ final class DirectBindingApplier { /** Connects a named observable to the View when its accessor exposes no writable property. */ private static void alignReadOnly(Map namespace, Property control, Resolved resolved, - DirectBinding binding, ApplicationContext context, ViewLifetime lifetime) { + DirectBinding binding, ViewInstances 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() @@ -292,10 +291,10 @@ final class DirectBindingApplier { * @param className the Converter class name * @return the Converter */ - private static Converter converter(ApplicationContext context, String className) { + private static Converter converter(ViewInstances context, String className) { try { Class type = Class.forName(className); - Object instance = context.getComponent(type.asSubclass(Object.class)); + Object instance = context.requiredService(type); if (!(instance instanceof Converter created)) { throw new IllegalArgumentException("Not a converter: " + className); } diff --git a/fx/src/main/java/de/neitzel/fx/view/FxmlHandlers.java b/fx/src/main/java/de/neitzel/fx/view/FxmlHandlers.java index b8f5332..b2cd0c0 100644 --- a/fx/src/main/java/de/neitzel/fx/view/FxmlHandlers.java +++ b/fx/src/main/java/de/neitzel/fx/view/FxmlHandlers.java @@ -20,7 +20,7 @@ final class FxmlHandlers implements LoadListener { } static void observe(FXMLLoader loader, ViewLifetime lifetime) { - if (lifetime.managed()) loader.setLoadListener(new FxmlHandlers(lifetime)); + loader.setLoadListener(new FxmlHandlers(lifetime)); } @Override diff --git a/fx/src/main/java/de/neitzel/fx/view/LoadSession.java b/fx/src/main/java/de/neitzel/fx/view/LoadSession.java index 4f6dd5c..d94d9b6 100644 --- a/fx/src/main/java/de/neitzel/fx/view/LoadSession.java +++ b/fx/src/main/java/de/neitzel/fx/view/LoadSession.java @@ -3,9 +3,7 @@ package de.neitzel.fx.view; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; -import java.util.HashSet; import java.util.List; -import java.util.Set; /** * Holds the binding lists instantiated while one View is loading. @@ -27,11 +25,6 @@ final class LoadSession { */ private final List bindingLists = new ArrayList<>(); - /** - * Component classes already built during the outermost load. - */ - private final Set> built = new HashSet<>(); - private Throwable bindingFailure; // JavaFX reports exceptions from a property listener to the thread's uncaught handler. @@ -105,23 +98,6 @@ final class LoadSession { stack.peek().bindingLists.add(bindingList); } - /** - * Records the first Component of {@code type} built during this load. - *

- * Nested documents share the outermost session, so a second Component of the same class - * anywhere in the load is not the first. - * - * @param type the Component class - * @return {@code true} when this is the first time that class is built during the load - */ - static boolean claimFirst(Class type) { - Deque stack = STACK.get(); - if (stack == null || stack.isEmpty()) { - return true; - } - return stack.peekLast().built.add(type); - } - /** * Returns the lists registered during this session, in document order. * diff --git a/fx/src/main/java/de/neitzel/fx/view/RepeatApplier.java b/fx/src/main/java/de/neitzel/fx/view/RepeatApplier.java index 4a0219a..0d4f2f5 100644 --- a/fx/src/main/java/de/neitzel/fx/view/RepeatApplier.java +++ b/fx/src/main/java/de/neitzel/fx/view/RepeatApplier.java @@ -1,6 +1,5 @@ package de.neitzel.fx.view; -import de.neitzel.injection.ApplicationContext; import javafx.beans.property.Property; import javafx.collections.ObservableList; import javafx.scene.Node; @@ -24,10 +23,10 @@ final class RepeatApplier { /** * Fills the named pane with one new Component for each element, in list order. *

- * Each Component is a new injected instance. The cached singleton of that class is left - * in place. The child's model property is the element. Adding or removing an element - * adds or removes the matching child. The list is the one the entity holds, so a change - * on either side is visible in the pane. + * The adapter creates a fresh Component for each occurrence. Its model property is the + * element. Adding an element loads a child. Removing one releases that child's View. + * The list is the one the entity holds, so a change on either side is visible in the pane. + * The parent's View lifetime also owns the remaining children. * * @param namespace objects addressed by {@code fx:id} * @param viewModel the ViewModel for this View, or a replacement that exposes the collection by name @@ -35,7 +34,7 @@ final class RepeatApplier { * @param context the container that creates each Component */ static void apply(Map namespace, Object viewModel, Repeat repeat, - ApplicationContext context, ViewLifetime lifetime) { + ViewInstances context, ViewLifetime lifetime) { Object named = namespace.get(repeat.getPane()); if (!(named instanceof Pane pane)) { throw new IllegalArgumentException("No pane \"" + repeat.getPane() + "\""); @@ -82,7 +81,7 @@ final class RepeatApplier { * @param values the collection */ @SuppressWarnings("unchecked") - private static void listen(Pane pane, Class type, ApplicationContext context, ObservableList values, + private static void listen(Pane pane, Class type, ViewInstances context, ObservableList values, ViewLifetime lifetime, int offset, List children) { ObservableList elements = (ObservableList) values; lifetime.listen(elements, change -> { @@ -113,7 +112,7 @@ final class RepeatApplier { * @param element the Model instance * @return the loaded Component */ - private static RepeatedChild child(Class type, ApplicationContext context, Object element, + private static RepeatedChild child(Class type, ViewInstances context, Object element, ViewLifetime owner) { ViewLifetime lifetime = owner.child(); try { diff --git a/fx/src/main/java/de/neitzel/fx/view/Table.java b/fx/src/main/java/de/neitzel/fx/view/Table.java index 5c1dca0..046fb51 100644 --- a/fx/src/main/java/de/neitzel/fx/view/Table.java +++ b/fx/src/main/java/de/neitzel/fx/view/Table.java @@ -1,6 +1,5 @@ package de.neitzel.fx.view; -import de.neitzel.injection.ApplicationContext; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -232,7 +231,7 @@ public class Table extends VBox { /** * The container that creates Rows. */ - private ApplicationContext context; + private ViewInstances context; /** * The Row class. @@ -363,7 +362,7 @@ public class Table extends VBox { * @param viewModel the ViewModel for this View * @param context the container that creates each Row */ - static void openAll(Parent root, Object viewModel, ApplicationContext context, ViewLifetime lifetime) { + static void openAll(Parent root, Object viewModel, ViewInstances context, ViewLifetime lifetime) { walk(root, root, viewModel, context, lifetime); } @@ -373,7 +372,7 @@ public class Table extends VBox { * @param viewModel the ViewModel for this View * @param context the container that creates each Row */ - void open(Object viewModel, ApplicationContext context, ViewLifetime owner) { + void open(Object viewModel, ViewInstances context, ViewLifetime owner) { if (resultMode) { return; } @@ -1339,7 +1338,7 @@ public class Table extends VBox { node.addEventFilter(MouseEvent.MOUSE_CLICKED, select); rowLifetime.own(() -> node.removeEventFilter(MouseEvent.MOUSE_CLICKED, select)); watchEdits(node, rowLifetime); - if (rowLifetime.managed()) rowLifetimes.put(element, rowLifetime); + rowLifetimes.put(element, rowLifetime); return node; } catch (RuntimeException | Error failure) { rowLifetime.rollback(failure); @@ -1566,7 +1565,7 @@ public class Table extends VBox { * @param viewModel the ViewModel for this View * @param context the container that creates each Row */ - private static void walk(Node node, Parent root, Object viewModel, ApplicationContext context, + private static void walk(Node node, Parent root, Object viewModel, ViewInstances context, ViewLifetime lifetime) { if (node != root && Components.ownsBindings(node)) return; if (node instanceof Table table) { diff --git a/fx/src/main/java/de/neitzel/fx/view/ViewDependencies.java b/fx/src/main/java/de/neitzel/fx/view/ViewDependencies.java new file mode 100644 index 0000000..66cc349 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/ViewDependencies.java @@ -0,0 +1,22 @@ +package de.neitzel.fx.view; + +import java.util.Optional; + +/** Supplies a View's objects from the application's dependency injection configuration. */ +public interface ViewDependencies { + + /** Checks whether the exact FXML type is a Component, without creating an instance. */ + boolean isComponent(Class type); + + /** + * Looks up an application-owned service such as a Converter or Localizer. + * Report lookup and creation failures as exceptions. An empty result means the service is absent. + */ + Optional findService(Class type); + + /** + * Creates a fresh Controller or Component and supplies its release action. + * The adapter owns any partial allocations until it returns the object. + */ + ViewObject createViewObject(Class type); +} diff --git a/fx/src/main/java/de/neitzel/fx/view/ViewInstances.java b/fx/src/main/java/de/neitzel/fx/view/ViewInstances.java new file mode 100644 index 0000000..9f72e76 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/ViewInstances.java @@ -0,0 +1,66 @@ +package de.neitzel.fx.view; + +import de.neitzel.fx.i18n.Localizer; + +import java.util.Objects; +import java.util.Optional; + +/** Instance selection shared by the FXML factories and the binding appliers. */ +record ViewInstances(ViewDependencies dependencies) { + + ViewInstances { + Objects.requireNonNull(dependencies, "View dependencies"); + } + + Object controller(Class type, ViewLifetime lifetime) { + return create(type, lifetime); + } + + boolean isComponent(Class type) { + return dependencies.isComponent(type); + } + + Object component(Class type, ViewLifetime lifetime) { + if (!dependencies.isComponent(type)) { + throw new IllegalArgumentException("No Component registered for " + type.getName()); + } + return createComponent(type, lifetime); + } + + Object createComponent(Class type, ViewLifetime lifetime) { + Object instance = create(type, lifetime); + if (instance.getClass() != type) { + throw new IllegalArgumentException("Expected exact Component type " + type.getName() + + ", got " + instance.getClass().getName()); + } + return instance; + } + + private Object create(Class type, ViewLifetime lifetime) { + try { + ViewObject view = dependencies.createViewObject(type); + // Each instance owns a distinct cleanup entry even if actions are shared. + lifetime.own(() -> view.release().run()); + return type.cast(view.instance()); + } catch (RuntimeException failure) { + throw new IllegalStateException("Could not create View object " + type.getName(), failure); + } + } + + Object requiredService(Class type) { + return service(type) + .orElseThrow(() -> new IllegalArgumentException("No View service for " + type.getName())); + } + + Localizer localizer() { + return service(Localizer.class).orElse(null); + } + + private Optional service(Class type) { + try { + return dependencies.findService(type); + } catch (RuntimeException failure) { + throw new IllegalStateException("Could not resolve View service " + type.getName(), failure); + } + } +} diff --git a/fx/src/main/java/de/neitzel/fx/view/ViewLifetime.java b/fx/src/main/java/de/neitzel/fx/view/ViewLifetime.java index 07db531..97180cd 100644 --- a/fx/src/main/java/de/neitzel/fx/view/ViewLifetime.java +++ b/fx/src/main/java/de/neitzel/fx/view/ViewLifetime.java @@ -22,31 +22,11 @@ final class ViewLifetime implements AutoCloseable { 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); - } - }); + if (closed) { + removal.run(); + } else { + cleanup.addLast(removal); } } diff --git a/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java b/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java index 8f2d174..0c49e9f 100644 --- a/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java +++ b/fx/src/main/java/de/neitzel/fx/view/ViewLoader.java @@ -2,12 +2,12 @@ package de.neitzel.fx.view; import de.neitzel.fx.i18n.Localizer; import de.neitzel.fx.i18n.Messages; -import de.neitzel.injection.ApplicationContext; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import java.io.IOException; import java.net.URL; +import java.util.Objects; /** * Loads a View for one Model instance. @@ -21,93 +21,35 @@ public final class ViewLoader { } /** - * Loads a View for one Model instance. - *

- * Reuses the ViewModel already built for {@code model}, or builds one, then loads {@code fxml} - * and applies binding elements declared in {@code fx:define}. A Computed binding writes a - * Controller method result to a control and does not write the Model. Direction {@code both} - * keeps the control and the Attribute - * aligned, so editing the control writes the Attribute immediately. Direction {@code view} - * shows the Attribute and follows later property changes without writing the Attribute back. - * Direction {@code model} shows the current value, writes the Attribute when the control - * changes, and does not push later property changes to the control. A Path of one name is an - * Attribute of this View's ViewModel. Further names step into a nested ViewModel, and the - * direction applies to the last name. When a Complex attribute along the Path is null, the - * control and the Model keep their current values. A collection of simple values is one shared - * list: the Direct binding sets the control property to that - * {@link javafx.collections.ObservableList}, so an add or remove is visible on both sides. - * A path that is not a read-write Attribute fails the load. The context creates a Controller - * the document names, and injects that Controller's services. When the document names no - * Controller, the library supplies one. A Controller that implements {@link HasViewModel} - * receives the ViewModel after construction and before bindings. {@link ViewModelClass} on that - * Controller names the ViewModel class. The library constructs it with the Model instance - * before load. With no annotation, the library builds the generic ViewModel. The first View of a - * Model instance fixes that class. A later View that names a different class fails the load, - * and the earlier View stays as it was. A later View that names none reuses the ViewModel. - * The context creates a - * Converter when a Direct binding names one. A converter that cannot produce a value - * keeps the previous value and records one error Message on the ViewModel that owns the last - * Attribute, with that Attribute's name as the source. A parent carries a copy with the source - * extended. It does not fail the load. - * A parent document names a Component class as an element. The context creates that Component - * and injects its services. A second element of the same class is another injected instance, - * and the cached singleton stays the first one. The Component document {@code ClassName.fxml}, - * in the same package, is loaded with the Component as {@code fx:root} and as the Controller. - * That document's bindings are not applied during this load. They run when the Component's - * model property becomes a non-null Model. {@link ViewModelClass} on the Component names the - * ViewModel class for that Model. A Component that implements {@link HasViewModel} receives - * that ViewModel after the property is set and before those bindings run. - * A {@link Repeat} in the same list names a pane, a Component class, and a collection - * Attribute. One new Component child is placed in that pane for each Model instance, in list - * order. Adding or removing an element updates that pane. Those instances are created with - * {@link de.neitzel.injection.ApplicationContext#createComponent} so the cached singleton of - * that class stays in place. A collection of Model instances is an - * {@link javafx.collections.ObservableList} of those instances, shared with the entity. - * Selection is a separate Attribute of the parent Model. Null means nothing is selected. - * A Direct binding can tie a control property to that Attribute. The repeated Component does - * not store the selection. - * Loading does not open a popup or fill a status bar. A Direct binding whose path is - * {@code latestMessage} shows the latest Message text. {@link MessagePopup#showNewMessages} - * shows each newly added Message in a dialog. - * - * @param fxml the FXML document - * @param model the Model instance - * @param context the application context - * @return the loaded View - * @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) { - return load(fxml, model, context, new ViewLifetime(ViewModels.LEGACY)); - } - - /** - * 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. - * + * Loads FXML with application-supplied dependencies and a managed Model context. + * Load and close the View on the JavaFX application thread. The caller owns the dependencies. * @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 + * @param dependencies the adapter for View objects and services + * @param models the Model context that owns the View * @return the loaded View */ - public static LoadedView load(URL fxml, Object model, ApplicationContext context, ViewModelContext models) { - return load(fxml, model, context, models.openView()); + public static LoadedView loadWithDependencies(URL fxml, Object model, + ViewDependencies dependencies, ViewModelContext models) { + return load(fxml, model, new ViewInstances(dependencies), models.openView()); } /** - * Opens a Component's own fx:root document with the supplied Model. The Component selects - * its ViewModel in the same context as its nested Views. Closing the result detaches its - * bindings and releases its controller and children. - * - * @param type the injected Component class with a sibling ClassName.fxml + * Loads a managed Component from its sibling ClassName.fxml on the JavaFX application thread. + * @param type the registered Component class * @param model the initial non-null Model - * @param context the application container - * @param models the owner of the View and its Model identity + * @param dependencies the adapter for View objects and services + * @param models the Model context that owns the View * @return the initialized Component and its effective ViewModel */ - public static LoadedView loadComponent(Class type, Object model, - ApplicationContext context, ViewModelContext models) { - java.util.Objects.requireNonNull(model, "Component Model"); + public static LoadedView loadComponentWithDependencies(Class type, Object model, + ViewDependencies dependencies, ViewModelContext models) { + return loadComponent(type, model, new ViewInstances(dependencies), models); + } + + private static LoadedView loadComponent(Class type, Object model, + ViewInstances context, ViewModelContext models) { + Objects.requireNonNull(model, "Component Model"); ViewLifetime lifetime = models.openView(); try { Parent root = type.cast(Components.fresh(type, context, lifetime)); @@ -116,11 +58,15 @@ public final class ViewLoader { return new LoadedView(root, viewModel, lifetime); } catch (RuntimeException | Error failure) { lifetime.rollback(failure); + if (failure instanceof RuntimeException) { + throw new IllegalStateException("Could not load Component " + type.getName() + " from " + + type.getSimpleName() + ".fxml: " + failure.getMessage(), failure); + } throw failure; } } - private static LoadedView load(URL fxml, Object model, ApplicationContext context, ViewLifetime lifetime) { + private static LoadedView load(URL fxml, Object model, ViewInstances context, ViewLifetime lifetime) { LoadSession session = LoadSession.nest(); try { Class controllerType = FxmlControllers.controllerClass(fxml); @@ -128,7 +74,7 @@ public final class ViewLoader { Object viewModel = ViewModels.of(lifetime.models(), model, viewModelClass); FXMLLoader loader = new FXMLLoader(fxml, resources(context, fxml, controllerType)); FxmlHandlers.observe(loader, lifetime); - loader.setControllerFactory(type -> createController(context, type, lifetime)); + loader.setControllerFactory(type -> context.controller(type, lifetime)); loader.setBuilderFactory(type -> Components.builder(type, context, lifetime)); Object loaded = loader.load(); if (!(loaded instanceof Parent root)) { @@ -153,27 +99,17 @@ public final class ViewLoader { throw new IllegalStateException("Could not load view " + fxml, failure); } catch (RuntimeException | Error failure) { lifetime.rollback(failure); + if (failure instanceof RuntimeException) { + throw new IllegalStateException("Could not load view " + fxml + ": " + failure.getMessage(), failure); + } throw failure; } finally { 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(ViewInstances context, URL fxml, Class type) { + Localizer languages = context.localizer(); + return languages == null ? null : languages.forView(fxml, type); } - - static Messages resources(ApplicationContext context, URL fxml, Class type) { - Localizer languages; - try { - languages = context.getComponent(Localizer.class); - } catch (IllegalArgumentException unregistered) { - return null; - } - return languages.forView(fxml, type); - } - } diff --git a/fx/src/main/java/de/neitzel/fx/view/ViewObject.java b/fx/src/main/java/de/neitzel/fx/view/ViewObject.java new file mode 100644 index 0000000..df8cc58 --- /dev/null +++ b/fx/src/main/java/de/neitzel/fx/view/ViewObject.java @@ -0,0 +1,15 @@ +package de.neitzel.fx.view; + +import java.util.Objects; + +/** + * An instance and the action its View invokes once on release. Use an empty action when the + * instance has no cleanup. The action is responsible for any container-specific destruction. + */ +public record ViewObject(T instance, Runnable release) { + + public ViewObject { + Objects.requireNonNull(instance, "View object"); + Objects.requireNonNull(release, "View object release action"); + } +} diff --git a/fx/src/test/java/de/neitzel/fx/view/BindCommandTest.java b/fx/src/test/java/de/neitzel/fx/view/BindCommandTest.java index d8cbd65..b690f97 100644 --- a/fx/src/test/java/de/neitzel/fx/view/BindCommandTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/BindCommandTest.java @@ -1,7 +1,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.command.CommandController; -import de.neitzel.injection.ApplicationContext; import java.nio.file.Files; import java.nio.file.Path; import javafx.scene.control.Button; @@ -35,7 +34,7 @@ class BindCommandTest { """); FxThread.onFx(() -> { try (var models = new ViewModelContext()) { - var view = ViewLoader.load(url, new CommandController.Subject(), services(), models); + var view = ViewLoader.loadWithDependencies(url, new CommandController.Subject(), services(), models); var model = (CommandController.Model) view.getViewModel(); var button = (Button) view.getRoot().lookup("#button"); var menu = ((MenuBar) view.getRoot().lookup("#menu")).getMenus().getFirst(); @@ -83,8 +82,8 @@ class BindCommandTest { var url = view("invalid-command.fxml", scenario[0]); FxThread.onFx(() -> { try (var models = new ViewModelContext()) { - var failure = assertThrows(IllegalArgumentException.class, - () -> ViewLoader.load(url, new CommandController.Subject(), services(), models)); + var failure = assertThrows(IllegalStateException.class, + () -> ViewLoader.loadWithDependencies(url, new CommandController.Subject(), services(), models)); assertTrue(failure.getMessage().contains("invalid-command.fxml")); assertTrue(failure.getMessage().contains(scenario[1])); } @@ -92,8 +91,8 @@ class BindCommandTest { } } - private ApplicationContext services() { - return new ApplicationContext("de.neitzel.fx.view.command"); + private TestViews services() { + return new TestViews(); } private java.net.URL view(String name, String bindings) throws Exception { diff --git a/fx/src/test/java/de/neitzel/fx/view/BindReadOnlySourcesTest.java b/fx/src/test/java/de/neitzel/fx/view/BindReadOnlySourcesTest.java index 45ae477..049c4d4 100644 --- a/fx/src/test/java/de/neitzel/fx/view/BindReadOnlySourcesTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/BindReadOnlySourcesTest.java @@ -2,7 +2,6 @@ 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; @@ -34,7 +33,7 @@ class BindReadOnlySourcesTest { @Test void followsOnlyDependenciesOfTheViewModelSource() throws Exception { FxThread.onFx(() -> { - LoadedView view = ViewLoader.load(DOCUMENT, new Person("Ada"), context()); + LoadedView view = TestViews.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"); @@ -77,8 +76,8 @@ class BindReadOnlySourcesTest { 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())); + IllegalStateException failure = assertThrows(IllegalStateException.class, + () -> TestViews.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()); @@ -86,7 +85,7 @@ class BindReadOnlySourcesTest { }); } - private static ApplicationContext context() { - return new ApplicationContext("de.neitzel.fx.view.readable"); + private static TestViews context() { + return new TestViews(); } } diff --git a/fx/src/test/java/de/neitzel/fx/view/CarryChildMessageTest.java b/fx/src/test/java/de/neitzel/fx/view/CarryChildMessageTest.java index ff6e25c..8ca6f72 100644 --- a/fx/src/test/java/de/neitzel/fx/view/CarryChildMessageTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/CarryChildMessageTest.java @@ -3,7 +3,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.fixture.Address; import de.neitzel.fx.view.fixture.Household; import de.neitzel.fx.view.fixture.Person; -import de.neitzel.injection.ApplicationContext; import javafx.application.Platform; import javafx.beans.property.Property; import javafx.scene.control.TextField; @@ -55,8 +54,8 @@ class CarryChildMessageTest { person.setAddress(new Address("Main")); URL fxml = CarryChildMessageTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); ViewModel personModel = loaded.getViewModel(); ViewModel addressModel = (ViewModel) personModel.property("address").getValue(); addressModel.addMessage(new Message(Message.Severity.INFO, "lane is closed", "street")); @@ -85,8 +84,8 @@ class CarryChildMessageTest { household.setPerson(person); URL fxml = CarryChildMessageTest.class.getResource("plain-view.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, household, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, household, context); ViewModel householdModel = loaded.getViewModel(); ViewModel personModel = (ViewModel) householdModel.property("person").getValue(); ViewModel addressModel = (ViewModel) personModel.property("address").getValue(); @@ -112,8 +111,8 @@ class CarryChildMessageTest { person.setAddress(new Address("Main")); URL fxml = CarryChildMessageTest.class.getResource("address-street-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); streetField.setText("nope"); @@ -145,8 +144,8 @@ class CarryChildMessageTest { person.setAddress(new Address("Main")); URL fxml = CarryChildMessageTest.class.getResource("address-street-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); streetField.setText("nope"); streetField.setText("ok Oak"); @@ -173,8 +172,8 @@ class CarryChildMessageTest { household.setPerson(person); URL fxml = CarryChildMessageTest.class.getResource("household-street-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, household, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, household, context); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); streetField.setText("nope"); @@ -217,8 +216,8 @@ class CarryChildMessageTest { person.setAddress(new Address("Main")); URL fxml = CarryChildMessageTest.class.getResource("plain-view.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); ViewModel personModel = loaded.getViewModel(); ViewModel addressModel = (ViewModel) personModel.property("address").getValue(); addressModel.addMessage(new Message(Message.Severity.INFO, "lane is closed", "street")); @@ -235,7 +234,7 @@ class CarryChildMessageTest { assertEquals("lane is closed", addressModel.getMessages().get(0).getText()); Address moved = new Address("Oak"); - LoadedView movedView = ViewLoader.load(fxml, moved, context); + LoadedView movedView = TestViews.load(fxml, moved, context); movedView.getViewModel().addMessage(new Message(Message.Severity.WARN, "under repair", "street")); address.setValue(movedView.getViewModel()); @@ -259,8 +258,8 @@ class CarryChildMessageTest { person.setAddress(new Address("Main")); URL fxml = CarryChildMessageTest.class.getResource("address-street-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); ViewModel personModel = loaded.getViewModel(); personModel.addMessage(new Message(Message.Severity.INFO, "keep me", "form")); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); @@ -304,8 +303,8 @@ class CarryChildMessageTest { household.setPerson(person); URL fxml = CarryChildMessageTest.class.getResource("household-street-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, household, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, household, context); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); streetField.setText("nope"); streetField.setText("ok Oak"); @@ -335,8 +334,8 @@ class CarryChildMessageTest { person.setWork(shared); URL fxml = CarryChildMessageTest.class.getResource("plain-view.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); ViewModel personModel = loaded.getViewModel(); ViewModel homeModel = (ViewModel) personModel.property("home").getValue(); homeModel.addMessage(new Message(Message.Severity.INFO, "lane is closed", "street")); diff --git a/fx/src/test/java/de/neitzel/fx/view/ChooseControllerAndViewModelTest.java b/fx/src/test/java/de/neitzel/fx/view/ChooseControllerAndViewModelTest.java index 56a4720..facbb6e 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ChooseControllerAndViewModelTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ChooseControllerAndViewModelTest.java @@ -2,7 +2,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.fixture.Address; import de.neitzel.fx.view.fixture.Person; -import de.neitzel.injection.ApplicationContext; import javafx.application.Platform; import javafx.beans.property.Property; import javafx.scene.control.Label; @@ -51,8 +50,8 @@ class ChooseControllerAndViewModelTest { Person person = new Person("Ada"); URL fxml = ChooseControllerAndViewModelTest.class.getResource("handed-name.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Label handedLabel = (Label) loaded.getRoot().lookup("#handedLabel"); assertEquals("handed-Ada", handedLabel.getText()); }); @@ -67,8 +66,8 @@ class ChooseControllerAndViewModelTest { Person person = new Person("Ada"); URL fxml = ChooseControllerAndViewModelTest.class.getResource("desk-greeting.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Label deskLabel = (Label) loaded.getRoot().lookup("#deskLabel"); assertEquals("from-the-desk", deskLabel.getText()); }); @@ -83,8 +82,8 @@ class ChooseControllerAndViewModelTest { Person person = new Person("Ada"); URL fxml = ChooseControllerAndViewModelTest.class.getResource("titled-name.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Label titleLabel = (Label) loaded.getRoot().lookup("#titleLabel"); assertEquals("titled-Ada", titleLabel.getText()); @SuppressWarnings("unchecked") @@ -105,8 +104,8 @@ class ChooseControllerAndViewModelTest { Person person = new Person("Ada"); URL fxml = ChooseControllerAndViewModelTest.class.getResource("badge-name.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Label badgeLabel = (Label) loaded.getRoot().lookup("#badgeLabel"); assertEquals("badge-Ada", badgeLabel.getText()); @SuppressWarnings("unchecked") @@ -128,8 +127,8 @@ class ChooseControllerAndViewModelTest { person.setAddress(new Address("Main")); URL fxml = ChooseControllerAndViewModelTest.class.getResource("caption-address.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Label captionLabel = (Label) loaded.getRoot().lookup("#captionLabel"); assertEquals("caption-Main", captionLabel.getText()); }); @@ -146,12 +145,12 @@ class ChooseControllerAndViewModelTest { URL badge = ChooseControllerAndViewModelTest.class.getResource("badge-name.fxml"); assertNotNull(titled); assertNotNull(badge); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); - LoadedView first = ViewLoader.load(titled, person, context); + TestViews context = new TestViews(); + LoadedView first = TestViews.load(titled, person, context); Label titleLabel = (Label) first.getRoot().lookup("#titleLabel"); assertEquals("titled-Ada", titleLabel.getText()); - IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, - () -> ViewLoader.load(badge, person, context)); + IllegalStateException failure = assertThrows(IllegalStateException.class, + () -> TestViews.load(badge, person, context)); assertTrue(failure.getMessage().contains("TitledViewModel"), failure.getMessage()); assertTrue(failure.getMessage().contains("BadgeViewModel"), failure.getMessage()); assertEquals("titled-Ada", titleLabel.getText()); @@ -169,9 +168,9 @@ class ChooseControllerAndViewModelTest { URL plain = ChooseControllerAndViewModelTest.class.getResource("name-both-ways.fxml"); assertNotNull(named); assertNotNull(plain); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen"); - LoadedView first = ViewLoader.load(named, person, context); - LoadedView second = ViewLoader.load(plain, person, context); + TestViews context = new TestViews(); + LoadedView first = TestViews.load(named, person, context); + LoadedView second = TestViews.load(plain, person, context); TextField firstName = (TextField) first.getRoot().lookup("#nameField"); TextField secondName = (TextField) second.getRoot().lookup("#nameField"); assertEquals("Ada", firstName.getText()); diff --git a/fx/src/test/java/de/neitzel/fx/view/ComputeAValueTest.java b/fx/src/test/java/de/neitzel/fx/view/ComputeAValueTest.java index b1be0b1..d38d973 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ComputeAValueTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ComputeAValueTest.java @@ -1,7 +1,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.fixture.Person; -import de.neitzel.injection.ApplicationContext; import javafx.application.Platform; import javafx.beans.property.Property; import javafx.scene.control.Label; @@ -49,8 +48,8 @@ class ComputeAValueTest { person.setAge(36); URL fxml = ComputeAValueTest.class.getResource("working-age.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.computed"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel"); assertEquals("initial-age", workingAgeLabel.getText()); assertEquals("Ada", person.getName()); @@ -67,8 +66,8 @@ class ComputeAValueTest { Person person = new Person("Ada"); URL fxml = ComputeAValueTest.class.getResource("working-age.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.computed"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField nameField = (TextField) loaded.getRoot().lookup("#nameField"); Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel"); nameField.setText("Grace"); @@ -86,8 +85,8 @@ class ComputeAValueTest { Person person = new Person("Ada"); URL fxml = ComputeAValueTest.class.getResource("working-age.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.computed"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel"); @SuppressWarnings("unchecked") Property name = (Property) loaded.property("name"); @@ -106,8 +105,8 @@ class ComputeAValueTest { Person person = new Person("Ada"); URL fxml = ComputeAValueTest.class.getResource("working-age.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.computed"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel"); assertEquals("initial-age", workingAgeLabel.getText()); workingAgeLabel.setText("sentinel"); diff --git a/fx/src/test/java/de/neitzel/fx/view/ConvertAndRecordFailureTest.java b/fx/src/test/java/de/neitzel/fx/view/ConvertAndRecordFailureTest.java index 180e480..2767018 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ConvertAndRecordFailureTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ConvertAndRecordFailureTest.java @@ -1,7 +1,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.fixture.Person; -import de.neitzel.injection.ApplicationContext; import javafx.application.Platform; import javafx.beans.property.IntegerProperty; import javafx.scene.control.Label; @@ -56,8 +55,8 @@ class ConvertAndRecordFailureTest { person.setAge(42); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); assertEquals("years:42", ageField.getText()); }); @@ -73,8 +72,8 @@ class ConvertAndRecordFailureTest { person.setAge(42); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); ageField.setText("years:11"); assertEquals(11, person.getAge()); @@ -91,8 +90,8 @@ class ConvertAndRecordFailureTest { person.setAge(42); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-view-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Label ageLabel = (Label) loaded.getRoot().lookup("#ageLabel"); assertEquals("shown 42", ageLabel.getText()); ageLabel.setText("shown 99"); @@ -110,8 +109,8 @@ class ConvertAndRecordFailureTest { person.setAge(42); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-and-view-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); Label ageLabel = (Label) loaded.getRoot().lookup("#ageLabel"); assertEquals("shown 42", ageLabel.getText()); @@ -131,8 +130,8 @@ class ConvertAndRecordFailureTest { person.setAge(42); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-model-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); assertEquals("years:42", ageField.getText()); ((IntegerProperty) loaded.property("age")).set(7); @@ -154,8 +153,8 @@ class ConvertAndRecordFailureTest { person.setAge(42); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); ageField.setText("nope"); assertEquals(Integer.valueOf(42), person.getAge()); @@ -180,8 +179,8 @@ class ConvertAndRecordFailureTest { person.setAge(42); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); ageField.setText("nope"); ViewModel viewModel = loaded.getViewModel(); @@ -205,8 +204,8 @@ class ConvertAndRecordFailureTest { person.setAge(42); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); ageField.setText("nope"); ageField.setText("years:11"); @@ -227,8 +226,8 @@ class ConvertAndRecordFailureTest { person.setAge(42); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); ViewModel viewModel = loaded.getViewModel(); ageField.setText("nope"); @@ -255,8 +254,8 @@ class ConvertAndRecordFailureTest { person.setAge(42); URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); ViewModel viewModel = loaded.getViewModel(); String log = captureErr(() -> { diff --git a/fx/src/test/java/de/neitzel/fx/view/DataGridFxmlTest.java b/fx/src/test/java/de/neitzel/fx/view/DataGridFxmlTest.java index f5831a3..faf1f67 100644 --- a/fx/src/test/java/de/neitzel/fx/view/DataGridFxmlTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/DataGridFxmlTest.java @@ -6,7 +6,6 @@ import de.neitzel.fx.control.NonNegativeIntegerSpinner; import de.neitzel.fx.control.StatusBar; import de.neitzel.fx.docking.DockPane; import de.neitzel.grid.*; -import de.neitzel.injection.ApplicationContext; import javafx.collections.*; import javafx.fxml.FXMLLoader; @@ -241,10 +240,10 @@ class DataGridFxmlTest { DataGridTest.fx(() -> { try { var view = - ViewLoader.load( + TestViews.load( document.toUri().toURL(), model, - new ApplicationContext("de.neitzel.fx.view.fixture")); + new TestViews()); @SuppressWarnings("unchecked") var grid = (DataGrid) view.getRoot().lookup("#grid"); ref.set(grid); diff --git a/fx/src/test/java/de/neitzel/fx/view/EditAddressInAComponentTest.java b/fx/src/test/java/de/neitzel/fx/view/EditAddressInAComponentTest.java index 41e8d86..c886907 100644 --- a/fx/src/test/java/de/neitzel/fx/view/EditAddressInAComponentTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/EditAddressInAComponentTest.java @@ -5,7 +5,6 @@ import de.neitzel.fx.view.component.Envelope; import de.neitzel.fx.view.component.Letter; import de.neitzel.fx.view.fixture.Address; import de.neitzel.fx.view.fixture.Person; -import de.neitzel.injection.ApplicationContext; import javafx.application.Platform; import javafx.scene.control.Label; import javafx.scene.control.TextField; @@ -55,8 +54,8 @@ class EditAddressInAComponentTest { person.setAddress(address); URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm"); assertNotNull(form); assertSame(address, form.getModel()); @@ -76,8 +75,8 @@ class EditAddressInAComponentTest { Person person = new Person("Ada"); URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm"); assertNotNull(form); assertNull(form.getModel()); @@ -97,8 +96,8 @@ class EditAddressInAComponentTest { person.setAddress(new Address("Main")); URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm"); Label streetLabel = (Label) form.lookup("#streetLabel"); assertEquals("Lane", streetLabel.getText()); @@ -116,8 +115,8 @@ class EditAddressInAComponentTest { person.setAddress(address); URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm"); assertSame(loaded.property("address").getValue(), form.receivedViewModel()); assertEquals("kept", form.streetTextAtHandOff()); @@ -136,8 +135,8 @@ class EditAddressInAComponentTest { Letter letter = new Letter(new Envelope(address)); URL fxml = EditAddressInAComponentTest.class.getResource("letter-envelope.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); - LoadedView loaded = ViewLoader.load(fxml, letter, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, letter, context); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); assertEquals("Main", streetField.getText()); streetField.setText("Oak"); @@ -151,8 +150,8 @@ class EditAddressInAComponentTest { @Test void componentAttributesApplyAfterInitialization() throws Exception { onFx(() -> { - var context = new ApplicationContext("de.neitzel.fx.view.component"); - var loaded = ViewLoader.load(getClass().getResource("address-component-attributes.fxml"), + var context = new TestViews(); + var loaded = TestViews.load(getClass().getResource("address-component-attributes.fxml"), new Person("Ada"), context); var first = (AddressForm) loaded.getRoot().lookup("#first"); var second = (AddressForm) loaded.getRoot().lookup("#second"); @@ -165,7 +164,7 @@ class EditAddressInAComponentTest { assertSame(first.getModel(), second.getModel()); assertEquals("Second", second.getCaption()); assertEquals(280, second.getPrefWidth()); - assertSame(first, context.getComponent(AddressForm.class)); + org.junit.jupiter.api.Assertions.assertNotSame(first, second); TextField field = (TextField) first.lookup("#streetField"); assertEquals("Main", field.getText()); field.setText("Oak"); @@ -180,9 +179,9 @@ class EditAddressInAComponentTest { void invalidComponentAttributesFailTheLoad() throws Exception { onFx(() -> { for (String kind : java.util.List.of("unknown", "number")) { - var context = new ApplicationContext("de.neitzel.fx.view.component"); + var context = new TestViews(); org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, - () -> ViewLoader.load(getClass().getResource("address-component-invalid-" + kind + ".fxml"), + () -> TestViews.load(getClass().getResource("address-component-invalid-" + kind + ".fxml"), new Person("Ada"), context)); } }); diff --git a/fx/src/test/java/de/neitzel/fx/view/FilterByChecklistTest.java b/fx/src/test/java/de/neitzel/fx/view/FilterByChecklistTest.java index 0953dfa..8de7515 100644 --- a/fx/src/test/java/de/neitzel/fx/view/FilterByChecklistTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/FilterByChecklistTest.java @@ -3,7 +3,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.component.VisitRow; import de.neitzel.fx.view.fixture.Host; import de.neitzel.fx.view.fixture.Visit; -import de.neitzel.injection.ApplicationContext; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.control.Button; @@ -151,7 +150,7 @@ class FilterByChecklistTest { private static LoadedView load(Host host) { URL fxml = FilterByChecklistTest.class.getResource("show-visits-selection.fxml"); assertNotNull(fxml); - return ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component")); + return TestViews.load(fxml, host, new TestViews()); } /** diff --git a/fx/src/test/java/de/neitzel/fx/view/FilterByComparisonTest.java b/fx/src/test/java/de/neitzel/fx/view/FilterByComparisonTest.java index afa6cec..6a40e04 100644 --- a/fx/src/test/java/de/neitzel/fx/view/FilterByComparisonTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/FilterByComparisonTest.java @@ -3,7 +3,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.fixture.Host; import de.neitzel.fx.view.fixture.Role; import de.neitzel.fx.view.fixture.Visit; -import de.neitzel.injection.ApplicationContext; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; @@ -206,7 +205,7 @@ class FilterByComparisonTest { private static LoadedView load(Host host) { URL fxml = FilterByComparisonTest.class.getResource("show-two-tables.fxml"); assertNotNull(fxml); - return ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component")); + return TestViews.load(fxml, host, new TestViews()); } /** diff --git a/fx/src/test/java/de/neitzel/fx/view/KeepAControlAfterTheColumnsTest.java b/fx/src/test/java/de/neitzel/fx/view/KeepAControlAfterTheColumnsTest.java index 47211ad..787cea1 100644 --- a/fx/src/test/java/de/neitzel/fx/view/KeepAControlAfterTheColumnsTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/KeepAControlAfterTheColumnsTest.java @@ -3,7 +3,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.component.ActionRow; import de.neitzel.fx.view.fixture.Host; import de.neitzel.fx.view.fixture.Visit; -import de.neitzel.injection.ApplicationContext; import javafx.scene.control.Button; import javafx.scene.control.ScrollPane; import javafx.scene.layout.HBox; @@ -67,7 +66,7 @@ class KeepAControlAfterTheColumnsTest { assertNotNull(fxml); Host host = new Host(); host.setVisits(new ArrayList<>(List.of(new Visit("Main", "Berlin")))); - LoadedView loaded = ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component")); + LoadedView loaded = TestViews.load(fxml, host, new TestViews()); return (Table) loaded.getRoot().lookup("#visitsTable"); } diff --git a/fx/src/test/java/de/neitzel/fx/view/ListSourceBindingTest.java b/fx/src/test/java/de/neitzel/fx/view/ListSourceBindingTest.java index fa2c30c..bbf10e1 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ListSourceBindingTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ListSourceBindingTest.java @@ -1,7 +1,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.control.AutoCompleteTextField; -import de.neitzel.injection.ApplicationContext; import java.util.Map; import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleListProperty; @@ -31,7 +30,8 @@ class ListSourceBindingTest { binding.setPath("tags"); binding.setDirection("view"); try (var models = new ViewModelContext(); var lifetime = new ViewLifetime(models)) { - DirectBindingApplier.apply(Map.of("combo", combo), model, binding, new ApplicationContext(Tags.class), lifetime); + DirectBindingApplier.apply(Map.of("combo", combo), model, binding, + new ViewInstances(new TestViews()), lifetime); assertSame(model.tags.get(), combo.getItems()); var replacement = FXCollections.observableArrayList("First"); model.tags.set(replacement); diff --git a/fx/src/test/java/de/neitzel/fx/view/ManagedViewTest.java b/fx/src/test/java/de/neitzel/fx/view/ManagedViewTest.java index ea5ae58..0d75e95 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ManagedViewTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ManagedViewTest.java @@ -5,7 +5,6 @@ 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; @@ -32,11 +31,11 @@ class ManagedViewTest { void sharesViewModelWithinContextAndClosesOnlyTheRequestedView() throws Exception { FxThread.onFx(() -> { var model = new Person("Ada"); - var injection = new ApplicationContext("de.neitzel.fx.view.managed"); + var injection = new TestViews(); 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); + var first = ViewLoader.loadWithDependencies(fxml("managed-view.fxml"), model, injection, models); + var second = ViewLoader.loadWithDependencies(fxml("managed-view.fxml"), model, injection, models); + var other = ViewLoader.loadWithDependencies(fxml("managed-view.fxml"), model, injection, otherModels); assertSame(first.getViewModel(), second.getViewModel()); assertNotSame(first.getViewModel(), other.getViewModel()); @@ -65,7 +64,7 @@ class ManagedViewTest { assertEquals("Lin", model.getName()); assertEquals(1, secondController.getCloseCount()); assertThrows(IllegalStateException.class, - () -> ViewLoader.load(fxml("managed-view.fxml"), model, injection, models)); + () -> ViewLoader.loadWithDependencies(fxml("managed-view.fxml"), model, injection, models)); } }); } @@ -74,18 +73,18 @@ class ManagedViewTest { void failedBindingClosesControllerAndRollsBackEarlierBinding() throws Exception { FxThread.onFx(() -> { var model = new Person("Ada"); - var injection = new ApplicationContext("de.neitzel.fx.view.managed"); + var injection = new TestViews(); 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 registry = injection.findService(ViewController.Registry.class).orElseThrow(); + assertThrows(IllegalStateException.class, + () -> ViewLoader.loadWithDependencies(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); + var loaded = ViewLoader.loadWithDependencies(fxml("managed-view.fxml"), model, injection, models); field(loaded.getRoot(), "#name").setText("Working"); assertEquals("Detached", abandoned.getInput().getText()); assertEquals("Working", model.getName()); @@ -97,11 +96,11 @@ class ManagedViewTest { void opensAComponentDirectlyAndDetachesOnlyItsOwnBindings() throws Exception { FxThread.onFx(() -> { var model = new Address("Main"); - var services = new ApplicationContext("de.neitzel.fx.view.component"); + var services = new TestViews(); var type = de.neitzel.fx.view.component.AddressForm.class; try (var models = new ViewModelContext()) { - var first = ViewLoader.loadComponent(type, model, services, models); - var second = ViewLoader.loadComponent(type, model, services, models); + var first = ViewLoader.loadComponentWithDependencies(type, model, services, models); + var second = ViewLoader.loadComponentWithDependencies(type, model, services, models); assertSame(first.getViewModel(), second.getViewModel()); var input = field(first.getRoot(), "#streetField"); input.setText("Shared"); @@ -121,8 +120,8 @@ class ManagedViewTest { 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 context = new TestViews(); + var loaded = ViewLoader.loadWithDependencies(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"); @@ -148,8 +147,8 @@ class ManagedViewTest { 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 context = new TestViews(); + var loaded = ViewLoader.loadWithDependencies(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"); diff --git a/fx/src/test/java/de/neitzel/fx/view/ObserveGridSelectionTest.java b/fx/src/test/java/de/neitzel/fx/view/ObserveGridSelectionTest.java index ef94a00..3b23e15 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ObserveGridSelectionTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ObserveGridSelectionTest.java @@ -2,7 +2,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.DataGridTest.Item; import de.neitzel.grid.TextFilter; -import de.neitzel.injection.ApplicationContext; import javafx.scene.control.Label; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -39,10 +38,10 @@ class ObserveGridSelectionTest { var control = grid.get(); control.select(1L); var document = getClass().getResource("grid-selection-summary.fxml"); - var context = new ApplicationContext("de.neitzel.fx.view.selection"); + var context = new TestViews(); try (var selection = control.observeSelection(); var models = new ViewModelContext(); - var view = ViewLoader.load(document, selection, context, models)) { + var view = ViewLoader.loadWithDependencies(document, selection, context, models)) { var initial = selection.getSelection(); var summary = (Label) view.getRoot().lookup("#summary"); assertEquals(List.of(1L), initial.selectedKeys()); diff --git a/fx/src/test/java/de/neitzel/fx/view/OpenAtAGivenWidthTest.java b/fx/src/test/java/de/neitzel/fx/view/OpenAtAGivenWidthTest.java index 5e63b1e..1290dfe 100644 --- a/fx/src/test/java/de/neitzel/fx/view/OpenAtAGivenWidthTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/OpenAtAGivenWidthTest.java @@ -2,7 +2,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.fixture.Host; import de.neitzel.fx.view.fixture.Visit; -import de.neitzel.injection.ApplicationContext; import javafx.scene.control.ScrollPane; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; @@ -87,7 +86,7 @@ class OpenAtAGivenWidthTest { */ @Test void aWidthThatIsNotPositiveFailsToLoad() throws Exception { - FxThread.onFx(() -> assertThrows(IllegalArgumentException.class, () -> table("show-visits-bad-width.fxml"))); + FxThread.onFx(() -> assertThrows(IllegalStateException.class, () -> table("show-visits-bad-width.fxml"))); } /** @@ -101,7 +100,7 @@ class OpenAtAGivenWidthTest { assertNotNull(fxml); Host host = new Host(); host.setVisits(new ArrayList<>(List.of(new Visit("Main", "Berlin")))); - LoadedView loaded = ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component")); + LoadedView loaded = TestViews.load(fxml, host, new TestViews()); return (Table) loaded.getRoot().lookup("#visitsTable"); } diff --git a/fx/src/test/java/de/neitzel/fx/view/ReachNestedAttributeTest.java b/fx/src/test/java/de/neitzel/fx/view/ReachNestedAttributeTest.java index ce013c8..c761475 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ReachNestedAttributeTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ReachNestedAttributeTest.java @@ -4,7 +4,6 @@ import de.neitzel.fx.view.fixture.Address; import de.neitzel.fx.view.fixture.ObjectHolder; import de.neitzel.fx.view.fixture.Person; import de.neitzel.fx.view.fixture.Role; -import de.neitzel.injection.ApplicationContext; import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.scene.control.Label; @@ -62,8 +61,8 @@ class ReachNestedAttributeTest { person.setAddress(new Address("Main")); URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Object addressValue = loaded.property("address").getValue(); assertInstanceOf(ViewModel.class, addressValue); assertEquals("Main", ((ViewModel) addressValue).property("street").getValue()); @@ -81,8 +80,8 @@ class ReachNestedAttributeTest { person.setAddress(address); URL fxml = ReachNestedAttributeTest.class.getResource("address-street-both.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); assertEquals("Main", streetField.getText()); streetField.setText("Oak"); @@ -101,8 +100,8 @@ class ReachNestedAttributeTest { person.setAddress(address); URL fxml = ReachNestedAttributeTest.class.getResource("address-street-both-and-view.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); Label streetLabel = (Label) loaded.getRoot().lookup("#streetLabel"); assertEquals("Main", streetLabel.getText()); @@ -125,8 +124,8 @@ class ReachNestedAttributeTest { person.setAddress(address); URL fxml = ReachNestedAttributeTest.class.getResource("address-object.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); ObjectHolder addressHolder = (ObjectHolder) loaded.getRoot().lookup("#addressHolder"); assertSame(address, addressHolder.getValue()); Address moved = new Address("Oak"); @@ -144,8 +143,8 @@ class ReachNestedAttributeTest { Person person = new Person("Ada"); URL fxml = ReachNestedAttributeTest.class.getResource("address-object.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); ObjectHolder addressHolder = (ObjectHolder) loaded.getRoot().lookup("#addressHolder"); assertNull(addressHolder.getValue()); assertNull(person.getAddress()); @@ -167,8 +166,8 @@ class ReachNestedAttributeTest { Person person = new Person("Ada"); URL fxml = ReachNestedAttributeTest.class.getResource("address-street-kept.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField streetField = (TextField) loaded.getRoot().lookup("#streetField"); assertEquals("kept", streetField.getText()); assertNull(person.getAddress()); @@ -184,8 +183,8 @@ class ReachNestedAttributeTest { Person person = new Person("Ada"); URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); assertNull(loaded.property("address").getValue()); }); } @@ -202,8 +201,8 @@ class ReachNestedAttributeTest { person.setWork(shared); URL fxml = ReachNestedAttributeTest.class.getResource("home-work-street.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); assertSame(loaded.property("home").getValue(), loaded.property("work").getValue()); TextField homeField = (TextField) loaded.getRoot().lookup("#homeField"); TextField workField = (TextField) loaded.getRoot().lookup("#workField"); @@ -227,8 +226,8 @@ class ReachNestedAttributeTest { person.setWork(work); URL fxml = ReachNestedAttributeTest.class.getResource("home-work-street.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); assertNotSame(loaded.property("home").getValue(), loaded.property("work").getValue()); TextField homeField = (TextField) loaded.getRoot().lookup("#homeField"); TextField workField = (TextField) loaded.getRoot().lookup("#workField"); @@ -249,8 +248,8 @@ class ReachNestedAttributeTest { person.setFriend(person); URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); assertSame(loaded.getViewModel(), loaded.property("friend").getValue()); }); } @@ -267,8 +266,8 @@ class ReachNestedAttributeTest { grace.setFriend(ada); URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, ada, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, ada, context); ViewModel graceModel = (ViewModel) loaded.property("friend").getValue(); assertEquals("Grace", graceModel.property("name").getValue()); assertSame(loaded.getViewModel(), graceModel.property("friend").getValue()); @@ -292,8 +291,8 @@ class ReachNestedAttributeTest { person.setHired(hired); URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); assertEquals(true, loaded.property("active").getValue()); assertSame(Role.ADMIN, loaded.property("role").getValue()); assertEquals(born, loaded.property("born").getValue()); @@ -314,8 +313,8 @@ class ReachNestedAttributeTest { person.setTags(tags); URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); assertInstanceOf(ObservableList.class, loaded.property("tags").getValue()); @SuppressWarnings("unchecked") ObservableList shown = (ObservableList) loaded.property("tags").getValue(); @@ -335,9 +334,9 @@ class ReachNestedAttributeTest { Person person = new Person("Ada"); URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView first = ViewLoader.load(fxml, person, context); - LoadedView second = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView first = TestViews.load(fxml, person, context); + LoadedView second = TestViews.load(fxml, person, context); assertSame(first.getViewModel(), second.getViewModel()); TextField firstName = (TextField) first.getRoot().lookup("#nameField"); TextField secondName = (TextField) second.getRoot().lookup("#nameField"); diff --git a/fx/src/test/java/de/neitzel/fx/view/RepeatAddressComponentsTest.java b/fx/src/test/java/de/neitzel/fx/view/RepeatAddressComponentsTest.java index 7792438..1e759db 100644 --- a/fx/src/test/java/de/neitzel/fx/view/RepeatAddressComponentsTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/RepeatAddressComponentsTest.java @@ -3,7 +3,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.component.AddressForm; import de.neitzel.fx.view.fixture.Address; import de.neitzel.fx.view.fixture.Person; -import de.neitzel.injection.ApplicationContext; import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.scene.control.ComboBox; @@ -61,8 +60,8 @@ class RepeatAddressComponentsTest { person.setAddresses(new ArrayList<>(List.of(main, oak))); URL fxml = RepeatAddressComponentsTest.class.getResource("plain-view.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); assertInstanceOf(ObservableList.class, loaded.property("addresses").getValue()); @SuppressWarnings("unchecked") ObservableList

addresses = (ObservableList
) loaded.property("addresses").getValue(); @@ -88,17 +87,13 @@ class RepeatAddressComponentsTest { person.setAddresses(new ArrayList<>(List.of(main, oak))); URL fxml = RepeatAddressComponentsTest.class.getResource("repeat-addresses.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); - AddressForm cached = context.getComponent(AddressForm.class); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); VBox pane = (VBox) loaded.getRoot().lookup("#addressPane"); assertEquals(2, pane.getChildren().size()); AddressForm first = (AddressForm) pane.getChildren().get(0); AddressForm second = (AddressForm) pane.getChildren().get(1); assertNotSame(first, second); - assertNotSame(cached, first); - assertNotSame(cached, second); - assertSame(cached, context.getComponent(AddressForm.class)); assertSame(main, first.getModel()); assertSame(oak, second.getModel()); assertEquals("Main", ((TextField) first.lookup("#streetField")).getText()); @@ -120,8 +115,8 @@ class RepeatAddressComponentsTest { person.setAddresses(new ArrayList<>(List.of(main, oak))); URL fxml = RepeatAddressComponentsTest.class.getResource("repeat-addresses.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); VBox pane = (VBox) loaded.getRoot().lookup("#addressPane"); @SuppressWarnings("unchecked") ObservableList
addresses = (ObservableList
) loaded.property("addresses").getValue(); @@ -159,8 +154,8 @@ class RepeatAddressComponentsTest { person.setSelectedAddress(oak); URL fxml = RepeatAddressComponentsTest.class.getResource("repeat-addresses.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); @SuppressWarnings("unchecked") ComboBox
selection = (ComboBox
) loaded.getRoot().lookup("#selection"); assertSame(oak, selection.getValue()); @@ -192,15 +187,13 @@ class RepeatAddressComponentsTest { person.setWork(work); URL fxml = RepeatAddressComponentsTest.class.getResource("two-address-forms.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); - AddressForm cached = context.getComponent(AddressForm.class); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); AddressForm homeForm = (AddressForm) loaded.getRoot().lookup("#homeForm"); AddressForm workForm = (AddressForm) loaded.getRoot().lookup("#workForm"); assertNotNull(homeForm); assertNotNull(workForm); assertNotSame(homeForm, workForm); - assertSame(cached, context.getComponent(AddressForm.class)); assertSame(home, homeForm.getModel()); assertSame(work, workForm.getModel()); assertEquals("Main", ((TextField) homeForm.lookup("#streetField")).getText()); diff --git a/fx/src/test/java/de/neitzel/fx/view/ResizeAColumnTest.java b/fx/src/test/java/de/neitzel/fx/view/ResizeAColumnTest.java index 4cf8a04..81844b7 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ResizeAColumnTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ResizeAColumnTest.java @@ -2,7 +2,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.fixture.Host; import de.neitzel.fx.view.fixture.Visit; -import de.neitzel.injection.ApplicationContext; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.input.MouseButton; @@ -89,7 +88,7 @@ class ResizeAColumnTest { private static Table table(Host host) { URL fxml = ResizeAColumnTest.class.getResource("show-visits.fxml"); assertNotNull(fxml); - LoadedView loaded = ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component")); + LoadedView loaded = TestViews.load(fxml, host, new TestViews()); return (Table) loaded.getRoot().lookup("#visitsTable"); } diff --git a/fx/src/test/java/de/neitzel/fx/view/SearchTheChecklistTest.java b/fx/src/test/java/de/neitzel/fx/view/SearchTheChecklistTest.java index b449d01..3b4039a 100644 --- a/fx/src/test/java/de/neitzel/fx/view/SearchTheChecklistTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/SearchTheChecklistTest.java @@ -2,7 +2,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.fixture.Host; import de.neitzel.fx.view.fixture.Visit; -import de.neitzel.injection.ApplicationContext; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; @@ -110,7 +109,7 @@ class SearchTheChecklistTest { private static LoadedView load(Host host) { URL fxml = SearchTheChecklistTest.class.getResource("show-visits.fxml"); assertNotNull(fxml); - return ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component")); + return TestViews.load(fxml, host, new TestViews()); } /** diff --git a/fx/src/test/java/de/neitzel/fx/view/SelectARowTest.java b/fx/src/test/java/de/neitzel/fx/view/SelectARowTest.java index 49a5098..c5be027 100644 --- a/fx/src/test/java/de/neitzel/fx/view/SelectARowTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/SelectARowTest.java @@ -3,7 +3,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.component.VisitRow; import de.neitzel.fx.view.fixture.Host; import de.neitzel.fx.view.fixture.Visit; -import de.neitzel.injection.ApplicationContext; import javafx.scene.control.ScrollPane; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; @@ -107,7 +106,7 @@ class SelectARowTest { private static LoadedView load(Host host) { URL fxml = SelectARowTest.class.getResource("show-visits-selection.fxml"); assertNotNull(fxml); - return ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component")); + return TestViews.load(fxml, host, new TestViews()); } /** diff --git a/fx/src/test/java/de/neitzel/fx/view/ShowAListOfSimpleValuesTest.java b/fx/src/test/java/de/neitzel/fx/view/ShowAListOfSimpleValuesTest.java index 78f8ea1..fdc5a5d 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ShowAListOfSimpleValuesTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ShowAListOfSimpleValuesTest.java @@ -1,7 +1,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.fixture.Person; -import de.neitzel.injection.ApplicationContext; import javafx.application.Platform; import javafx.scene.control.ListView; import javafx.scene.layout.VBox; @@ -51,8 +50,8 @@ class ShowAListOfSimpleValuesTest { person.setTags(new ArrayList<>(List.of("red", "blue"))); URL fxml = ShowAListOfSimpleValuesTest.class.getResource("tags-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); VBox root = (VBox) loaded.getRoot(); assertEquals(1, root.getChildren().size()); @SuppressWarnings("unchecked") diff --git a/fx/src/test/java/de/neitzel/fx/view/ShowATableOfRowsTest.java b/fx/src/test/java/de/neitzel/fx/view/ShowATableOfRowsTest.java index 4845807..d0748af 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ShowATableOfRowsTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ShowATableOfRowsTest.java @@ -4,7 +4,6 @@ import de.neitzel.fx.view.component.CityFirstRow; import de.neitzel.fx.view.component.VisitRow; import de.neitzel.fx.view.fixture.Host; import de.neitzel.fx.view.fixture.Visit; -import de.neitzel.injection.ApplicationContext; import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.scene.Parent; @@ -191,7 +190,7 @@ class ShowATableOfRowsTest { void aTableWithNoColumnFailsToLoad() throws Exception { onFx(() -> { Host host = host(new Visit("Main", "Berlin")); - assertThrows(IllegalArgumentException.class, () -> load("show-visits-no-column.fxml", host)); + assertThrows(IllegalStateException.class, () -> load("show-visits-no-column.fxml", host)); }); } @@ -202,7 +201,7 @@ class ShowATableOfRowsTest { void aRepeatedAttributeFailsToLoad() throws Exception { onFx(() -> { Host host = host(new Visit("Main", "Berlin")); - assertThrows(IllegalArgumentException.class, () -> load("show-visits-duplicate.fxml", host)); + assertThrows(IllegalStateException.class, () -> load("show-visits-duplicate.fxml", host)); }); } @@ -213,7 +212,7 @@ class ShowATableOfRowsTest { void aComplexAttributeFailsToLoad() throws Exception { onFx(() -> { Host host = host(new Visit("Main", "Berlin")); - assertThrows(IllegalArgumentException.class, () -> load("show-visits-complex.fxml", host)); + assertThrows(IllegalStateException.class, () -> load("show-visits-complex.fxml", host)); }); } @@ -227,8 +226,8 @@ class ShowATableOfRowsTest { private static LoadedView load(String name, Host host) { URL fxml = ShowATableOfRowsTest.class.getResource(name); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component"); - return ViewLoader.load(fxml, host, context); + TestViews context = new TestViews(); + return TestViews.load(fxml, host, context); } /** diff --git a/fx/src/test/java/de/neitzel/fx/view/ShowAndEditOneAttributeTest.java b/fx/src/test/java/de/neitzel/fx/view/ShowAndEditOneAttributeTest.java index 15db4c3..0e6b648 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ShowAndEditOneAttributeTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ShowAndEditOneAttributeTest.java @@ -1,7 +1,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.fixture.Person; -import de.neitzel.injection.ApplicationContext; import javafx.application.Platform; import javafx.beans.property.IntegerProperty; import javafx.scene.control.Label; @@ -51,8 +50,8 @@ class ShowAndEditOneAttributeTest { Person person = new Person("Ada"); URL fxml = ShowAndEditOneAttributeTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField nameField = (TextField) loaded.getRoot().lookup("#nameField"); assertEquals("Ada", nameField.getText()); nameField.setText("Grace"); @@ -69,8 +68,8 @@ class ShowAndEditOneAttributeTest { Person person = new Person("Ada"); URL fxml = ShowAndEditOneAttributeTest.class.getResource("name-both-and-view.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField nameField = (TextField) loaded.getRoot().lookup("#nameField"); Label nameLabel = (Label) loaded.getRoot().lookup("#nameLabel"); assertEquals("Ada", nameLabel.getText()); @@ -91,8 +90,8 @@ class ShowAndEditOneAttributeTest { Person person = new Person("Ada"); URL fxml = ShowAndEditOneAttributeTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); person.setName("Grace"); TextField nameField = (TextField) loaded.getRoot().lookup("#nameField"); assertEquals("Ada", nameField.getText()); @@ -108,9 +107,9 @@ class ShowAndEditOneAttributeTest { Person person = new Person("Ada"); URL fxml = ShowAndEditOneAttributeTest.class.getResource("read-only-title.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, - () -> ViewLoader.load(fxml, person, context)); + TestViews context = new TestViews(); + IllegalStateException failure = assertThrows(IllegalStateException.class, + () -> TestViews.load(fxml, person, context)); assertTrue(failure.getMessage().contains("title")); }); } @@ -124,9 +123,9 @@ class ShowAndEditOneAttributeTest { Person person = new Person("Ada"); URL fxml = ShowAndEditOneAttributeTest.class.getResource("object-class.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, - () -> ViewLoader.load(fxml, person, context)); + TestViews context = new TestViews(); + IllegalStateException failure = assertThrows(IllegalStateException.class, + () -> TestViews.load(fxml, person, context)); assertTrue(failure.getMessage().contains("class")); }); } @@ -140,8 +139,8 @@ class ShowAndEditOneAttributeTest { Person person = new Person("Ada"); URL fxml = ShowAndEditOneAttributeTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); assertInstanceOf(IntegerProperty.class, loaded.property("age")); }); } diff --git a/fx/src/test/java/de/neitzel/fx/view/ShowMessagesWhenAskedTest.java b/fx/src/test/java/de/neitzel/fx/view/ShowMessagesWhenAskedTest.java index afac235..0f12e73 100644 --- a/fx/src/test/java/de/neitzel/fx/view/ShowMessagesWhenAskedTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/ShowMessagesWhenAskedTest.java @@ -1,7 +1,6 @@ package de.neitzel.fx.view; import de.neitzel.fx.view.fixture.Person; -import de.neitzel.injection.ApplicationContext; import javafx.application.Platform; import javafx.scene.Node; import javafx.scene.Parent; @@ -60,8 +59,8 @@ class ShowMessagesWhenAskedTest { Person person = new Person("Ada"); URL fxml = ShowMessagesWhenAskedTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Parent root = loaded.getRoot(); Set nodesBefore = new HashSet<>(root.lookupAll("*")); Set windowsBefore = snapshotWindows(); @@ -82,8 +81,8 @@ class ShowMessagesWhenAskedTest { Person person = new Person("Ada"); URL fxml = ShowMessagesWhenAskedTest.class.getResource("latest-message.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Label messageLabel = (Label) loaded.getRoot().lookup("#messageLabel"); loaded.getViewModel().addMessage( new Message(Message.Severity.INFO, "saved the person", "form")); @@ -103,8 +102,8 @@ class ShowMessagesWhenAskedTest { Person person = new Person("Ada"); URL fxml = ShowMessagesWhenAskedTest.class.getResource("name-both-ways.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); Set windowsBefore = snapshotWindows(); MessagePopup.showNewMessages(loaded.getViewModel()); assertEquals(windowsBefore, snapshotWindows()); @@ -129,8 +128,8 @@ class ShowMessagesWhenAskedTest { person.setAge(42); URL fxml = ShowMessagesWhenAskedTest.class.getResource("age-both-converted.fxml"); assertNotNull(fxml); - ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture"); - LoadedView loaded = ViewLoader.load(fxml, person, context); + TestViews context = new TestViews(); + LoadedView loaded = TestViews.load(fxml, person, context); TextField ageField = (TextField) loaded.getRoot().lookup("#ageField"); Set windowsBefore = snapshotWindows(); MessagePopup.showNewMessages(loaded.getViewModel()); diff --git a/fx/src/test/java/de/neitzel/fx/view/SortOneColumnTest.java b/fx/src/test/java/de/neitzel/fx/view/SortOneColumnTest.java index 0061d1c..c390c6e 100644 --- a/fx/src/test/java/de/neitzel/fx/view/SortOneColumnTest.java +++ b/fx/src/test/java/de/neitzel/fx/view/SortOneColumnTest.java @@ -4,7 +4,6 @@ import de.neitzel.fx.view.component.VisitRow; import de.neitzel.fx.view.fixture.Host; import de.neitzel.fx.view.fixture.Role; import de.neitzel.fx.view.fixture.Visit; -import de.neitzel.injection.ApplicationContext; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; @@ -148,7 +147,7 @@ class SortOneColumnTest { private static LoadedView load(String name, Host host) { URL fxml = SortOneColumnTest.class.getResource(name); assertNotNull(fxml); - return ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component")); + return TestViews.load(fxml, host, new TestViews()); } /** diff --git a/fx/src/test/java/de/neitzel/fx/view/TestViews.java b/fx/src/test/java/de/neitzel/fx/view/TestViews.java new file mode 100644 index 0000000..b403c11 --- /dev/null +++ b/fx/src/test/java/de/neitzel/fx/view/TestViews.java @@ -0,0 +1,87 @@ +package de.neitzel.fx.view; + +import de.neitzel.fx.view.chosen.BadgeController; +import de.neitzel.fx.view.chosen.CaptionAddressForm; +import de.neitzel.fx.view.chosen.DeskController; +import de.neitzel.fx.view.chosen.DeskGreeting; +import de.neitzel.fx.view.chosen.HandedNameController; +import de.neitzel.fx.view.chosen.TitledController; +import de.neitzel.fx.view.command.CommandController; +import de.neitzel.fx.view.component.ActionRow; +import de.neitzel.fx.view.component.AddressForm; +import de.neitzel.fx.view.component.CityFirstRow; +import de.neitzel.fx.view.component.EnvelopeForm; +import de.neitzel.fx.view.component.StreetCaption; +import de.neitzel.fx.view.component.VisitRow; +import de.neitzel.fx.view.computed.WorkingAgeController; +import de.neitzel.fx.view.fixture.AgeUnit; +import de.neitzel.fx.view.fixture.CheckedStreetConverter; +import de.neitzel.fx.view.fixture.PrefixedAgeConverter; +import de.neitzel.fx.view.fixture.ShownAgeConverter; +import de.neitzel.fx.view.managed.ViewController; +import de.neitzel.fx.view.readable.ReadableSourcesController; +import de.neitzel.fx.view.selection.SelectionSummaryController; +import java.net.URL; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; + +/** Explicit registration for the FX tests. Each test shares Models only within its own context. */ +final class TestViews implements ViewDependencies { + private static final Set> COMPONENTS = Set.of(ActionRow.class, AddressForm.class, + CaptionAddressForm.class, CityFirstRow.class, EnvelopeForm.class, VisitRow.class); + + private final ViewModelContext models = new ViewModelContext(); + private final ViewController.Registry registry = new ViewController.Registry(); + private final StreetCaption captions = new StreetCaption(); + private final DeskGreeting greeting = new DeskGreeting(); + + private final Map, Object> services = Map.of( + ViewController.Registry.class, registry, + CheckedStreetConverter.class, new CheckedStreetConverter(), + PrefixedAgeConverter.class, new PrefixedAgeConverter(new AgeUnit()), + ShownAgeConverter.class, new ShownAgeConverter(), + ReadableSourcesController.Caption.class, new ReadableSourcesController.Caption()); + + private final Map, Supplier> factories = Map.ofEntries( + Map.entry(ActionRow.class, ActionRow::new), + Map.entry(AddressForm.class, () -> new AddressForm(captions)), + Map.entry(BadgeController.class, BadgeController::new), + Map.entry(CaptionAddressForm.class, CaptionAddressForm::new), + Map.entry(CityFirstRow.class, CityFirstRow::new), + Map.entry(CommandController.class, CommandController::new), + Map.entry(DeskController.class, () -> new DeskController(greeting)), + Map.entry(EnvelopeForm.class, EnvelopeForm::new), + Map.entry(HandedNameController.class, HandedNameController::new), + Map.entry(ReadableSourcesController.class, ReadableSourcesController::new), + Map.entry(SelectionSummaryController.class, SelectionSummaryController::new), + Map.entry(TitledController.class, TitledController::new), + Map.entry(ViewController.class, () -> new ViewController(registry)), + Map.entry(VisitRow.class, VisitRow::new), + Map.entry(WorkingAgeController.class, WorkingAgeController::new)); + + static LoadedView load(URL fxml, Object model, TestViews dependencies) { + return ViewLoader.loadWithDependencies(fxml, model, dependencies, dependencies.models); + } + + @Override + public boolean isComponent(Class type) { + return COMPONENTS.contains(type); + } + + @Override + public Optional findService(Class type) { + return Optional.ofNullable(services.get(type)).map(type::cast); + } + + @Override + public ViewObject createViewObject(Class type) { + Supplier factory = factories.get(type); + if (factory == null) throw new IllegalArgumentException("Unregistered test View type " + type.getName()); + T object = type.cast(factory.get()); + return new ViewObject<>(object, () -> { + if (object instanceof ViewController controller) controller.close(); + }); + } +} diff --git a/fx/src/test/java/de/neitzel/fx/view/ViewDependenciesTest.java b/fx/src/test/java/de/neitzel/fx/view/ViewDependenciesTest.java new file mode 100644 index 0000000..cc562e9 --- /dev/null +++ b/fx/src/test/java/de/neitzel/fx/view/ViewDependenciesTest.java @@ -0,0 +1,198 @@ +package de.neitzel.fx.view; + +import de.neitzel.fx.i18n.Localizer; +import de.neitzel.fx.view.component.AddressForm; +import de.neitzel.fx.view.component.StreetCaption; +import de.neitzel.fx.view.component.VisitRow; +import de.neitzel.fx.view.fixture.Address; +import de.neitzel.fx.view.fixture.AgeUnit; +import de.neitzel.fx.view.fixture.Host; +import de.neitzel.fx.view.fixture.Person; +import de.neitzel.fx.view.fixture.PrefixedAgeConverter; +import de.neitzel.fx.view.fixture.Visit; +import de.neitzel.fx.view.managed.ViewController; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; +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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ViewDependenciesTest { + + @BeforeAll + static void startFx() throws InterruptedException { + FxThread.start(); + } + + @Test + void createsControllersForEachViewAndIncludeAndReleasesEachOnce() throws Exception { + FxThread.onFx(() -> { + var source = new Dependencies(); + try (var models = new ViewModelContext()) { + var first = load("adapter-view.fxml", new Person("Ada"), source, models); + var second = load("adapter-view.fxml", new Person("Grace"), source, models); + var parent = controller(first, "#parent"); + var included = controller(first, "#included"); + var other = controller(second, "#parent"); + assertEquals(4, source.releases.size()); + assertNotSame(parent, included); + assertNotSame(parent, other); + first.close(); + first.close(); + assertEquals(1, source.releases.get(parent)); + assertEquals(1, source.releases.get(included)); + assertEquals(0, source.releases.get(other)); + assertEquals(0, parent.getCloseCount()); + assertSame(source.registry, source.findService(ViewController.Registry.class).orElseThrow()); + } + assertTrue(source.releases.values().stream().allMatch(count -> count == 1)); + }); + } + + @Test + void createsExactComponentsAndReleasesChildrenAsTheirModelsAreRemoved() throws Exception { + FxThread.onFx(() -> { + var source = new Dependencies(); + var person = new Person("Ada"); + person.setAddresses(new ArrayList<>(List.of(new Address("Main")))); + var host = new Host(); + host.setVisits(new ArrayList<>(List.of(new Visit("Main", "Darmstadt")))); + try (var models = new ViewModelContext()) { + load("repeat-addresses.fxml", person, source, models); + load("show-visits.fxml", host, source, models); + var address = source.releases.keySet().stream().filter(AddressForm.class::isInstance) + .map(AddressForm.class::cast).findFirst().orElseThrow(); + var row = source.releases.keySet().stream().filter(VisitRow.class::isInstance) + .findFirst().orElseThrow(); + assertEquals("Lane", address.getCaption()); + assertNotNull(address.receivedViewModel()); + assertEquals("kept", address.streetTextAtHandOff()); + person.getAddresses().clear(); + host.getVisits().clear(); + assertEquals(1, source.releases.get(address)); + assertEquals(1, source.releases.get(row)); + var standalone = ViewLoader.loadComponentWithDependencies( + AddressForm.class, new Address("New"), source, models); + assertNotSame(address, standalone.getRoot()); + + source.addressFactory = ignored -> new AddressForm(new StreetCaption()) {}; + var wrong = assertThrows(IllegalStateException.class, () -> + ViewLoader.loadComponentWithDependencies(AddressForm.class, new Address("Bad"), source, models)); + assertTrue(wrong.getMessage().contains("Expected exact Component type")); + source.addressFactory = null; + var missing = assertThrows(IllegalStateException.class, () -> + ViewLoader.loadComponentWithDependencies(AddressForm.class, new Address("Bad"), source, models)); + assertTrue(missing.getMessage().contains("No Component registered")); + } + assertTrue(source.releases.values().stream().allMatch(count -> count == 1)); + }); + } + + @Test + void rollsBackEveryAcquiredObjectWhenAComponentLoadFails() throws Exception { + FxThread.onFx(() -> { + var source = new Dependencies(); + source.failOnRelease = true; + try (var models = new ViewModelContext()) { + var failure = assertThrows(IllegalStateException.class, () -> + load("adapter-invalid.fxml", new Person("Ada"), source, models)); + assertTrue(failure.getMessage().contains("adapter-invalid.fxml")); + assertTrue(failure.getCause().getSuppressed().length > 0); + assertEquals(2, source.releases.size()); + assertTrue(source.releases.values().stream().allMatch(count -> count == 1)); + } + }); + } + + @Test + void resolvesConvertersAndDistinguishesMissingServicesFromLookupFailure() throws Exception { + FxThread.onFx(() -> { + var source = new Dependencies(); + var person = new Person("Ada"); + person.setAge(24); + try (var models = new ViewModelContext()) { + var loaded = load("age-both-converted.fxml", person, source, models); + var fields = ((VBox) loaded.getRoot()).getChildren(); + assertEquals(new AgeUnit().prefix() + 24, ((TextField) fields.getFirst()).getText()); + source.services.remove(PrefixedAgeConverter.class); + var missing = assertThrows(IllegalStateException.class, () -> + load("age-both-converted.fxml", person, source, models)); + assertTrue(missing.getMessage().contains(PrefixedAgeConverter.class.getName())); + source.services.put(Localizer.class, new Localizer(Locale.GERMAN, Locale.ENGLISH, + new Localizer.Catalog(getClass(), "LocalizerTestApp"))); + var localized = load("adapter-localized.fxml", person, source, models); + assertEquals("Application", localized.getRoot().getAccessibleText()); + source.lookupFailure = new IllegalArgumentException("Ambiguous Localizer"); + var unavailable = assertThrows(IllegalStateException.class, () -> + load("adapter-view.fxml", person, source, models)); + assertTrue(unavailable.getMessage().contains(Localizer.class.getName())); + assertSame(source.lookupFailure, unavailable.getCause().getCause()); + } + }); + } + + private static ViewController controller(LoadedView view, String id) { + return (ViewController) view.getRoot().lookup(id).getUserData(); + } + + private static LoadedView load(String resource, Object model, ViewDependencies source, ViewModelContext models) { + URL fxml = ViewDependenciesTest.class.getResource(resource); + return ViewLoader.loadWithDependencies(fxml, model, source, models); + } + + private static final class Dependencies implements ViewDependencies { + private final ViewController.Registry registry = new ViewController.Registry(); + private final Map, Object> services = new HashMap<>(Map.of( + ViewController.Registry.class, registry, + PrefixedAgeConverter.class, new PrefixedAgeConverter(new AgeUnit()))); + private final Map releases = new IdentityHashMap<>(); + private Function addressFactory = AddressForm::new; + private RuntimeException lookupFailure; + private boolean failOnRelease; + + @Override + public boolean isComponent(Class type) { + return type == VisitRow.class || (type == AddressForm.class && addressFactory != null); + } + + @Override + public Optional findService(Class type) { + if (type == Localizer.class && lookupFailure != null) throw lookupFailure; + return Optional.ofNullable(services.get(type)).map(type::cast); + } + + @Override + public ViewObject createViewObject(Class type) { + Object instance; + if (type == ViewController.class) { + instance = new ViewController(registry); + } else if (type == AddressForm.class) { + instance = addressFactory.apply(new StreetCaption()); + } else if (type == VisitRow.class) { + instance = new VisitRow(); + } else { + throw new AssertionError("Unexpected DI type " + type); + } + releases.put(instance, 0); + return new ViewObject<>(type.cast(instance), () -> { + releases.merge(instance, 1, Integer::sum); + if (failOnRelease) throw new IllegalStateException("release failed"); + }); + } + } +} diff --git a/fx/src/test/java/de/neitzel/fx/view/chosen/BadgeController.java b/fx/src/test/java/de/neitzel/fx/view/chosen/BadgeController.java index 41037b3..b62fd92 100644 --- a/fx/src/test/java/de/neitzel/fx/view/chosen/BadgeController.java +++ b/fx/src/test/java/de/neitzel/fx/view/chosen/BadgeController.java @@ -1,12 +1,11 @@ package de.neitzel.fx.view.chosen; import de.neitzel.fx.view.ViewModelClass; -import jakarta.inject.Singleton; /** * Controller that names {@link BadgeViewModel} as a replacement ViewModel. */ -@Singleton + @ViewModelClass(BadgeViewModel.class) public class BadgeController { } diff --git a/fx/src/test/java/de/neitzel/fx/view/chosen/CaptionAddressForm.java b/fx/src/test/java/de/neitzel/fx/view/chosen/CaptionAddressForm.java index 9895fa5..5d5185e 100644 --- a/fx/src/test/java/de/neitzel/fx/view/chosen/CaptionAddressForm.java +++ b/fx/src/test/java/de/neitzel/fx/view/chosen/CaptionAddressForm.java @@ -1,7 +1,6 @@ package de.neitzel.fx.view.chosen; import de.neitzel.fx.view.ViewModelClass; -import jakarta.inject.Singleton; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.layout.VBox; @@ -9,7 +8,7 @@ import javafx.scene.layout.VBox; /** * Component that names {@link StreetTitleViewModel} for the address it shows. */ -@Singleton + @ViewModelClass(StreetTitleViewModel.class) public class CaptionAddressForm extends VBox { diff --git a/fx/src/test/java/de/neitzel/fx/view/chosen/DeskController.java b/fx/src/test/java/de/neitzel/fx/view/chosen/DeskController.java index d45bb8e..6a31d7b 100644 --- a/fx/src/test/java/de/neitzel/fx/view/chosen/DeskController.java +++ b/fx/src/test/java/de/neitzel/fx/view/chosen/DeskController.java @@ -1,12 +1,10 @@ package de.neitzel.fx.view.chosen; -import jakarta.inject.Inject; -import jakarta.inject.Singleton; /** * Controller that shows a greeting supplied by an injected service. */ -@Singleton + public class DeskController { /** @@ -19,7 +17,7 @@ public class DeskController { * * @param greeting the service that supplies the greeting */ - @Inject + public DeskController(DeskGreeting greeting) { this.greeting = greeting; } diff --git a/fx/src/test/java/de/neitzel/fx/view/chosen/DeskGreeting.java b/fx/src/test/java/de/neitzel/fx/view/chosen/DeskGreeting.java index d48f35f..3179a09 100644 --- a/fx/src/test/java/de/neitzel/fx/view/chosen/DeskGreeting.java +++ b/fx/src/test/java/de/neitzel/fx/view/chosen/DeskGreeting.java @@ -1,11 +1,10 @@ package de.neitzel.fx.view.chosen; -import jakarta.inject.Singleton; /** * Service whose text a controller must show, so a test can see that injection ran. */ -@Singleton + public class DeskGreeting { /** diff --git a/fx/src/test/java/de/neitzel/fx/view/chosen/HandedNameController.java b/fx/src/test/java/de/neitzel/fx/view/chosen/HandedNameController.java index e2f88fd..4b1d565 100644 --- a/fx/src/test/java/de/neitzel/fx/view/chosen/HandedNameController.java +++ b/fx/src/test/java/de/neitzel/fx/view/chosen/HandedNameController.java @@ -2,12 +2,11 @@ package de.neitzel.fx.view.chosen; import de.neitzel.fx.view.HasViewModel; import de.neitzel.fx.view.ViewModel; -import jakarta.inject.Singleton; /** * Controller whose computed value is taken from the ViewModel handed over before bindings. */ -@Singleton + public class HandedNameController implements HasViewModel { /** diff --git a/fx/src/test/java/de/neitzel/fx/view/chosen/TitledController.java b/fx/src/test/java/de/neitzel/fx/view/chosen/TitledController.java index 3fb9350..2d00acc 100644 --- a/fx/src/test/java/de/neitzel/fx/view/chosen/TitledController.java +++ b/fx/src/test/java/de/neitzel/fx/view/chosen/TitledController.java @@ -1,12 +1,11 @@ package de.neitzel.fx.view.chosen; import de.neitzel.fx.view.ViewModelClass; -import jakarta.inject.Singleton; /** * Controller that names {@link titledviewmodel} for its view. */ -@Singleton + @ViewModelClass(TitledViewModel.class) public class TitledController { } diff --git a/fx/src/test/java/de/neitzel/fx/view/command/CommandController.java b/fx/src/test/java/de/neitzel/fx/view/command/CommandController.java index 0bb8df5..ddec5c2 100644 --- a/fx/src/test/java/de/neitzel/fx/view/command/CommandController.java +++ b/fx/src/test/java/de/neitzel/fx/view/command/CommandController.java @@ -3,12 +3,11 @@ package de.neitzel.fx.view.command; import de.neitzel.fx.view.Command; import de.neitzel.fx.view.ViewModel; import de.neitzel.fx.view.ViewModelClass; -import jakarta.inject.Named; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import lombok.Getter; -@Named + @ViewModelClass(CommandController.Model.class) public final class CommandController { diff --git a/fx/src/test/java/de/neitzel/fx/view/component/ActionRow.java b/fx/src/test/java/de/neitzel/fx/view/component/ActionRow.java index d4fe816..76e353b 100644 --- a/fx/src/test/java/de/neitzel/fx/view/component/ActionRow.java +++ b/fx/src/test/java/de/neitzel/fx/view/component/ActionRow.java @@ -1,7 +1,5 @@ package de.neitzel.fx.view.component; -import jakarta.inject.Inject; -import jakarta.inject.Singleton; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.layout.HBox; @@ -9,7 +7,7 @@ import javafx.scene.layout.HBox; /** * A Row with street and city fields and a control after them. */ -@Singleton + public class ActionRow extends HBox { /** @@ -20,7 +18,7 @@ public class ActionRow extends HBox { /** * Creates a row. */ - @Inject + public ActionRow() { } diff --git a/fx/src/test/java/de/neitzel/fx/view/component/AddressForm.java b/fx/src/test/java/de/neitzel/fx/view/component/AddressForm.java index c72716d..edf0146 100644 --- a/fx/src/test/java/de/neitzel/fx/view/component/AddressForm.java +++ b/fx/src/test/java/de/neitzel/fx/view/component/AddressForm.java @@ -2,8 +2,6 @@ package de.neitzel.fx.view.component; import de.neitzel.fx.view.HasViewModel; import de.neitzel.fx.view.ViewModel; -import jakarta.inject.Inject; -import jakarta.inject.Singleton; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; @@ -16,7 +14,7 @@ import javafx.scene.layout.VBox; *

* The container injects the caption service. the street label shows that service's prefix. */ -@Singleton + public class AddressForm extends VBox implements HasViewModel { /** @@ -54,7 +52,7 @@ public class AddressForm extends VBox implements HasViewModel { * * @param captions the service that supplies the street prefix */ - @Inject + public AddressForm(StreetCaption captions) { this.captions = captions; } diff --git a/fx/src/test/java/de/neitzel/fx/view/component/CityFirstRow.java b/fx/src/test/java/de/neitzel/fx/view/component/CityFirstRow.java index 1686efc..e9e1678 100644 --- a/fx/src/test/java/de/neitzel/fx/view/component/CityFirstRow.java +++ b/fx/src/test/java/de/neitzel/fx/view/component/CityFirstRow.java @@ -1,7 +1,5 @@ package de.neitzel.fx.view.component; -import jakarta.inject.Inject; -import jakarta.inject.Singleton; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.layout.HBox; @@ -9,7 +7,7 @@ import javafx.scene.layout.HBox; /** * A Row that lays city out before street. */ -@Singleton + public class CityFirstRow extends HBox { /** @@ -20,7 +18,7 @@ public class CityFirstRow extends HBox { /** * Creates a row. */ - @Inject + public CityFirstRow() { } diff --git a/fx/src/test/java/de/neitzel/fx/view/component/EnvelopeForm.java b/fx/src/test/java/de/neitzel/fx/view/component/EnvelopeForm.java index f4b7c32..b6e0d40 100644 --- a/fx/src/test/java/de/neitzel/fx/view/component/EnvelopeForm.java +++ b/fx/src/test/java/de/neitzel/fx/view/component/EnvelopeForm.java @@ -1,6 +1,5 @@ package de.neitzel.fx.view.component; -import jakarta.inject.Singleton; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.layout.VBox; @@ -8,7 +7,7 @@ import javafx.scene.layout.VBox; /** * Component that shows one envelope and the address component inside it. */ -@Singleton + public class EnvelopeForm extends VBox { /** diff --git a/fx/src/test/java/de/neitzel/fx/view/component/StreetCaption.java b/fx/src/test/java/de/neitzel/fx/view/component/StreetCaption.java index e91e914..ec2c2a7 100644 --- a/fx/src/test/java/de/neitzel/fx/view/component/StreetCaption.java +++ b/fx/src/test/java/de/neitzel/fx/view/component/StreetCaption.java @@ -1,11 +1,10 @@ package de.neitzel.fx.view.component; -import jakarta.inject.Singleton; /** * Service whose text an address component must show, so a test can see that injection ran. */ -@Singleton + public class StreetCaption { /** diff --git a/fx/src/test/java/de/neitzel/fx/view/component/VisitRow.java b/fx/src/test/java/de/neitzel/fx/view/component/VisitRow.java index fa769d5..268a608 100644 --- a/fx/src/test/java/de/neitzel/fx/view/component/VisitRow.java +++ b/fx/src/test/java/de/neitzel/fx/view/component/VisitRow.java @@ -1,8 +1,6 @@ package de.neitzel.fx.view.component; import de.neitzel.fx.view.fixture.Visit; -import jakarta.inject.Inject; -import jakarta.inject.Singleton; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; @@ -12,7 +10,7 @@ import javafx.scene.layout.HBox; /** * A Row that shows a visit's street and city, street first. */ -@Singleton + public class VisitRow extends HBox { /** @@ -29,7 +27,7 @@ public class VisitRow extends HBox { /** * Creates a row. */ - @Inject + public VisitRow() { model.addListener((observable, previous, current) -> applyHeight(current)); } diff --git a/fx/src/test/java/de/neitzel/fx/view/computed/WorkingAgeController.java b/fx/src/test/java/de/neitzel/fx/view/computed/WorkingAgeController.java index 9bbb1c4..f69ecc9 100644 --- a/fx/src/test/java/de/neitzel/fx/view/computed/WorkingAgeController.java +++ b/fx/src/test/java/de/neitzel/fx/view/computed/WorkingAgeController.java @@ -1,13 +1,12 @@ package de.neitzel.fx.view.computed; -import jakarta.inject.Singleton; import javafx.fxml.FXML; import javafx.scene.control.TextField; /** * Controller that derives a label from the name field and does not write the model. */ -@Singleton + public class WorkingAgeController { /** diff --git a/fx/src/test/java/de/neitzel/fx/view/fixture/AgeUnit.java b/fx/src/test/java/de/neitzel/fx/view/fixture/AgeUnit.java index 212329a..f3f8940 100644 --- a/fx/src/test/java/de/neitzel/fx/view/fixture/AgeUnit.java +++ b/fx/src/test/java/de/neitzel/fx/view/fixture/AgeUnit.java @@ -1,11 +1,10 @@ package de.neitzel.fx.view.fixture; -import jakarta.inject.Singleton; /** * Service whose text a converter must show, so a test can see that injection ran. */ -@Singleton + public class AgeUnit { /** diff --git a/fx/src/test/java/de/neitzel/fx/view/fixture/CheckedStreetConverter.java b/fx/src/test/java/de/neitzel/fx/view/fixture/CheckedStreetConverter.java index 34c5224..f19c130 100644 --- a/fx/src/test/java/de/neitzel/fx/view/fixture/CheckedStreetConverter.java +++ b/fx/src/test/java/de/neitzel/fx/view/fixture/CheckedStreetConverter.java @@ -1,12 +1,11 @@ package de.neitzel.fx.view.fixture; import de.neitzel.fx.view.Converter; -import jakarta.inject.Singleton; /** * Accepts a street written as {@code ok } plus the street, and rejects anything else. */ -@Singleton + public class CheckedStreetConverter implements Converter { /** diff --git a/fx/src/test/java/de/neitzel/fx/view/fixture/PrefixedAgeConverter.java b/fx/src/test/java/de/neitzel/fx/view/fixture/PrefixedAgeConverter.java index 3cea0fc..8f5ed25 100644 --- a/fx/src/test/java/de/neitzel/fx/view/fixture/PrefixedAgeConverter.java +++ b/fx/src/test/java/de/neitzel/fx/view/fixture/PrefixedAgeConverter.java @@ -1,13 +1,11 @@ package de.neitzel.fx.view.fixture; import de.neitzel.fx.view.Converter; -import jakarta.inject.Inject; -import jakarta.inject.Singleton; /** * Converts an age using the prefix from {@link AgeUnit}. */ -@Singleton + public class PrefixedAgeConverter implements Converter { /** @@ -20,7 +18,7 @@ public class PrefixedAgeConverter implements Converter { * * @param ageUnit the service that supplies the prefix */ - @Inject + public PrefixedAgeConverter(AgeUnit ageUnit) { this.ageUnit = ageUnit; } diff --git a/fx/src/test/java/de/neitzel/fx/view/fixture/ShownAgeConverter.java b/fx/src/test/java/de/neitzel/fx/view/fixture/ShownAgeConverter.java index 50caae2..7b9a331 100644 --- a/fx/src/test/java/de/neitzel/fx/view/fixture/ShownAgeConverter.java +++ b/fx/src/test/java/de/neitzel/fx/view/fixture/ShownAgeConverter.java @@ -1,12 +1,11 @@ package de.neitzel.fx.view.fixture; import de.neitzel.fx.view.Converter; -import jakarta.inject.Singleton; /** * Shows an age and has no reverse conversion. */ -@Singleton + public class ShownAgeConverter implements Converter { /** diff --git a/fx/src/test/java/de/neitzel/fx/view/managed/ViewController.java b/fx/src/test/java/de/neitzel/fx/view/managed/ViewController.java index aa1f6bc..64bf5c1 100644 --- a/fx/src/test/java/de/neitzel/fx/view/managed/ViewController.java +++ b/fx/src/test/java/de/neitzel/fx/view/managed/ViewController.java @@ -1,21 +1,19 @@ 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() { } } @@ -29,7 +27,7 @@ public class ViewController implements AutoCloseable { @Getter private int closeCount; - @Inject + public ViewController(Registry registry) { this.registry = registry; } diff --git a/fx/src/test/java/de/neitzel/fx/view/readable/ReadableSourcesController.java b/fx/src/test/java/de/neitzel/fx/view/readable/ReadableSourcesController.java index cf177d1..28480a7 100644 --- a/fx/src/test/java/de/neitzel/fx/view/readable/ReadableSourcesController.java +++ b/fx/src/test/java/de/neitzel/fx/view/readable/ReadableSourcesController.java @@ -3,7 +3,6 @@ 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; @@ -14,7 +13,7 @@ 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 { @@ -52,7 +51,7 @@ public class ReadableSourcesController { } /** 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) { diff --git a/fx/src/test/java/de/neitzel/fx/view/selection/SelectionSummaryController.java b/fx/src/test/java/de/neitzel/fx/view/selection/SelectionSummaryController.java index b1a39c9..1752366 100644 --- a/fx/src/test/java/de/neitzel/fx/view/selection/SelectionSummaryController.java +++ b/fx/src/test/java/de/neitzel/fx/view/selection/SelectionSummaryController.java @@ -2,11 +2,10 @@ package de.neitzel.fx.view.selection; import de.neitzel.fx.view.DataGridSelection; import de.neitzel.fx.view.ViewModelClass; -import jakarta.inject.Singleton; import javafx.beans.value.ObservableValue; /** Supplies a read-only summary of the selected keys and available rows. */ -@Singleton + @ViewModelClass(SelectionSummaryController.Summary.class) public class SelectionSummaryController { diff --git a/fx/src/test/resources/de/neitzel/fx/view/adapter-include.fxml b/fx/src/test/resources/de/neitzel/fx/view/adapter-include.fxml new file mode 100644 index 0000000..5046277 --- /dev/null +++ b/fx/src/test/resources/de/neitzel/fx/view/adapter-include.fxml @@ -0,0 +1,5 @@ + + + + + diff --git a/fx/src/test/resources/de/neitzel/fx/view/adapter-invalid.fxml b/fx/src/test/resources/de/neitzel/fx/view/adapter-invalid.fxml new file mode 100644 index 0000000..ba26a15 --- /dev/null +++ b/fx/src/test/resources/de/neitzel/fx/view/adapter-invalid.fxml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/fx/src/test/resources/de/neitzel/fx/view/adapter-localized.fxml b/fx/src/test/resources/de/neitzel/fx/view/adapter-localized.fxml new file mode 100644 index 0000000..de872b6 --- /dev/null +++ b/fx/src/test/resources/de/neitzel/fx/view/adapter-localized.fxml @@ -0,0 +1,2 @@ + + diff --git a/fx/src/test/resources/de/neitzel/fx/view/adapter-view.fxml b/fx/src/test/resources/de/neitzel/fx/view/adapter-view.fxml new file mode 100644 index 0000000..9dd8a88 --- /dev/null +++ b/fx/src/test/resources/de/neitzel/fx/view/adapter-view.fxml @@ -0,0 +1,6 @@ + + + + + + diff --git a/injection/README.md b/injection/README.md index 8960d53..3298dac 100644 --- a/injection/README.md +++ b/injection/README.md @@ -8,7 +8,7 @@ The worked example is the person desk in `fx-example`, package `de.neitzel.fx.ex ## Quick start -Depend on the module. It brings Reflections 0.10.2 and `jakarta.inject-api` 2.0.1 (plus shared logging dependencies). The parent artifact is `de.neitzel.lib:neitzellib:1.0.6`. Java 25. +Depend on the module. It brings Reflections 0.10.2 and `jakarta.inject-api` 2.0.1 (plus shared logging dependencies). The published example below uses `de.neitzel.lib:injection:1.0.6` and Java 25. A source build uses the version declared in the checkout's parent POM. ```xml @@ -20,14 +20,21 @@ Depend on the module. It brings Reflections 0.10.2 and `jakarta.inject-api` 2.0. Mark a class with `jakarta.inject.Singleton` or `jakarta.inject.Named`, and take dependencies with `jakarta.inject.Inject`. Open a context on the package that contains those classes. -The desk does it this way. `DeskApp` names the scan root and opens the context. `ViewLoader` then asks that context for the controller, the forms, and the converters. `AgeSuffix` is a `@Named` service. `AgeConverter` takes that service in its constructor. +In the current Person Desk, `DeskApp` names the scan root and its +`dependencies(person)` method creates the context and configures the optional +FX adapter. That adapter supplies the Controller, forms and Converters. +`AgeSuffix` is a `@Named` service that `AgeConverter` receives in its constructor. +See the [FX adapter setup](../fx-injection/README.md). ```java -ApplicationContext context = new ApplicationContext(DeskApp.class); -LoadedView loaded = ViewLoader.load( - DeskController.class.getResource("Desk.fxml"), DeskApp.sample(), context); +var person = DeskApp.sample(); +var models = new ViewModelContext(); +var loaded = ViewLoader.loadWithDependencies( + DeskController.class.getResource("Desk.fxml"), person, DeskApp.dependencies(person), models); ``` +The example closes the Model context when its window is hidden. + `DeskApp.start` is that load, then the scene. The class carries `@Config(basePackage = "de.neitzel.fx.example")`. ```java @@ -74,13 +81,13 @@ The desk uses all three places: | Place | Desk class | What is injected | | --- | --- | --- | | Constructor | `AgeConverter` | `AgeSuffix` | -| Constructor | `VisitRow` | `DeskController` | +| Constructor | `VisitRow` | `VisitActions` | | Field | `StreetConverter` | `StreetPolicy`, on a private field, after the no-arg constructor | | Setter | `AddressForm.setHeading` | `FormHeading` | `AddressForm.initialize` runs later, when FXML loads the form, and copies `heading.text()` onto the label. The setter has already run by then. The home form shows the word `Address`. -`VisitRow` is created again for every table row. Each row receives the same `DeskController`, because the controller is a singleton and dependencies are loaded with `getComponent`. +Each table row has a fresh `VisitRow`. The rows receive the shared `VisitActions` service configured for the current Person. ## Ask for an instance @@ -92,9 +99,9 @@ public void addSingleton(Class type, T instance) `getComponent` returns the cached instance. The first call creates it and stores it. Later calls return that object. -`createComponent` always builds a new instance and does not store it. Dependencies of that instance still come from `getComponent`, so they are the shared singletons. `fx` uses this for a second component of the same class in one load, and for every repeated row and table row. The home `AddressForm` is the cached instance. Each `VisitForm` and each `VisitRow` is a new instance, and each of them still sees the one `DeskController` and the one `StreetConverter`. +`createComponent` always builds a new instance and does not store it. Dependencies of that instance still come from `getComponent`, so they are the shared singletons. The optional FX adapter calls `createComponent` for every Controller and Component, including the home form and each Repeat or Table row. It resolves shared Converters and the optional Localizer with `getComponent`. -A type the context does not know produces `IllegalArgumentException` with the message `No component found for type:` and the class name. A failure while calling the constructor or writing a member is wrapped as `RuntimeException` whose message starts with `Fehler beim Erstellen der Instanz für`, with the original failure as the cause. +An unknown type produces `IllegalArgumentException` with the message `No component found for type:` and the class name. In the separated development build, the concrete exception is `MissingComponentException`, a subclass of `IllegalArgumentException` that exposes the missing type. A failure while calling the constructor or writing a member is wrapped as `RuntimeException` whose message starts with `Fehler beim Erstellen der Instanz für`, with the original failure as the cause. The context is a plain map. It is not safe to share across threads without external locking. There is no shutdown and no list-all method. @@ -162,7 +169,7 @@ A class with a single `String` constructor and no `@Inject` takes that construct `createComponent` on a manually added type has no injection constructor and fails. -The desk does not call `addSingleton`. Its services are the scanned classes. +The desk uses scanned services. Its bootstrap configures the shared `VisitActions` with the current Person before loading FXML. ## Scope diff --git a/injection/src/main/java/de/neitzel/injection/ApplicationContext.java b/injection/src/main/java/de/neitzel/injection/ApplicationContext.java index 8b1174d..16070e7 100644 --- a/injection/src/main/java/de/neitzel/injection/ApplicationContext.java +++ b/injection/src/main/java/de/neitzel/injection/ApplicationContext.java @@ -125,7 +125,7 @@ public class ApplicationContext { private ComponentData componentData(Class type) { ComponentData data = components.get(type); if (data == null) { - throw new IllegalArgumentException("No component found for type: " + type.getName()); + throw new MissingComponentException(type); } return data; } diff --git a/injection/src/main/java/de/neitzel/injection/MissingComponentException.java b/injection/src/main/java/de/neitzel/injection/MissingComponentException.java new file mode 100644 index 0000000..26ac516 --- /dev/null +++ b/injection/src/main/java/de/neitzel/injection/MissingComponentException.java @@ -0,0 +1,15 @@ +package de.neitzel.injection; + +import lombok.Getter; + +/** A lookup requested a type with no registration in the ApplicationContext. */ +@Getter +public final class MissingComponentException extends IllegalArgumentException { + + private final Class componentType; + + public MissingComponentException(Class componentType) { + super("No component found for type: " + componentType.getName()); + this.componentType = componentType; + } +} diff --git a/pom.xml b/pom.xml index 05d3064..52aea20 100644 --- a/pom.xml +++ b/pom.xml @@ -25,6 +25,7 @@ data-grid-jdbc fx fx-test + fx-injection fx-example gson net