Run Designer previews with application-owned DI adapters

This commit is contained in:
2026-11-26 16:01:19 +01:00
parent e49d586916
commit 6126967fdc
56 changed files with 2131 additions and 50 deletions
+6 -1
View File
@@ -32,6 +32,11 @@ On macOS `IDEA_HOME` points to the IDE application's `Contents` directory. The c
Maven is pinned to **3.9.11** (Wrapper **3.3.4**); the separate IntelliJ build uses **Gradle 9.1.0** and IntelliJ Platform Gradle Plugin **2.20.1**. Wrapper distributions have pinned checksums. Shared-module-only validation is `./mvnw -B -ntp clean verify`; it does not qualify IntelliJ packaging. Plugin output is under `designer-intellij/build/distributions/`.
The [Spring DI fixture](integration-fixtures/spring-di/README.md) qualifies
application-owned dependency injection with the development FX API. It has
an independent JavaFX launcher and checks for target previews, Standalone
and the registered IntelliJ editor.
## Java source conventions
Use focused Lombok annotations for mechanical constructors/accessors/logging,
@@ -68,7 +73,7 @@ python3 scripts/check-ide-host.py --java-home "$JAVA_HOME" --target-java-home "$
### Archiver in IntelliJ
Build the Designer modules and plugin with the bootstrap command above. It verifies the [NeitzelLib release baseline](docs/runtime/neitzellib-baseline.md). Use the NeitzelLib version declared by Archiver for its application build. Archiver includes its preview examples in the `designer-preview` Maven profile. To open an isolated IntelliJ instance with a project copy and the built plugin, run from this checkout with the same Maven environment:
Build the Designer modules and plugin with the bootstrap command above. It verifies the [NeitzelLib release baseline](docs/runtime/neitzellib-baseline.md). Install the FX snapshot declared by Archiver for its application build. Its README records the compatible source revision and its legacy `ApplicationContext` provider setup. Archiver includes its preview examples in the `designer-preview` Maven profile. To open an isolated IntelliJ instance with a project copy and the built plugin, run from this checkout with the same Maven environment:
```sh
python3 scripts/run-fixture-host.py intellij --archiver ../Archiver \
+4 -1
View File
@@ -39,7 +39,10 @@
<execution>
<goals><goal>test-jar</goal></goals>
<configuration>
<includes><include>**/ProjectionHostChecks*.class</include></includes>
<includes>
<include>**/ProjectionHostChecks*.class</include>
<include>**/SpringPreviewHostChecks.class</include>
</includes>
</configuration>
</execution>
</executions>
@@ -0,0 +1,97 @@
package de.neitzel.fxdesigner.kit;
import com.oracle.javafx.scenebuilder.kit.fxom.FXOMInstance;
import com.oracle.javafx.scenebuilder.kit.fxom.FXOMFxIdIndex;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.Callable;
import java.util.stream.Stream;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.image.ImageView;
/** Runs the same UI actions in the standalone and the registered IntelliJ editor. */
public final class SpringPreviewHostChecks {
private SpringPreviewHostChecks() {}
public static void verify(DesignerPane pane, String label, boolean book, Path output) throws Exception {
try {
await(() -> pane.kit().editor().getFxomDocument() != null, "canvas");
click(pane, "Build and Refresh");
if (book) {
await(() -> {
var component = new FXOMFxIdIndex(pane.kit().editor().getFxomDocument()).lookup("featured");
return component instanceof FXOMInstance instance
&& instance.getSceneGraphObject() instanceof SnapshotRegion region
&& region.image() != null && region.statusText().equals("Target runtime");
}, "Spring Component canvas pixels");
}
click(pane, "Form preview");
await(() -> pane.lookup("#full-preview-image") instanceof ImageView view && view.getImage() != null
&& ((Label) pane.lookup("#preview-state")).getText().startsWith(label + " · "),
label + " form preview");
for (int run = 1; run <= 2; run++) {
String attempt = (book ? "book-" : "card-") + run;
System.out.println(label + " interactive preview " + run);
Files.writeString(output.resolve("spring-attempt"), attempt);
click(pane, "Interactive preview");
await(() -> {
var error = output.resolve("target-error.txt");
if (Files.exists(error)) throw new AssertionError(Files.readString(error));
if (hasLabel(pane, "Interactive preview failed; use Interactive preview to retry"))
throw new AssertionError("Interactive preview failed");
var result = output.resolve(attempt + ".txt");
return Files.exists(result) && Files.readString(result)
.equals(book ? "Preview contact book" : "Preview entry");
}, label + " interactive preview " + run);
click(pane, "Stop preview");
}
} catch (Exception | AssertionError failure) {
var details = fx(() -> Stream.concat(pane.lookupAll(".label").stream(), pane.lookupAll(".text-area").stream())
.map(node -> switch (node) {
case Label control -> control.getText();
case TextArea control -> control.getText();
default -> "";
})
.filter(text -> text != null && !text.isBlank())
.distinct().toList());
throw new AssertionError(details.toString(), failure);
}
}
private static boolean hasLabel(DesignerPane pane, String text) {
return pane.lookupAll(".label").stream().anyMatch(node ->
node instanceof Label label && text.equals(label.getText()));
}
private static void click(DesignerPane pane, String text) throws Exception {
fx(() -> {
var button = pane.lookupAll(".button").stream()
.filter(node -> node instanceof Button control && text.equals(control.getText()))
.map(Button.class::cast)
.findFirst().orElseThrow();
button.fire();
return null;
});
}
private static void await(Callable<Boolean> condition, String description) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(100);
while (System.nanoTime() < deadline) {
if (fx(condition)) return;
Thread.sleep(100);
}
throw new AssertionError("Timed out waiting for " + description);
}
public static <T> T fx(Callable<T> action) throws Exception {
var task = new FutureTask<T>(action);
Platform.runLater(task);
return task.get(15, TimeUnit.SECONDS);
}
}
@@ -2,7 +2,10 @@ package de.neitzel.fxdesigner.preview;
import java.util.concurrent.*;
/** Owned example state. The NeitzelLib adapter requires C to be an ApplicationContext. */
/**
* Owned example state. Return ViewDependencies on FX runtimes with the DI adapter API.
* An ApplicationContext is supported on runtimes that provide the legacy loaders.
*/
public interface PreviewSession<M, C> extends AutoCloseable {
M model();
@@ -0,0 +1,52 @@
package de.neitzel.fxdesigner.standalone;
import de.neitzel.fxdesigner.kit.DesignerPane;
import de.neitzel.fxdesigner.workflow.HostLaunch;
import de.neitzel.fxdesigner.kit.SpringPreviewHostChecks;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CompletableFuture;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.stage.Stage;
import static de.neitzel.fxdesigner.kit.SpringPreviewHostChecks.fx;
public final class SpringPreviewHostSmoke {
public static void main(String[] args) throws Exception {
var launch = HostLaunch.load(Path.of(args[0]));
Platform.startup(() -> Platform.setImplicitExit(false));
var book = Path.of(args[1]);
var output = Path.of(args[2]);
try (var host = new StandaloneHost(launch.runtimes(),
location -> CompletableFuture.completedFuture(null),
diagnostic -> System.out.println(diagnostic.message()))) {
verify(host, launch, book, "Spring contact book", true, output);
verify(host, launch, book.resolveSibling("EntryCard.fxml"), "Spring entry", false, output);
Files.writeString(output.resolve("SUCCESS.txt"),
"PASS Spring canvas, form and interactive previews in standalone");
} finally {
Platform.exit();
}
}
private static void verify(StandaloneHost host, HostLaunch launch, Path file, String label, boolean book, Path output)
throws Exception {
var stage = fx(Stage::new);
var pane = fx(() -> {
var editor = new DesignerPane(host.services(), launch, file);
stage.setScene(new Scene(editor, 1300, 850));
stage.show();
return editor;
});
try {
SpringPreviewHostChecks.verify(pane, label, book, output);
} finally {
fx(() -> {
pane.close();
stage.close();
return null;
});
}
}
}
+2
View File
@@ -25,6 +25,8 @@
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>${neitzellib.version}</version>
<!-- The captured target application supplies FX at runtime. -->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
@@ -0,0 +1,78 @@
package de.neitzel.fxdesigner.target;
import de.neitzel.fx.view.LoadedView;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import javafx.scene.Parent;
/** Resolves the appropriate loader signature in the captured application's FX runtime. */
record PreviewViewLoader(Class<?> contract, boolean legacy) {
private static final String CONTRACT = "de.neitzel.fx.view.ViewDependencies";
private static final String VIEW_OBJECT = "de.neitzel.fx.view.ViewObject";
private static final String LEGACY_CONTEXT = "de.neitzel.injection.ApplicationContext";
static PreviewViewLoader forContext(Object context) {
for (Class<?> type = context.getClass(); type != null; type = type.getSuperclass()) {
if (LEGACY_CONTEXT.equals(type.getName())) return new PreviewViewLoader(type, true);
}
Class<?> contract;
try {
contract = Class.forName(CONTRACT, false, ViewLoader.class.getClassLoader());
} catch (ClassNotFoundException unavailable) {
throw new PreviewFailure(
PreviewFailure.Code.CONTEXT_TYPE,
"Preview context must be an ApplicationContext or use NeitzelLib FX with the ViewDependencies API",
unavailable);
}
if (!contract.isInstance(context)) {
throw new PreviewFailure(
PreviewFailure.Code.CONTEXT_TYPE,
"Preview context must be an ApplicationContext or ViewDependencies",
null);
}
return new PreviewViewLoader(contract, false);
}
LoadedView load(
URL resource, Class<? extends Parent> component, Object model, Object context,
ViewModelContext models) throws Throwable {
try {
var method =
component == null
? ViewLoader.class.getMethod(
legacy ? "load" : "loadWithDependencies", URL.class, Object.class, contract, ViewModelContext.class)
: ViewLoader.class.getMethod(
legacy ? "loadComponent" : "loadComponentWithDependencies",
Class.class, Object.class, contract, ViewModelContext.class);
return (LoadedView) method.invoke(
null, component == null ? resource : component, model, context, models);
} catch (NoSuchMethodException unavailable) {
if (legacy) {
throw new PreviewFailure(
PreviewFailure.Code.CONTEXT_TYPE,
"This FX runtime needs the preview provider to return ViewDependencies. "
+ "Use fx-injection for ApplicationContext or use the previous FX baseline.",
unavailable);
}
throw missingCapability(unavailable);
} catch (InvocationTargetException failed) {
throw failed.getCause();
}
}
static boolean missingContract(Throwable failure) {
if (!(failure instanceof ClassNotFoundException || failure instanceof NoClassDefFoundError)
|| failure.getMessage() == null) return false;
var name = failure.getMessage().replace('/', '.');
return name.equals(CONTRACT) || name.equals(VIEW_OBJECT);
}
static PreviewFailure missingCapability(Throwable cause) {
return new PreviewFailure(
PreviewFailure.Code.CONTEXT_TYPE,
"ViewDependencies preview needs NeitzelLib FX with the DI adapter API (1.0.7 or its development snapshot)",
cause);
}
}
@@ -2,7 +2,6 @@ package de.neitzel.fxdesigner.target;
import de.neitzel.fx.view.*;
import de.neitzel.fxdesigner.preview.*;
import de.neitzel.injection.ApplicationContext;
import java.time.Duration;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -84,14 +83,6 @@ public final class TargetPreview implements AutoCloseable {
var previous = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(loader);
try {
// Named modules need this one package open for Reflections' ClassLoader resource enumeration.
for (Module module : ModuleLayer.boot().modules())
if (module.getPackages().contains(d.componentPackage())
&& !module.isOpen(d.componentPackage()))
throw failure(
PreviewFailure.Code.MODULE_ACCESS,
"Open component package " + d.componentPackage() + " for NeitzelLib scanning",
null);
Class<?> type = Class.forName(d.providerClass(), false, loader);
if (!PreviewProvider.class.isAssignableFrom(type))
throw failure(
@@ -103,21 +94,37 @@ public final class TargetPreview implements AutoCloseable {
if (provider.modelType() != modelType)
throw failure(
PreviewFailure.Code.MODEL_TYPE, "Descriptor/provider Model types differ", null);
try {
session = provider.open(d.id());
if (session == null || session.model() == null || !modelType.isInstance(session.model()))
} catch (Throwable error) {
if (closedModulePackage(d.componentPackage()) && failedNeitzelLookup(error))
throw scanAccess(d, error);
throw error;
}
Object model = session == null ? null : session.model();
if (!modelType.isInstance(model))
throw failure(
PreviewFailure.Code.MODEL_TYPE, "Provider returned an incompatible Model", null);
if (!(session.context() instanceof ApplicationContext context))
throw failure(
PreviewFailure.Code.CONTEXT_TYPE,
"NeitzelLib preview requires an ApplicationContext",
null);
Object context = session.context();
if (context == null)
throw failure(PreviewFailure.Code.CONTEXT_TYPE, "Preview session returned no context", null);
var viewLoader = PreviewViewLoader.forContext(context);
if (viewLoader.legacy() && closedModulePackage(d.componentPackage()))
throw scanAccess(d, null);
var resource = loader.getResource(d.viewResource());
if (resource == null)
if (resource == null) {
int slash = d.viewResource().lastIndexOf('/');
if (slash > 0) {
String resourcePackage = d.viewResource().substring(0, slash).replace('/', '.');
if (closedModulePackage(resourcePackage))
throw failure(
PreviewFailure.Code.RESOURCE,
"View resource unavailable: " + d.viewResource() + "; check module resource openness",
PreviewFailure.Code.MODULE_ACCESS,
"Open FXML resource package " + resourcePackage + " to load " + d.viewResource(),
null);
}
throw failure(
PreviewFailure.Code.RESOURCE, "View resource unavailable: " + d.viewResource(), null);
}
var xml = javax.xml.parsers.DocumentBuilderFactory.newInstance();
xml.setNamespaceAware(true);
xml.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
@@ -128,12 +135,13 @@ public final class TargetPreview implements AutoCloseable {
"http://javafx.com/fxml/1".equals(element.getNamespaceURI())
&& "root".equals(element.getLocalName());
}
Class<? extends Parent> componentType = null;
if (component) {
String name =
d.viewResource().substring(0, d.viewResource().length() - 5).replace('/', '.');
var componentType = Class.forName(name, false, loader).asSubclass(Parent.class);
view = ViewLoader.loadComponent(componentType, session.model(), context, models);
} else view = ViewLoader.load(resource, session.model(), context, models);
componentType = Class.forName(name, false, loader).asSubclass(Parent.class);
}
view = viewLoader.load(resource, componentType, model, context, models);
scene = new Scene(view.getRoot(), 420, 240);
interactive = new javafx.stage.Stage();
interactive.setScene(scene);
@@ -166,13 +174,38 @@ public final class TargetPreview implements AutoCloseable {
}
}
private static boolean closedModulePackage(String name) {
return ModuleLayer.boot().modules().stream()
.anyMatch(module -> module.getPackages().contains(name) && !module.isOpen(name));
}
private static boolean failedNeitzelLookup(Throwable error) {
for (Throwable cause = error; cause != null; cause = cause.getCause()) {
for (var frame : cause.getStackTrace()) {
String owner = frame.getClassName();
if (owner.equals("de.neitzel.injection.ApplicationContext")
|| owner.equals("de.neitzel.injection.ComponentScanner")) return true;
}
}
return false;
}
private static PreviewFailure scanAccess(ExampleDescriptor descriptor, Throwable cause) {
return failure(
PreviewFailure.Code.MODULE_ACCESS,
"Open component package " + descriptor.componentPackage() + " for NeitzelLib scanning",
cause);
}
private static PreviewFailure failure(PreviewFailure.Code code, String text, Throwable e) {
return new PreviewFailure(code, text, e);
}
private static PreviewFailure classify(Throwable e) {
if (e instanceof PreviewFailure f) return f;
for (Throwable t = e; t != null; t = t.getCause())
for (Throwable t = e; t != null; t = t.getCause()) {
if (PreviewViewLoader.missingContract(t))
return PreviewViewLoader.missingCapability(e);
if (t instanceof java.lang.reflect.InaccessibleObjectException
|| t instanceof IllegalAccessException
|| t instanceof IllegalAccessError)
@@ -180,6 +213,7 @@ public final class TargetPreview implements AutoCloseable {
PreviewFailure.Code.MODULE_ACCESS,
"Target module access denied; inspect declared exports/opens",
e);
}
return failure(PreviewFailure.Code.LOAD, "NeitzelLib View load failed", e);
}
+30 -3
View File
@@ -1,6 +1,30 @@
# Preview API and target adapter qualification
Implementation history: this page records its original bootstrap work package. The [first connected workflow](first-connected-workflow.md) now supplies worker transport, draft overlays and runnable minimal hosts; historical test counts below remain scoped to that earlier step.
The compatibility checks below cover the published 1.0.6 target, the earlier
DI adapter snapshot and the separated FX snapshot. The rest of the page
records the original Java 21 bootstrap qualification. The
[first connected workflow](first-connected-workflow.md) documents worker
transport, draft overlays and runnable minimal hosts.
## Current DI compatibility checks
Use JDK 25 and install the current Designer tools in the Maven repository
that supplies the target artifacts. The release-based legacy fixtures use
`ApplicationContext`.
```sh
python3 scripts/check-preview-fixtures.py --target-java-home "$JAVA_HOME"
```
To repeat the legacy checks on the earlier development snapshot, point
`MAVEN_OPTS` at its separate repository and add
`--neitzellib-version 1.0.7-SNAPSHOT`. Follow the
[Spring fixture guide](../integration-fixtures/spring-di/README.md) for the
separated snapshot and the runtime checks without Neitzel's injection
implementation or Reflections. See the
[baseline record](runtime/neitzellib-baseline.md) for artifact identity.
## Original bootstrap qualification
Work package 6 is implemented against the [verified NeitzelLib development artifact](runtime/neitzellib-baseline.md), Java 21 and application JavaFX 21.0.7. This qualifies target-side execution; it does not connect the designer UI, snapshot activation or worker transport. Those remain work package 7.
@@ -12,7 +36,10 @@ The dependency-free Java 21 preview API contains:
- `PreviewProvider<M,C>`: `modelType()` and `open(exampleId)`.
- `PreviewSession<M,C>`: `model()`, `context()`, asynchronous `ready()` and `close()`.
The NeitzelLib target adapter requires an `ApplicationContext` context. Providers have public no-argument constructors. They create fresh Models and explicitly configured services after selection, on the target FX thread. They own cleanup of partial allocations when construction throws before returning a session. The adapter owns the returned session and calls its cleanup once on load failure, readiness failure, timeout, cancellation or normal close.
The original fixtures use `ApplicationContext`. Current workers also accept
`ViewDependencies` when the captured FX runtime supplies the DI adapter API.
The [Spring fixture](../integration-fixtures/spring-di/README.md) qualifies
that path. Providers have public no-argument constructors. They create fresh Models and explicitly configured services after selection, on the target FX thread. They own cleanup of partial allocations when construction throws before returning a session. The adapter owns the returned session and calls its cleanup once on load failure, readiness failure, timeout, cancellation or normal close.
Discovery reads UTF-8 `META-INF/neitzel-fx-designer/examples.properties` resources without loading provider or Model classes. This development metadata contract has format version 1:
@@ -35,7 +62,7 @@ These are tested development signatures, not a published API release or a promis
## Lifecycle boundary established by the fixtures
NeitzelLib's `ViewModels` retains Model/ViewModel identities in a process-wide identity map with no public disposal operation. Closing a session releases provider-owned resources but cannot clear that map. Consequently `TargetPreview` allows **one session per target JVM**, including failed sessions. Every restart and interactive preview needs a fresh process.
The original Java 21 FX artifact retained Model/ViewModel identities in a process-wide identity map. That qualification established **one session per target JVM**, including failed sessions. The same process ownership rule still applies. Current managed loaders use a `ViewModelContext`. The worker closes it before the preview session's provider-owned services.
The adapter's readiness deadline and cleanup are cooperative FX-thread operations. A blocked constructor, Controller or cleanup hook cannot be interrupted by the adapter. Work package 7 must enforce an external process deadline, bounded graceful shutdown and forced termination using the host-owned lifetime channel. The fixture runner enforces a 30-second process timeout. Session close is not proof that library-held objects have been garbage-collected.
+190
View File
@@ -141,5 +141,195 @@
"repositoryPath": "de/neitzel/lib/fx-test/1.0.6/fx-test-1.0.6.jar",
"sha256": "0cae3772377ad161535ab6b8414b350df37970c09a5872db35a00f305d6fdad3"
}
],
"diAdapterSnapshot": {
"status": "qualified-development-snapshot",
"version": "1.0.7-SNAPSHOT",
"sourceBaseRevision": "efda8c2d14c0b812ba9f217a3cebbb81787278ea",
"sourceTree": "57f803dab0812e8ef44f0087f80326f44df24d62",
"requiredCapability": "ViewDependencies and managed loader methods",
"javaVersion": "25.0.5",
"javafxVersion": "27.0.1",
"springVersion": "6.2.11",
"testResults": {
"core": {
"tests": 9,
"failures": 0,
"errors": 0,
"skipped": 1
},
"injection": {
"tests": 10,
"failures": 0,
"errors": 0,
"skipped": 0
},
"data-grid": {
"tests": 33,
"failures": 0,
"errors": 0,
"skipped": 0
},
"fx": {
"tests": 415,
"failures": 0,
"errors": 0,
"skipped": 12
},
"fx-test": {
"tests": 2,
"failures": 0,
"errors": 0,
"skipped": 0
}
},
"artifacts": [
{
"repositoryPath": "de/neitzel/lib/neitzellib/1.0.7-SNAPSHOT/neitzellib-1.0.7-SNAPSHOT.pom",
"sha256": "54e80182ab74387914298165318b175adffbc6011b8c7c80f4b7034c9c5da6cc"
},
{
"repositoryPath": "de/neitzel/lib/core/1.0.7-SNAPSHOT/core-1.0.7-SNAPSHOT.pom",
"sha256": "c164de433753bf35e9e748cb169e499737e91787b962036bcd0192fd537da0a1"
},
{
"repositoryPath": "de/neitzel/lib/core/1.0.7-SNAPSHOT/core-1.0.7-SNAPSHOT.jar",
"sha256": "3ed354f7975eadcf20774ae86311c67c0486bd074b4ee7d1eb23bb809a53411d"
},
{
"repositoryPath": "de/neitzel/lib/injection/1.0.7-SNAPSHOT/injection-1.0.7-SNAPSHOT.pom",
"sha256": "65968ade4a6d4be69a4bacce363c8f2282f66e900d7ec4600c0a2a11b89b8d40"
},
{
"repositoryPath": "de/neitzel/lib/injection/1.0.7-SNAPSHOT/injection-1.0.7-SNAPSHOT.jar",
"sha256": "541976f22b80ac65faec1b9181b7446040c578c2fc564062eedee1a6219ebf7a"
},
{
"repositoryPath": "de/neitzel/lib/data-grid/1.0.7-SNAPSHOT/data-grid-1.0.7-SNAPSHOT.pom",
"sha256": "852feff1ec1652aed8c8cd13ec7138a648c08b77b8444f3bc28d08ef0d152a2c"
},
{
"repositoryPath": "de/neitzel/lib/data-grid/1.0.7-SNAPSHOT/data-grid-1.0.7-SNAPSHOT.jar",
"sha256": "69ae9be16f71b0fb0c09c565a74e88f324df649a7ba24165eac9b87148708910"
},
{
"repositoryPath": "de/neitzel/lib/fx/1.0.7-SNAPSHOT/fx-1.0.7-SNAPSHOT.pom",
"sha256": "72b1e07a0f1784e91fb015542ce424f9681267d2c8d7573f01a00209e2908c87"
},
{
"repositoryPath": "de/neitzel/lib/fx/1.0.7-SNAPSHOT/fx-1.0.7-SNAPSHOT.jar",
"sha256": "d34b25a15715c27c26b4fc3c94a28695b5cf49d78edecc9f5e28cb3633bbaed5"
},
{
"repositoryPath": "de/neitzel/lib/fx-test/1.0.7-SNAPSHOT/fx-test-1.0.7-SNAPSHOT.pom",
"sha256": "07decf3a7f28cdefca6800508b392bbd92b5d4f78bd00ca463e3deb40133048d"
},
{
"repositoryPath": "de/neitzel/lib/fx-test/1.0.7-SNAPSHOT/fx-test-1.0.7-SNAPSHOT.jar",
"sha256": "a7e42ab2b1cc6254d2c487f87a291627e774c0a2b70ba76fffbdb953019e6e5d"
}
]
},
"fxInjectionSplit": {
"status": "qualified-development-snapshot",
"version": "1.0.7-SNAPSHOT",
"sourceBaseRevision": "efda8c2d14c0b812ba9f217a3cebbb81787278ea",
"sourceTree": "323f30c1e513da1189fb61fd8589fcca81d82cbc",
"requiredCapability": "FX managed ViewDependencies without injection or Reflections",
"javaVersion": "25.0.5",
"javafxVersion": "27.0.1",
"springVersion": "6.2.11",
"testResults": {
"core": {
"tests": 9,
"failures": 0,
"errors": 0,
"skipped": 1
},
"injection": {
"tests": 10,
"failures": 0,
"errors": 0,
"skipped": 0
},
"data-grid": {
"tests": 33,
"failures": 0,
"errors": 0,
"skipped": 0
},
"fx": {
"tests": 413,
"failures": 0,
"errors": 0,
"skipped": 12
},
"fx-test": {
"tests": 2,
"failures": 0,
"errors": 0,
"skipped": 0
},
"fx-injection": {
"tests": 2,
"failures": 0,
"errors": 0,
"skipped": 0
}
},
"artifacts": [
{
"repositoryPath": "de/neitzel/lib/neitzellib/1.0.7-SNAPSHOT/neitzellib-1.0.7-SNAPSHOT.pom",
"sha256": "602d99dbc1633fe5f131dc7816babb07fe34a72c2cf31a79449c3f2e373a1849"
},
{
"repositoryPath": "de/neitzel/lib/core/1.0.7-SNAPSHOT/core-1.0.7-SNAPSHOT.pom",
"sha256": "d88f50c5d3e57f598426b91e808b86a3993da0fa56feb61dc2c50327eb0e695e"
},
{
"repositoryPath": "de/neitzel/lib/core/1.0.7-SNAPSHOT/core-1.0.7-SNAPSHOT.jar",
"sha256": "246c9b8ed7044569bcfeffcbe0d1bab9e2205c5fcf881f1938cab7fef7194f11"
},
{
"repositoryPath": "de/neitzel/lib/injection/1.0.7-SNAPSHOT/injection-1.0.7-SNAPSHOT.pom",
"sha256": "65968ade4a6d4be69a4bacce363c8f2282f66e900d7ec4600c0a2a11b89b8d40"
},
{
"repositoryPath": "de/neitzel/lib/injection/1.0.7-SNAPSHOT/injection-1.0.7-SNAPSHOT.jar",
"sha256": "a81a89bc94277d9454fa3991a964ac3411dafbecb709272f48e5c78d51720279"
},
{
"repositoryPath": "de/neitzel/lib/data-grid/1.0.7-SNAPSHOT/data-grid-1.0.7-SNAPSHOT.pom",
"sha256": "852feff1ec1652aed8c8cd13ec7138a648c08b77b8444f3bc28d08ef0d152a2c"
},
{
"repositoryPath": "de/neitzel/lib/data-grid/1.0.7-SNAPSHOT/data-grid-1.0.7-SNAPSHOT.jar",
"sha256": "9c250c149deb81812bbb310cd14fc58bb1a29b334863db798ecc2ed4eaa02956"
},
{
"repositoryPath": "de/neitzel/lib/fx/1.0.7-SNAPSHOT/fx-1.0.7-SNAPSHOT.pom",
"sha256": "b1613c38a8775283101f9bc89b1c908a28e66273337ff47e180b8735645e5cc7"
},
{
"repositoryPath": "de/neitzel/lib/fx/1.0.7-SNAPSHOT/fx-1.0.7-SNAPSHOT.jar",
"sha256": "f65dee75a7a960118ddcf747eee756ac1786bc85713cc638d9246c6f44db0782"
},
{
"repositoryPath": "de/neitzel/lib/fx-test/1.0.7-SNAPSHOT/fx-test-1.0.7-SNAPSHOT.pom",
"sha256": "07decf3a7f28cdefca6800508b392bbd92b5d4f78bd00ca463e3deb40133048d"
},
{
"repositoryPath": "de/neitzel/lib/fx-test/1.0.7-SNAPSHOT/fx-test-1.0.7-SNAPSHOT.jar",
"sha256": "fc9a5d4b2f697394d3c7e2eeb29e8f06e95b737799d03673d1c41947d19ed945"
},
{
"repositoryPath": "de/neitzel/lib/fx-injection/1.0.7-SNAPSHOT/fx-injection-1.0.7-SNAPSHOT.pom",
"sha256": "8dcee2ca40dbf0ae8789f54f592b7695f1c2569b95ccfcc668b9c39fe00a2b10"
},
{
"repositoryPath": "de/neitzel/lib/fx-injection/1.0.7-SNAPSHOT/fx-injection-1.0.7-SNAPSHOT.jar",
"sha256": "82868e661ed791dd5e349e238841a9bb4f1ed456aced99625f2de55604e2cabc"
}
]
}
}
+31 -1
View File
@@ -1,6 +1,6 @@
# NeitzelLib release baseline
NeitzelFXDesigner uses `de.neitzel.lib:fx:1.0.6` on JDK 25 and JavaFX 27.0.1 for target tooling and its fixtures. That release provides managed Views, CommandBindings, direct `ViewLoader.loadComponent` loading for `fx:root` previews, one-way HTML and suggestion-list bindings, and literal DataGrid group-label keys. The Designer hosts use JavaFX 26.
NeitzelFXDesigner uses `de.neitzel.lib:fx:1.0.6` on JDK 25 and JavaFX 27.0.1 as the target tools' compile-time baseline and for release-based fixtures, including the original previews and the contact-book tutorial. That release provides managed Views, CommandBindings, direct `ViewLoader.loadComponent` loading for `fx:root` previews, one-way HTML and suggestion-list bindings, and literal DataGrid group-label keys. The Designer hosts use JavaFX 26.
The [baseline manifest](neitzellib-baseline.json) records the source revision, tag, Surefire totals and SHA-256 checksums of the published POMs and JARs. It includes the `fx-test` module used by the contact-book example. See the [NeitzelLib 1.0.6 release](https://gitea.neitzel.de/konrad/NeitzelLib/releases/tag/v1.0.6).
@@ -16,6 +16,36 @@ Maven resolves the release from the Gitea Maven registry. The verifier reads `~/
If you are qualifying a source change, use a separate local Maven repository. A new local build can produce different JAR bytes. The manifest identifies the registry artifacts used for the Designer release.
## DI adapter development qualification
The manifest's `diAdapterSnapshot` section records the previous local FX
`1.0.7-SNAPSHOT` used for the first DI adapter qualification. It still
contains the Neitzel injection dependency and the legacy FX overloads.
It records the tested source tree separately from the published release
revision and identifies the actual POMs and JARs used for the fixture.
The Designer continues to compile target tools against FX 1.0.6. The target
worker links the optional DI contract against the captured application FX
runtime after discovering a provider's context. The release verifier checks
the published baseline at the top of the manifest.
## Separated FX development qualification
The manifest's `fxInjectionSplit` section identifies the separated
development artifacts. The previous snapshot uses the same Maven
coordinates and is preserved in a distinct local repository. The
published 1.0.6 release remains the target tool's compile-time baseline.
The target application supplies FX at runtime. The worker resolves
legacy loaders for a raw `ApplicationContext` and managed dependency
loaders for a `ViewDependencies` implementation. The separated snapshot
requires the latter. See the [provider compatibility table](../user-guide/projects.md#use-the-separated-fx-runtime-with-neitzel-di).
To recheck the previous snapshot, use its own repository in
`MAVEN_OPTS` and run `check-preview-fixtures.py` with
`--neitzellib-version 1.0.7-SNAPSHOT`. Install the current Designer tools
into that repository while preserving its FX artifacts. Run the
[Spring checks](../../integration-fixtures/spring-di/README.md) against
the separated snapshot repository.
## Original Java 21 qualification
- Unmodified library main plus the new regression fixture: seven tests, one expected loading error in `componentAttributesApplyAfterInitialization`. Maven reported success because its POM hardcodes `testFailureIgnore=true`; the XML result correctly identified the failure.
+4 -1
View File
@@ -31,7 +31,10 @@ Start with the German contact-book guide or use the [Person desk quick start](qu
The tested host baseline is macOS arm64, Java 25 and JavaFX/Kit 26. The reference application uses Java 25 and JavaFX 27.0.1. IntelliJ is qualified against build **263.7307.200**. These are tested combinations, not a claim that arbitrary JavaFX, JDK, IDE or OS versions work.
Install the Designer tooling `0.1.1-SNAPSHOT` from this checkout. Published Designer versions are available from the [Gitea Maven registry](https://gitea.neitzel.de/api/packages/konrad/maven), which Maven can use as both a dependency and plugin repository. The target applications and examples use the [NeitzelLib `1.0.6` release baseline](../runtime/neitzellib-baseline.md).
Install the Designer tooling `0.1.1-SNAPSHOT` from this checkout. Published Designer versions are available from the [Gitea Maven registry](https://gitea.neitzel.de/api/packages/konrad/maven), which Maven can use as both a dependency and plugin repository. The target tools compile against the [NeitzelLib `1.0.6` release baseline](../runtime/neitzellib-baseline.md).
The contact-book tutorial uses that release. The Person Desk source checkout
and the Spring fixture can exercise the separated development runtime.
See [provider setup and compatibility](projects.md#use-the-separated-fx-runtime-with-neitzel-di).
## Scope and conventions
+10 -3
View File
@@ -1,6 +1,6 @@
# Architecture, development and troubleshooting
The host owns editing; the target owns application execution. This separation lets a JavaFX 26 editor design applications using the qualified JavaFX 21 runtime without importing their classes or native toolkit into the host.
The host owns editing; the target owns application execution. The JavaFX 26 editor can preview an application running JavaFX 27.0.1 in its own process, with its own classes and native toolkit.
```mermaid
flowchart TD
@@ -12,7 +12,8 @@ flowchart TD
BUILD --> STORE[Immutable snapshot and leases]
CORE --> WORKER[Authenticated target JVM]
STORE --> WORKER
WORKER --> LIB[NeitzelLib ViewLoader and injection]
WORKER --> LIB[Application's NeitzelLib ViewLoader]
LIB --> DI[Application-chosen View dependencies]
LIB --> MODEL[Fresh sample Model and ViewModel graph]
LIB --> VIEW[Real FXML Components and bindings]
WORKER --> PIXELS[Images and sizing metadata]
@@ -34,7 +35,12 @@ flowchart TD
| `designer-maven-plugin` | Captures Maven's effective application runtime for immutable snapshots |
| `designer-model-processor` | Optional Java 25 compile-time Model metadata and ViewModel generation |
The application depends on NeitzelLib FX/core/injection and its own JavaFX runtime, not the host. Preview providers depend on the small API; annotation processing depends on the processor. The target tool JARs are supplied by the host. The shared UI uses a narrow patched Kit source with recorded provenance; see [third-party notices](../../THIRD-PARTY-NOTICES.md). The Kit patch retains its BSD-3-Clause notice. The original Designer code currently has no assigned license, as the notices state; a public repository alone does not establish reuse permission. Retain the applicable third-party licenses and notices when redistributing those components. See [module boundaries](../module-host-boundaries.md) for extension points.
The application supplies its FX and JavaFX artifacts. With separated FX, it
can use `fx-injection` or supply its own `ViewDependencies`. The host supplies
the target tool JARs. The worker chooses the loader from the captured FX
runtime according to the provider's context. Providers use the small preview
API, and projects that generate Model metadata use the optional processor.
See [provider setup and compatibility](projects.md#use-the-separated-fx-runtime-with-neitzel-di). The shared UI uses a narrow patched Kit source with recorded provenance; see [third-party notices](../../THIRD-PARTY-NOTICES.md). The Kit patch retains its BSD-3-Clause notice. The original Designer code currently has no assigned license, as the notices state; a public repository alone does not establish reuse permission. Retain the applicable third-party licenses and notices when redistributing those components. See [module boundaries](../module-host-boundaries.md) for extension points.
## Trust and lifecycle
@@ -61,6 +67,7 @@ The [real fx-example qualification](quick-start.md#verify-this-reference-integra
| Blank/stale Component image | Successful Build and Refresh, matching sample descriptor, Model PI, captured resource mapping and target logs |
| New preview refused after Java/POM change | Build again, or explicitly select last successful build with its outdated state |
| Child View has no sample | Add a descriptor matching that resource and a compatible fresh provider; rebuild |
| Preview reports missing DI contract or legacy loader | Match the provider's context type to the captured FX runtime, then rebuild and refresh |
| Preview fails loading a class/property | Verify the original application first, correct FXML/imports/JPMS access, inspect target logs; no broad opens are injected |
| Converter warning | Declare/test capabilities when supported; an unverified warning is distinct from a known incompatible binding |
| Metadata stale or duplicate | Clean build after processor/Model changes; ensure one owning source compilation emits it |
+2
View File
@@ -4,6 +4,8 @@
## 1. App ohne Plugin starten
Dieser Kurzstart bleibt auf FX 1.0.6 und dessen `ApplicationContext`-Vorschau abgestimmt. Für den getrennten FX-Entwicklungsstand gibt es eine [Provider-Migration](projects.md#use-the-separated-fx-runtime-with-neitzel-di).
Du brauchst einen vollständigen **JDK 25**, Maven **3.9.11 oder neuer** und NeitzelLib `fx` und `fx-test` in Version `1.0.6`. Die Beispiel-POM lädt sie aus der Gitea Maven-Registry. Die JavaFX-Version **27.0.1** bringt Maven mit. Das Projekt läuft auf dem Classpath; du musst kein `module-info.java` schreiben und kein JavaFX-SDK in IntelliJ eintragen.
Öffne `examples/contact-book` als eigenes Projekt in IntelliJ. Falls IntelliJ es nicht als Maven-Projekt erkennt, verknüpfe die `pom.xml` als Maven-Projekt. Wähle JDK 25 als Project SDK und für Maven; aktiviere **nicht** das Profil `designer-preview`. Führe im Beispielordner aus:
+2
View File
@@ -19,6 +19,8 @@ Die überprüfte Ausgangskombination für dieses Beispiel ist:
Die JDK-/JavaFX-Version der Anwendung ist unabhängig vom JavaFX-Toolkit des IntelliJ-Prozesses. Anwendungs- und Vorschau-Code läuft im Zielprozess. Die Kombination wurde mit dem aufgeführten IntelliJ SDK auf macOS geprüft. Die zugehörigen Quellstände und Artefaktgrenzen stehen in der [NeitzelLib-Baseline](../runtime/neitzellib-baseline.md).
Dieses Tutorial nutzt die FX-1.0.6-Loader mit `ApplicationContext`. Für eine eigene Anwendung auf dem getrennten Entwicklungsstand gilt die [Provider-Migration](projects.md#use-the-separated-fx-runtime-with-neitzel-di).
Die Beispiel-POM bezieht `fx` und das Testmodul `fx-test` in Version `1.0.6` aus der Gitea Maven-Registry. Falls du dafür ein separates Maven-Repository verwendest, müssen Maven, Gradle und der aus IntelliJ gestartete Maven-Build auf dasselbe Repository zugreifen. Starte IntelliJ dann aus der Shell mit dem dort gesetzten `MAVEN_OPTS`. Das Beispiel kopiert keine Bibliotheksquellen und enthält keinen Designer-Host als Laufzeitabhängigkeit.
## 2. Die Anwendung separat starten
+1 -1
View File
@@ -18,7 +18,7 @@ The canvas is a design surface, not the running application. Use interactive pre
## Interactive preview
**Interactive preview** starts a separate target JVM with its own Model/context and the current View plus known open Component drafts. It does not share the canvas Model. **Restart** creates fresh sample state; **Stop preview** closes only the owned preview. Closing its editor closes its preview while other editors remain open.
**Interactive preview** starts a separate target JVM with fresh sample data and services from the provider. It uses the captured application FX runtime and the current View plus known open Component drafts. See [supported provider context types](projects.md#use-the-separated-fx-runtime-with-neitzel-di). It does not share the canvas Model. **Restart** creates fresh sample state; **Stop preview** closes only the owned preview. Closing its editor closes its preview while other editors remain open.
Typing later FXML drafts does not destroy interactive state immediately: the preview remains open and indicates earlier drafts. Saving an affected document restarts the preview with fresh sample state. Explicit restart also captures current drafts and clears that indication. Build changes require the normal successful-snapshot selection. Invalid bindings block new previews while leaving source editing/saving available.
+81 -10
View File
@@ -45,7 +45,7 @@ A context identifies one application module, profile set, launch mode and runtim
| `preview.readinessTimeoutSeconds` | Asynchronous readiness timeout, 1–300 seconds |
| `modulePath` | Required only for module-path mode: `entryModule`, optional `addReads` and `addOpens` |
Named-module applications need their ordinary FXMLLoader/injection reflective access as well as explicit preview access. Use the real module names from your dependencies. The Designer does not automatically add broad `--add-opens` workarounds. Consult the [qualified classpath/module-path fixtures](../preview-target-fixtures.md) and existing `designer-target-tools/src/test` examples before adapting a JPMS application.
Named-module applications need reflective access for FXMLLoader, FX and their chosen DI framework as well as explicit preview access. Use the real module names from your dependencies. The Designer does not automatically add broad `--add-opens` workarounds. Consult the [qualified classpath/module-path fixtures](../preview-target-fixtures.md) and existing `designer-target-tools/src/test` examples before adapting a JPMS application.
## Local runtime settings
@@ -67,20 +67,32 @@ The [local settings schema](../../designer-contracts/src/main/resources/schema/l
## Typed sample providers
Add `de.neitzel.fxdesigner:designer-preview-api:0.1.1-SNAPSHOT` with test scope, preferably in an opt-in profile. A provider implements `PreviewProvider<Model, ApplicationContext>`; its public no-argument constructor and `open(exampleId)` execute only in the target JVM, after selection. `modelType()` declares the Model contract.
Add `de.neitzel.fxdesigner:designer-preview-api` with test scope, preferably
in an opt-in profile. Use `0.1.1-SNAPSHOT` with locally built Designer tools.
The version of the preview API is separate from the FX version. The public
no-argument constructor and `open(exampleId)` run in the target JVM after
selection. `modelType()` declares the Model contract.
The following is an illustrative fragment: `Person`, `MyApplication` and `createSamplePerson()` belong to your application. Import `PreviewProvider` and `PreviewSession` from `de.neitzel.fxdesigner.preview` and `ApplicationContext` from `de.neitzel.injection`. The complete compiling providers are in NeitzelLib’s `fx-example/src/designer/java/de/neitzel/fx/example/preview`.
On separated FX, return `ViewDependencies` from the preview session.
This is the outline of a Person Desk provider. It shares the application's
adapter setup and uses a fresh sample Model. A new project supplies its own
equivalents of `Person` and `DeskApp`.
```java
public final class PersonPreview implements PreviewProvider<Person, ApplicationContext> {
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
public final class PersonPreview implements PreviewProvider<Person, ViewDependencies> {
public Class<Person> modelType() { return Person.class; }
public PreviewSession<Person, ApplicationContext> open(String id) {
if (!id.equals("person")) throw new IllegalArgumentException(id);
Person model = createSamplePerson();
ApplicationContext context = new ApplicationContext(MyApplication.class);
public PreviewSession<Person, ViewDependencies> open(String id) {
if (!"person".equals(id)) throw new IllegalArgumentException(id);
Person model = DeskApp.sample();
ViewDependencies dependencies = DeskApp.dependencies(model);
return new PreviewSession<>() {
public Person model() { return model; }
public ApplicationContext context() { return context; }
public ViewDependencies context() { return dependencies; }
public void close() { /* release resources owned by this sample */ }
};
}
@@ -89,7 +101,11 @@ public final class PersonPreview implements PreviewProvider<Person, ApplicationC
Use fresh Models and services on every call. Do not reuse production singletons, real accounts or external data unintentionally. `open` must clean partial allocations if it throws. `ready()` is called after View load/CSS/layout on the FX thread; return a completion stage for asynchronous work and never block that thread. `close()` runs once on FX after normal close or load/readiness failure. Forced process death cannot guarantee cooperative cleanup.
The actual example uses `DeskPreviewProvider`, `AddressPreviewProvider` and `NotePreviewProvider`. Independent Row previews prepare their parent Controller state explicitly; a Row cannot assume that a separately edited parent View has already run. Sample setup avoids the application's message popup.
The Person Desk's `DeskPreviewProvider`, `AddressPreviewProvider` and
`NotePreviewProvider` are under
`fx-example/src/designer/java/de/neitzel/fx/example/preview`. The standalone
Row preview configures a sample Person and the shared `VisitActions` service
before loading the row. The sample setup skips the application's message popup.
Register non-executing descriptors in `META-INF/neitzel-fx-designer/examples.properties`:
@@ -106,6 +122,61 @@ example.0.componentPackage=com.example
Descriptors are discovered without constructing providers. Per-document selection matches the FXML resource, including independent Components. Inspect the reference example's real five-entry descriptor when adding another View; a new generated FXML file needs its own descriptor before it has an interactive sample.
## Use the separated FX runtime with Neitzel DI
| Captured application FX | Type returned by `PreviewSession.context()` |
| --- | --- |
| Published 1.0.6, including the contact-book tutorial | `ApplicationContext` |
| Earlier DI adapter qualification snapshot | `ApplicationContext` or `ViewDependencies` |
| Separated 1.0.7-SNAPSHOT | `ViewDependencies` |
The worker selects the loader in the captured application runtime. The
[two snapshot variants](../runtime/neitzellib-baseline.md#separated-fx-development-qualification)
use the same Maven coordinates. If a provider still returns a raw
`ApplicationContext` after upgrading to separated FX, change the provider's
context type and return the configured adapter. Install
`de.neitzel.lib:fx-injection` and register the application's concrete FXML
Components, including those used by Repeat and Table. For example:
```java
var services = new ApplicationContext(MyApplication.class);
var dependencies = new NeitzelViewDependencies(services,
Set.of(AddressForm.class, VisitRow.class));
```
Use `PreviewProvider<Model, ViewDependencies>` and
`PreviewSession<Model, ViewDependencies>` with that adapter. Ordinary
application loads pass the adapter to `ViewLoader.loadWithDependencies`
with a window- or document-owned `ViewModelContext`. When two Views
need the same data or action, share an application service through DI.
Each View receives its own Controller.
## Run a Preview with Spring
The target worker also accepts `PreviewSession<Model, ViewDependencies>`
when the captured application uses NeitzelLib FX with the DI adapter API.
The [Spring fixture](../../integration-fixtures/spring-di/README.md) uses
the separated NeitzelLib `1.0.7-SNAPSHOT` development runtime from an isolated Maven repository. Both application and preview run without Neitzel's injection JAR and Reflections.
Register concrete Controller and Component classes as Spring prototype beans.
The fixture looks up shared services by class, checks Component membership
in an explicit set, and returns a `ViewObject` that calls Spring's
`destroyBean(name, instance)` when the View releases that object. The
[Spring adapter](../../integration-fixtures/spring-di/app/src/main/java/fixture/spring/app/SpringViews.java)
is used both by the application and by the sample providers.
A Preview provider opens its own Spring context with sample data. Its
`context()` method returns the FX adapter. Its `close()` method closes the
Spring context after the worker closes the Views. Keep the existing
`META-INF/neitzel-fx-designer/examples.properties` format. For a named module, expose the provider
to the worker and configure FXML resource and reflective access for JavaFX,
FX and Spring. The descriptor's `componentPackage` key remains required. The worker uses
it for its legacy `ApplicationContext` package-scan access check. A new
adapter supplies Component types independently of that key. An application
using `fx-injection` still needs module access for its own Neitzel package
scan. Spring needs the module access declared by its own application and
provider modules.
## Declare the View's Model
Use a processing instruction, ignored by normal FXMLLoader:
+5 -1
View File
@@ -14,7 +14,11 @@ mvn -pl fx-example javafx:run
Surefire fails the build on test failures. The XML reports record which tests ran.
The first command builds/installs the required reactor modules. The second launches only the application module; do not add `-am` to `javafx:run`, because the parent and library modules have no application entry point. The `Main` launcher calls `Application.launch(DeskApp.class, args)`. `DeskApp` creates the sample Person and injection context, then loads `view/Desk.fxml` through NeitzelLib's `ViewLoader`.
The first command builds/installs the required reactor modules. The second launches only the application module; do not add `-am` to `javafx:run`, because the parent and library modules have no application entry point. The `Main` launcher calls `Application.launch(DeskApp.class, args)`. On the separated development checkout, `DeskApp` creates the sample Person
and a `NeitzelViewDependencies` adapter through `DeskApp.dependencies(person)`.
It passes both to the managed loader with its own `ViewModelContext`. For the
preview, build the reference example from the same checkout and use the current
Designer tools. See [runtime compatibility](projects.md#use-the-separated-fx-runtime-with-neitzel-di).
Edit the name and home address, add a visit or tag, and select a visit. The same visit list feeds both the Table and repeated forms. Close the application before continuing. The library's [`fx-example` README](https://gitea.neitzel.de/konrad/NeitzelLib/src/branch/main/fx-example/README.md) explains the individual controls and binding behavior.
+2
View File
@@ -39,6 +39,8 @@ Die normale App benötigt weder NeitzelFXDesigner noch dessen Vorschau-Artefakte
## Optionale Designer-Vorschau
Die Provider dieses Beispiels liefern einen `ApplicationContext` für FX 1.0.6. Beim Wechsel auf den getrennten FX-Entwicklungsstand gilt die [Provider-Migration](../../docs/user-guide/projects.md#use-the-separated-fx-runtime-with-neitzel-di).
Die Vorschau hängt am Maven-Profil `designer-preview` und der eingecheckten `neitzel-fx-designer.json`. Zuerst müssen die Designer-Worker und die passende lokale Preview-API im NeitzelFXDesigner-Checkout installiert sein. Folge danach dem [Tutorialabschnitt für Plugin und lokale Projektkonfiguration](../../docs/user-guide/kontakt-tutorial.md#4-das-projekt-mit-dem-designer-verbinden). Für den Profil-Build:
```sh
+79
View File
@@ -0,0 +1,79 @@
# Spring contact book
This Maven fixture runs as a JavaFX application and as a NeitzelFXDesigner
preview. It uses Spring Framework 6.2.11, the separated NeitzelLib `1.0.7-SNAPSHOT`,
JavaFX 27.0.1 in the target and JDK 25. Views use the same FXML and adapter
in both environments. Spring owns the application services. Each Controller
and Component is a prototype.
## Run it
Set `JAVA_HOME` to JDK 25 and use a separate local Maven repository to stage
the development artifacts. From the Designer checkout:
```sh
export DI_MAVEN_REPOSITORY="/absolute/path/to/di-repository"
export MAVEN_OPTS="-Dmaven.repo.local=$DI_MAVEN_REPOSITORY"
(cd ../NeitzelLib && ./mvnw -pl fx-test -am clean install)
./mvnw -B -ntp install
./mvnw -f integration-fixtures/spring-di/app/pom.xml javafx:run
```
Edit the book name to see the Spring-supplied Converter update the caption.
Closing the window first destroys its prototypes, then stops the shared
service. The [application bootstrap](app/src/main/java/fixture/spring/app/SpringBook.java)
uses the managed `ViewLoader`. The [Spring registration](app/src/main/java/fixture/spring/app/SpringBookContext.java)
assigns separate scopes to the view types and services.
## Open the previews
From the Designer checkout, set up the ignored local paths once:
```sh
python3 scripts/configure-library-example.py \
--project integration-fixtures/spring-di --target-java-home "$JAVA_HOME"
```
Use the same local Maven repository when starting the Designer or IntelliJ.
Open `app/src/main/resources/fixture/spring/ui/Book.fxml`, select
**Build and Refresh** and then **Form preview** or **Interactive preview**.
The preview starts with `Preview contact book`; changes to it belong to
that preview. **Stop preview** closes the session. Open `EntryCard.fxml`
and start its separate example to see that Component as a standalone root.
The [Book provider](preview/src/main/java/fixture/spring/preview/BookExamples.java)
creates a fresh Model and Spring context. The [Component provider](preview/src/main/java/fixture/spring/preview/CardExamples.java)
returns its own Model and context. Both provide the application
[adapter](app/src/main/java/fixture/spring/app/SpringViews.java).
FXML resources and fields in `fixture.spring.ui` are accessible in the
[application module](app/src/main/java/module-info.java). The
[preview module](preview/src/main/java/module-info.java) exposes its providers.
The package named by `componentPackage` stays closed to demonstrate that
the Spring worker uses FXML resource access and the registered Spring beans.
## Run the checks
From the Designer checkout, using the same JDK and local Maven repository:
```sh
python3 scripts/check-preview-fixtures.py --spring-di --target-java-home "$JAVA_HOME"
./designer-intellij/gradlew -p designer-intellij -PideaHome="$IDEA_HOME" \
-Dmaven.repo.local="$DI_MAVEN_REPOSITORY" buildPlugin
./mvnw -pl designer-standalone \
org.apache.maven.plugins:maven-dependency-plugin:3.6.1:build-classpath \
-DincludeScope=test -Dmdep.outputFile=target/smoke-classpath.txt
python3 scripts/check-spring-hosts.py --java-home "$JAVA_HOME" \
--target-java-home "$JAVA_HOME" --idea-home "$IDEA_HOME"
```
The worker checks include two simultaneous Views, separate scopes, nested
Components, Repeat and Table release, cleanup after load/readiness failure
and cancellation, module resource diagnostics, and the required runtime
diagnostic against FX 1.0.6. The host checks use disposably copied project
files and exercise the canvas, form preview and interactive preview.
Each Spring context verifies that the running application or preview
cannot load Neitzel's `ApplicationContext` or Reflections and that
their JARs are absent from its classpath and module path. The test
runner separately verifies the normal Maven dependency trees. Its
missing-API check resolves FX 1.0.6 from a separate POM.
@@ -0,0 +1,45 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.neitzel.fxdesigner.fixtures</groupId>
<artifactId>spring-di</artifactId>
<version>1</version>
</parent>
<artifactId>spring-di-app</artifactId>
<dependencies>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>${neitzellib.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>${jakarta-annotation.version}</version>
</dependency>
<dependency>
<groupId>jakarta.inject</groupId>
<artifactId>jakarta.inject-api</artifactId>
<version>${jakarta-inject.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>${javafx-maven-plugin.version}</version>
<configuration>
<mainClass>fixture.spring.app/fixture.spring.app.SpringBook</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,40 @@
package fixture.spring.app;
import jakarta.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;
/** An in-memory service shared by all View objects in one Spring context. */
public final class FixtureService {
private final String label;
private final List<Object> live = new ArrayList<>();
private int released;
private int atShutdown = -1;
private int shutdowns;
public FixtureService(String label) { this.label = label; }
public String label() { return label; }
public void created(Object object) { live.add(object); }
public void release(Object object) {
if (!live.remove(object)) throw new IllegalStateException("Unknown View object: " + object);
released++;
}
public int liveCount() { return live.size(); }
public int releasedCount() { return released; }
public int liveAtShutdown() { return atShutdown; }
public int shutdownCount() { return shutdowns; }
@PreDestroy
public void shutdown() {
atShutdown = live.size();
shutdowns++;
System.out.println("SPRING CLOSED " + label + " live=" + atShutdown + " released=" + released);
}
}
@@ -0,0 +1,35 @@
package fixture.spring.app;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import fixture.spring.model.Book;
import fixture.spring.ui.BookController;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public final class SpringBook extends Application {
private SpringBookContext context;
private final ViewModelContext models = new ViewModelContext();
public static void main(String[] args) { launch(args); }
@Override
public void start(Stage stage) {
context = SpringBookContext.open("Application service");
var view = ViewLoader.loadWithDependencies(BookController.class.getResource("Book.fxml"),
Book.sample("Spring contact book"), context.dependencies(), models);
stage.setTitle("Spring contact book");
stage.setScene(new Scene(view.getRoot(), 660, 500));
stage.show();
}
@Override
public void stop() {
try {
models.close();
} finally {
if (context != null) context.close();
}
}
}
@@ -0,0 +1,46 @@
package fixture.spring.app;
import de.neitzel.fx.view.Converter;
import fixture.spring.ui.BookController;
import fixture.spring.ui.EntryCard;
import fixture.spring.ui.EntryPanel;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public record SpringBookContext(AnnotationConfigApplicationContext spring, SpringViews dependencies)
implements AutoCloseable {
private static final Map<Class<?>, String> VIEW_BEANS = Map.of(
BookController.class, "bookController", EntryCard.class, "entryCard", EntryPanel.class, "entryPanel");
public static SpringBookContext open(String serviceLabel) {
SpringRuntime.requireNoNeitzelDi(serviceLabel);
var spring = new AnnotationConfigApplicationContext();
try {
spring.registerBean(FixtureService.class, () -> new FixtureService(serviceLabel));
spring.registerBean(NameConverter.class);
VIEW_BEANS.forEach((type, name) -> spring.registerBean(name, type,
bean -> bean.setScope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)));
spring.refresh();
return new SpringBookContext(spring,
new SpringViews(spring.getBeanFactory(), VIEW_BEANS, Set.of(EntryCard.class, EntryPanel.class)));
} catch (RuntimeException | Error failure) {
spring.close();
throw failure;
}
}
public FixtureService service() { return spring.getBean(FixtureService.class); }
@Override
public void close() { spring.close(); }
public static final class NameConverter implements Converter {
@Override
public Object toControlValue(Object value) { return "[" + value + "]"; }
@Override
public Object toAttributeValue(Object value) { return value; }
}
}
@@ -0,0 +1,35 @@
package fixture.spring.app;
import java.io.File;
import java.nio.file.Path;
import java.util.List;
import java.util.regex.Pattern;
/** Verifies the artifact isolation in both the fixture application and its preview process. */
final class SpringRuntime {
private static final Pattern NEITZEL_DI = Pattern.compile("(?:fx-injection|injection|reflections)-.*\\.jar");
private SpringRuntime() {}
static void requireNoNeitzelDi(String label) {
var loader = Thread.currentThread().getContextClassLoader();
for (String type : List.of("de.neitzel.injection.ApplicationContext", "org.reflections.Reflections")) {
try {
Class.forName(type, false, loader);
throw new IllegalStateException("Unexpected runtime type " + type);
} catch (ClassNotFoundException expected) {
// The fixture must be usable without either implementation.
}
}
for (String property : List.of("java.class.path", "jdk.module.path")) {
String path = System.getProperty(property, "");
if (path.isEmpty()) continue;
for (String entry : path.split(Pattern.quote(File.pathSeparator))) {
if (NEITZEL_DI.matcher(Path.of(entry).getFileName().toString()).matches())
throw new IllegalStateException("Unexpected DI artifact on " + property + ": " + entry);
}
}
var mode = SpringRuntime.class.getModule().isNamed() ? "module-path" : "classpath";
System.out.println("SPRING FX ISOLATION " + mode + " " + label);
}
}
@@ -0,0 +1,36 @@
package fixture.spring.app;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewObject;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
public record SpringViews(ConfigurableBeanFactory beans, Map<Class<?>, String> viewBeans,
Set<Class<?>> components) implements ViewDependencies {
public SpringViews {
viewBeans = Map.copyOf(viewBeans);
components = Set.copyOf(components);
}
@Override
public boolean isComponent(Class<?> type) {
return components.contains(type);
}
@Override
public <T> Optional<T> findService(Class<T> type) {
return Optional.ofNullable(beans.getBeanProvider(type).getIfAvailable());
}
@Override
public <T> ViewObject<T> createViewObject(Class<T> type) {
String name = viewBeans.get(type);
if (name == null || !beans.isPrototype(name)) {
throw new IllegalArgumentException("Expected a prototype bean for " + type.getName());
}
T instance = beans.getBean(name, type);
return new ViewObject<>(instance, () -> beans.destroyBean(name, instance));
}
}
@@ -0,0 +1,33 @@
package fixture.spring.model;
import java.util.ArrayList;
import java.util.List;
public final class Book {
private String name;
private Entry featured;
private List<Entry> entries = new ArrayList<>();
public static Book sample(String name) {
var book = new Book();
book.setName(name);
var featured = new Entry("Featured");
featured.setDetail(new Entry("Nested entry"));
book.setFeatured(featured);
book.getEntries().add(new Entry("First entry"));
book.getEntries().add(new Entry("Second entry"));
return book;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Entry getFeatured() { return featured; }
public void setFeatured(Entry featured) { this.featured = featured; }
public List<Entry> getEntries() { return entries; }
public void setEntries(List<Entry> entries) { this.entries = entries; }
}
@@ -0,0 +1,18 @@
package fixture.spring.model;
public final class Entry {
private String name;
private Entry detail;
public Entry(String name) {
this.name = name;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Entry getDetail() { return detail; }
public void setDetail(Entry detail) { this.detail = detail; }
}
@@ -0,0 +1,31 @@
package fixture.spring.ui;
import fixture.spring.app.FixtureService;
import jakarta.annotation.PreDestroy;
import jakarta.inject.Inject;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
public final class BookController {
private final FixtureService service;
@FXML
private TextField bookName;
@Inject
public BookController(FixtureService service) {
this.service = service;
service.created(this);
}
@FXML
private void initialize() {
bookName.setPromptText(service.label());
bookName.setUserData(this);
}
public FixtureService service() { return service; }
@PreDestroy
public void dispose() { service.release(this); }
}
@@ -0,0 +1,29 @@
package fixture.spring.ui;
import fixture.spring.app.FixtureService;
import fixture.spring.model.Entry;
import jakarta.annotation.PreDestroy;
import jakarta.inject.Inject;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.layout.VBox;
public final class EntryCard extends VBox {
private final FixtureService service;
private final ObjectProperty<Entry> model = new SimpleObjectProperty<>(this, "model");
@Inject
public EntryCard(FixtureService service) {
this.service = service;
service.created(this);
}
public ObjectProperty<Entry> modelProperty() { return model; }
public Entry getModel() { return model.get(); }
public void setModel(Entry entry) { model.set(entry); }
@PreDestroy
public void dispose() { service.release(this); }
}
@@ -0,0 +1,29 @@
package fixture.spring.ui;
import fixture.spring.app.FixtureService;
import fixture.spring.model.Entry;
import jakarta.annotation.PreDestroy;
import jakarta.inject.Inject;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.layout.VBox;
public final class EntryPanel extends VBox {
private final FixtureService service;
private final ObjectProperty<Entry> model = new SimpleObjectProperty<>(this, "model");
@Inject
public EntryPanel(FixtureService service) {
this.service = service;
service.created(this);
}
public ObjectProperty<Entry> modelProperty() { return model; }
public Entry getModel() { return model.get(); }
public void setModel(Entry entry) { model.set(entry); }
@PreDestroy
public void dispose() { service.release(this); }
}
@@ -0,0 +1,16 @@
module fixture.spring.app {
requires fx;
requires jakarta.annotation;
requires jakarta.inject;
requires javafx.controls;
requires javafx.fxml;
requires spring.beans;
requires spring.context;
exports fixture.spring.app;
exports fixture.spring.model;
exports fixture.spring.ui;
opens fixture.spring.model to fx;
opens fixture.spring.ui;
}
@@ -0,0 +1,2 @@
<?import javafx.scene.layout.VBox?>
<VBox/>
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<?neitzel-model fixture.spring.model.Book?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.Column?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import de.neitzel.fx.view.Repeat?>
<?import de.neitzel.fx.view.Table?>
<?import fixture.spring.ui.EntryPanel?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="fixture.spring.ui.BookController" spacing="8">
<fx:define>
<BindingList>
<DirectBinding control="bookName" property="text" path="name" direction="both"/>
<DirectBinding control="convertedName" property="text" path="name" direction="view"
converter="fixture.spring.app.SpringBookContext$NameConverter"/>
<DirectBinding control="featured" property="model" path="featured" direction="both"/>
<Repeat pane="entries" component="fixture.spring.ui.EntryCard" collection="entries"/>
</BindingList>
</fx:define>
<TextField fx:id="bookName"/>
<Label fx:id="convertedName"/>
<EntryPanel fx:id="featured"/>
<VBox fx:id="entries"/>
<Table fx:id="entriesTable" collection="entries" row="fixture.spring.ui.EntryCard" prefHeight="120">
<Column header="Entry" attribute="name"/>
</Table>
</VBox>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<?neitzel-model fixture.spring.model.Entry?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<fx:root type="javafx.scene.layout.VBox" xmlns:fx="http://javafx.com/fxml/1">
<fx:define>
<BindingList>
<DirectBinding control="entryName" property="text" path="name" direction="both"/>
</BindingList>
</fx:define>
<TextField fx:id="entryName"/>
</fx:root>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<?neitzel-model fixture.spring.model.Entry?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import fixture.spring.ui.EntryCard?>
<?import javafx.scene.layout.VBox?>
<fx:root type="javafx.scene.layout.VBox" xmlns:fx="http://javafx.com/fxml/1">
<fx:define>
<BindingList>
<DirectBinding control="nested" property="model" path="detail" direction="both"/>
</BindingList>
</fx:define>
<EntryCard fx:id="nested"/>
</fx:root>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import fixture.spring.ui.EntryCard?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="fixture.spring.ui.BookController">
<TextField fx:id="bookName"/>
<EntryCard unknownProperty="fails after acquisition"/>
</VBox>
@@ -0,0 +1,54 @@
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewObject;
import de.neitzel.fxdesigner.preview.ExampleDescriptor;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
import java.util.Optional;
import de.neitzel.fxdesigner.target.PreviewFailure;
import de.neitzel.fxdesigner.target.TargetPreview;
import java.time.Duration;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
/** Runs against FX 1.0.6 without linking the newer adapter types in the launcher. */
public final class CapabilityCheck {
public static void main(String[] args) throws Exception {
Platform.startup(() -> Platform.setImplicitExit(false));
try {
var descriptor = new ExampleDescriptor("book", "Missing adapter", "java.lang.String",
"CapabilityCheck$Provider", "Book.fxml", "fixture");
try (var target = TargetPreview.open(descriptor, CapabilityCheck.class.getClassLoader(), Duration.ofSeconds(20))) {
try {
target.ready().toCompletableFuture().get(20, TimeUnit.SECONDS);
throw new AssertionError("Expected missing FX adapter API");
} catch (ExecutionException failure) {
var diagnostic = (PreviewFailure) failure.getCause();
if (diagnostic.code() != PreviewFailure.Code.CONTEXT_TYPE
|| !diagnostic.getMessage().contains("1.0.7")) throw new AssertionError(diagnostic);
}
target.cleanup().toCompletableFuture().get(5, TimeUnit.SECONDS);
System.out.println("PASS missing-capability 1");
}
} finally {
Platform.exit();
}
}
// Linking this Provider itself needs the new interface, before opening any preview session.
public static final class Provider implements PreviewProvider<String, ViewDependencies>, ViewDependencies {
public Class<String> modelType() { return String.class; }
public PreviewSession<String, ViewDependencies> open(String id) {
throw new AssertionError("Provider unexpectedly loaded with the old FX runtime");
}
public boolean isComponent(Class<?> type) { return false; }
public <T> Optional<T> findService(Class<T> type) { return Optional.empty(); }
public <T> ViewObject<T> createViewObject(Class<T> type) {
throw new UnsupportedOperationException();
}
}
}
@@ -0,0 +1,246 @@
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import de.neitzel.fx.view.ViewObject;
import de.neitzel.fxdesigner.preview.ExampleDescriptor;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
import de.neitzel.fxdesigner.target.ExampleCatalog;
import de.neitzel.fxdesigner.target.PreviewFailure;
import de.neitzel.fxdesigner.target.TargetPreview;
import fixture.spring.app.FixtureService;
import fixture.spring.app.SpringBook;
import fixture.spring.app.SpringBookContext;
import fixture.spring.model.Book;
import fixture.spring.preview.BookExamples;
import fixture.spring.ui.BookController;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public final class SpringChecks {
private static final String UI = "fixture/spring/ui/";
private static int assertions;
public static void main(String[] args) throws Exception {
Platform.startup(() -> Platform.setImplicitExit(false));
try {
if (args[0].equals("application")) {
fx(() -> { application(); return null; });
} else {
preview(args[0]);
}
System.out.println("PASS " + args[0] + " " + assertions);
} finally {
Platform.exit();
}
}
private static void application() throws Exception {
var app = new SpringBook();
var stage = new Stage();
try {
app.start(stage);
check(stage.isShowing() && name(stage.getScene().getRoot()).getText().equals("Spring contact book"),
"normal application launch");
} finally {
stage.close();
app.stop();
}
FixtureService service;
try (var spring = SpringBookContext.open("Application check"); var models = new ViewModelContext()) {
service = spring.service();
var fxml = BookController.class.getResource("Book.fxml");
var model = Book.sample("Local contact book");
var first = ViewLoader.loadWithDependencies(fxml, model, spring.dependencies(), models);
var second = ViewLoader.loadWithDependencies(fxml, model, spring.dependencies(), models);
var firstRoot = first.getRoot();
var secondRoot = second.getRoot();
checkBook(firstRoot, "Local contact book", "Application check");
var firstController = (BookController) name(firstRoot).getUserData();
var otherController = (BookController) name(secondRoot).getUserData();
check(firstController != otherController && firstController.service() == otherController.service(),
"prototype controllers share one injected service");
check(firstRoot.lookup("#featured") != secondRoot.lookup("#featured"), "distinct embedded Components");
check(service.liveCount() == 14, "seven UI instances per view");
model.getEntries().removeFirst();
check(service.releasedCount() == 4 && service.liveCount() == 10, "Repeat and Table entries released");
first.close();
first.close();
check(service.releasedCount() == 9 && otherController.service() == spring.service(),
"one close preserves the other View and the service");
try {
ViewLoader.loadWithDependencies(BookController.class.getResource("Invalid.fxml"),
model, spring.dependencies(), models);
throw new AssertionError("Invalid child loaded");
} catch (IllegalStateException expected) {
check(service.releasedCount() == 11 && service.liveCount() == 5, "child and controller rollback");
}
}
checkClosed(service);
}
private static void preview(String mode) throws Exception {
var loader = SpringChecks.class.getClassLoader();
var descriptors = ExampleCatalog.discover(loader);
check(descriptors.size() == 2, "exact fixture descriptors");
var listed = descriptors.stream().filter(d -> d.id().equals(mode.equals("card") ? "card" : "book"))
.findFirst().orElseThrow();
check(BookExamples.lastService() == null, "discovery did not open provider");
var selected = switch (mode) {
case "invalid" -> with(listed, mode, listed.providerClass(), UI + "Invalid.fxml");
case "release-failure" -> with(listed, mode, FailingReleaseExample.class.getName(), listed.viewResource());
case "wrong-context" -> with(listed, mode, WrongExample.class.getName(), listed.viewResource());
case "missing-resource" -> with(listed, mode, listed.providerClass(), "missing/Book.fxml");
case "closed-resource" -> with(listed, mode, listed.providerClass(), "fixture/spring/app/Closed.fxml");
default -> with(listed, mode, listed.providerClass(), listed.viewResource());
};
try (var target = TargetPreview.open(selected, loader, Duration.ofSeconds(20))) {
if (mode.equals("cancel")) {
check(fx(() -> BookExamples.lastService().liveCount()) == 7, "waited for live View");
target.cancel();
}
switch (mode) {
case "release-failure" -> {
target.ready().toCompletableFuture().get(20, TimeUnit.SECONDS);
target.close();
try {
target.cleanup().toCompletableFuture().get(5, TimeUnit.SECONDS);
throw new AssertionError("Expected View cleanup failure");
} catch (ExecutionException failure) {
check(((PreviewFailure) failure.getCause()).code() == PreviewFailure.Code.CLEANUP,
"failed release reported");
}
}
case "book", "card" -> {
target.ready().toCompletableFuture().get(20, TimeUnit.SECONDS);
fx(() -> {
Parent root = target.loadedView().getRoot();
if (mode.equals("book")) {
checkBook(root, "Preview contact book", "Preview service");
name(root).setText("Edited in preview");
check(((Label) root.lookup("#convertedName")).getText().equals("[Edited in preview]"),
"live binding in preview");
} else {
check(((TextField) root.lookup("#entryName")).getText().equals("Preview entry"),
"standalone fx:root Component loaded");
}
check(target.render(420, 240).length == 420 * 240 * 4, "target rendered");
return null;
});
}
default -> expectFailure(target, mode);
}
}
// The call to close() from the test thread posts to FX. The next FX action follows it.
if (java.util.Set.of("book", "invalid", "readiness", "cancel", "missing-resource", "closed-resource",
"release-failure").contains(mode))
fx(() -> { checkClosed(BookExamples.lastService()); return null; });
}
private static ExampleDescriptor with(ExampleDescriptor d, String mode, String provider, String resource) {
return new ExampleDescriptor(mode, d.label(), d.modelType(), provider, resource, d.componentPackage());
}
private static void expectFailure(TargetPreview target, String mode) throws Exception {
var expected = switch (mode) {
case "cancel" -> PreviewFailure.Code.CANCELLED;
case "readiness" -> PreviewFailure.Code.READINESS;
case "invalid" -> PreviewFailure.Code.LOAD;
case "closed-resource" -> PreviewFailure.Code.MODULE_ACCESS;
case "missing-resource" -> PreviewFailure.Code.RESOURCE;
default -> PreviewFailure.Code.CONTEXT_TYPE;
};
try {
target.ready().toCompletableFuture().get(20, TimeUnit.SECONDS);
throw new AssertionError("Expected " + expected);
} catch (ExecutionException failure) {
var diagnostic = (PreviewFailure) failure.getCause();
check(diagnostic.code() == expected, "expected " + expected + ", got " + diagnostic);
}
target.cleanup().toCompletableFuture().get(5, TimeUnit.SECONDS);
}
private static void checkBook(Parent root, String text, String service) {
check(name(root).getText().equals(text) && name(root).getPromptText().equals(service), "FXML and injected service");
check(((Label) root.lookup("#convertedName")).getText().equals("[" + text + "]"), "Spring Converter");
var panel = (Parent) root.lookup("#featured");
check(((TextField) panel.lookup("#entryName")).getText().equals("Nested entry"), "nested Component");
check(((VBox) root.lookup("#entries")).getChildren().size() == 2, "Repeat children");
check(root.lookup("#entriesTable") != null, "Table loaded");
}
private static TextField name(Parent root) { return (TextField) root.lookup("#bookName"); }
private static void checkClosed(FixtureService service) {
check(service.liveAtShutdown() == 0 && service.shutdownCount() == 1,
"context closed once, after all View objects were destroyed");
}
private static <T> T fx(Callable<T> action) throws Exception {
var task = new FutureTask<T>(action);
Platform.runLater(task);
return task.get(20, TimeUnit.SECONDS);
}
private static void check(boolean ok, String message) {
if (!ok) throw new AssertionError(message);
assertions++;
}
public static final class FailingReleaseExample implements PreviewProvider<Book, ViewDependencies> {
@Override
public Class<Book> modelType() { return Book.class; }
@Override
public PreviewSession<Book, ViewDependencies> open(String id) {
var delegate = new BookExamples().open(id);
var dependencies = delegate.context();
return new PreviewSession<>() {
public Book model() { return delegate.model(); }
public ViewDependencies context() {
return new ViewDependencies() {
public boolean isComponent(Class<?> type) { return dependencies.isComponent(type); }
public <T> Optional<T> findService(Class<T> type) { return dependencies.findService(type); }
public <T> ViewObject<T> createViewObject(Class<T> type) {
var acquired = dependencies.createViewObject(type);
return new ViewObject<>(acquired.instance(), () -> {
acquired.release().run();
if (type == BookController.class) throw new IllegalStateException("release failed");
});
}
};
}
public void close() throws Exception { delegate.close(); }
};
}
}
public static final class WrongExample implements PreviewProvider<Book, Object> {
@Override
public Class<Book> modelType() { return Book.class; }
@Override
public PreviewSession<Book, Object> open(String id) {
return new PreviewSession<>() {
public Book model() { return new Book(); }
public Object context() { return new Object(); }
public void close() {}
};
}
}
}
@@ -0,0 +1,23 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>de.neitzel.fxdesigner.fixtures</groupId>
<artifactId>spring-di-legacy-runtime</artifactId>
<version>1</version>
<properties>
<neitzellib.version>1.0.6</neitzellib.version>
</properties>
<repositories>
<repository>
<id>gitea-neitzelfxdesigner</id>
<url>https://gitea.neitzel.de/api/packages/konrad/maven</url>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>${neitzellib.version}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,22 @@
{
"schemaVersion": "1.0",
"contexts": {
"spring": {
"applicationModule": "app",
"launchMode": "module-path",
"buildRuntime": "java25",
"targetRuntime": "java25",
"buildJava": 25,
"targetJava": 25,
"preview": {
"sourceSet": "module",
"module": "preview",
"provider": "fixture.spring.preview.BookExamples",
"defaultExample": "book"
},
"modulePath": {
"entryModule": "fixture.spring.preview"
}
}
}
}
+38
View File
@@ -0,0 +1,38 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>de.neitzel.fxdesigner.fixtures</groupId>
<artifactId>spring-di</artifactId>
<version>1</version>
<packaging>pom</packaging>
<modules>
<module>app</module>
<module>preview</module>
</modules>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<designer.version>0.1.1-SNAPSHOT</designer.version>
<jakarta-annotation.version>2.1.1</jakarta-annotation.version>
<jakarta-inject.version>2.0.1</jakarta-inject.version>
<neitzellib.version>1.0.7-SNAPSHOT</neitzellib.version>
<spring.version>6.2.11</spring.version>
<javafx-maven-plugin.version>0.0.8</javafx-maven-plugin.version>
<maven-compiler-plugin.version>3.16.0</maven-compiler-plugin.version>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
@@ -0,0 +1,21 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.neitzel.fxdesigner.fixtures</groupId>
<artifactId>spring-di</artifactId>
<version>1</version>
</parent>
<artifactId>spring-di-preview</artifactId>
<dependencies>
<dependency>
<groupId>de.neitzel.fxdesigner.fixtures</groupId>
<artifactId>spring-di-app</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>de.neitzel.fxdesigner</groupId>
<artifactId>designer-preview-api</artifactId>
<version>${designer.version}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,44 @@
package fixture.spring.preview;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
import fixture.spring.app.FixtureService;
import fixture.spring.app.SpringBookContext;
import fixture.spring.model.Book;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
public final class BookExamples implements PreviewProvider<Book, ViewDependencies> {
private static FixtureService lastService;
public static FixtureService lastService() { return lastService; }
@Override
public Class<Book> modelType() { return Book.class; }
@Override
public PreviewSession<Book, ViewDependencies> open(String id) {
var book = Book.sample("Preview contact book");
var spring = SpringBookContext.open("Preview service");
lastService = spring.service();
return new PreviewSession<>() {
@Override
public Book model() { return book; }
@Override
public ViewDependencies context() { return spring.dependencies(); }
@Override
public CompletionStage<Void> ready() {
if (id.equals("cancel")) return new CompletableFuture<>();
if (id.equals("readiness")) return CompletableFuture.failedFuture(new IllegalStateException("Example failed"));
return PreviewSession.super.ready();
}
@Override
public void close() { spring.close(); }
};
}
}
@@ -0,0 +1,29 @@
package fixture.spring.preview;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
import fixture.spring.app.SpringBookContext;
import fixture.spring.model.Entry;
public final class CardExamples implements PreviewProvider<Entry, ViewDependencies> {
@Override
public Class<Entry> modelType() { return Entry.class; }
@Override
public PreviewSession<Entry, ViewDependencies> open(String id) {
var model = new Entry("Preview entry");
var spring = SpringBookContext.open("Card preview service");
return new PreviewSession<>() {
@Override
public Entry model() { return model; }
@Override
public ViewDependencies context() { return spring.dependencies(); }
@Override
public void close() { spring.close(); }
};
}
}
@@ -0,0 +1,7 @@
module fixture.spring.preview {
requires de.neitzel.fxdesigner.preview;
requires fixture.spring.app;
requires fx;
exports fixture.spring.preview;
}
@@ -0,0 +1,14 @@
format=1
count=2
example.0.id=book
example.0.label=Spring contact book
example.0.modelType=fixture.spring.model.Book
example.0.providerClass=fixture.spring.preview.BookExamples
example.0.viewResource=fixture/spring/ui/Book.fxml
example.0.componentPackage=fixture.spring.app
example.1.id=card
example.1.label=Spring entry
example.1.modelType=fixture.spring.model.Entry
example.1.providerClass=fixture.spring.preview.CardExamples
example.1.viewResource=fixture/spring/ui/EntryCard.fxml
example.1.componentPackage=fixture.spring.app
@@ -0,0 +1,101 @@
import de.neitzel.fx.example.DeskApp;
import de.neitzel.fx.example.model.Person;
import de.neitzel.fxdesigner.preview.ExampleDescriptor;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
import de.neitzel.fxdesigner.target.ExampleCatalog;
import de.neitzel.fxdesigner.target.PreviewFailure;
import de.neitzel.fxdesigner.target.TargetPreview;
import de.neitzel.injection.ApplicationContext;
import java.time.Duration;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
/** Exercises actual Person Desk preview providers against the split FX artifacts. */
public final class NeitzelAdapterPreviewCheck {
public static void main(String[] args) throws Exception {
var loader = NeitzelAdapterPreviewCheck.class.getClassLoader();
String scenario = args[0];
if (scenario.equals("application")) {
application();
return;
}
String example = scenario.equals("row") ? "row" : "desk";
var descriptor = ExampleCatalog.discover(loader).stream()
.filter(entry -> entry.id().equals(example)).findFirst().orElseThrow();
if (scenario.equals("raw-context"))
descriptor = new ExampleDescriptor("raw-context", descriptor.label(), descriptor.modelType(),
LegacyProvider.class.getName(), descriptor.viewResource(), descriptor.componentPackage());
Platform.startup(() -> Platform.setImplicitExit(false));
try (var preview = TargetPreview.open(descriptor, loader, Duration.ofSeconds(25))) {
try {
preview.ready().toCompletableFuture().get(25, TimeUnit.SECONDS);
if (scenario.equals("raw-context")) throw new AssertionError("Raw ApplicationContext was accepted");
var check = new FutureTask<Void>(() -> {
var view = preview.loadedView();
if (scenario.equals("row")) {
((Button) view.getRoot().lookup(".button")).fire();
} else if (!"Ada Lovelace".equals(((TextField) view.getRoot().lookup("#nameField")).getText())) {
throw new AssertionError("The Person Desk Model was not bound");
}
if (preview.render(500, 380).length != 500 * 380 * 4)
throw new AssertionError("Unexpected render size");
return null;
});
Platform.runLater(check);
check.get(15, TimeUnit.SECONDS);
} catch (ExecutionException failure) {
if (!scenario.equals("raw-context")
|| !(failure.getCause() instanceof PreviewFailure diagnostic)
|| diagnostic.code() != PreviewFailure.Code.CONTEXT_TYPE
|| !diagnostic.getMessage().contains("fx-injection")) throw failure;
}
preview.close();
preview.cleanup().toCompletableFuture().get(10, TimeUnit.SECONDS);
System.out.println("PASS " + scenario);
} finally {
Platform.exit();
}
}
private static void application() throws Exception {
var check = new FutureTask<Void>(() -> {
var window = new Stage();
try {
new DeskApp().start(window);
if (!window.isShowing()
|| !"Ada Lovelace".equals(((TextField) window.getScene().lookup("#nameField")).getText()))
throw new AssertionError("The migrated Person Desk did not open");
} finally {
window.close();
}
return null;
});
Platform.startup(check);
try {
check.get(15, TimeUnit.SECONDS);
System.out.println("PASS application");
} finally {
Platform.exit();
}
}
public static final class LegacyProvider implements PreviewProvider<Person, ApplicationContext> {
public Class<Person> modelType() { return Person.class; }
public PreviewSession<Person, ApplicationContext> open(String example) {
var person = DeskApp.sample();
var context = DeskApp.dependencies(person).context();
return new PreviewSession<>() {
public Person model() { return person; }
public ApplicationContext context() { return context; }
public void close() {}
};
}
}
}
@@ -0,0 +1,66 @@
package qualification;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.stage.Window;
/** Test-only observer of the actual interactive window, inside the target JVM. */
public final class SpringTargetProbe {
public static void premain(String output) {
var command = System.getProperty("sun.java.command", "").split(" ", 2)[0];
if (command.endsWith(".WorkerMain"))
Thread.ofPlatform().daemon().name("spring-preview-probe").start(() -> Observer.observe(Path.of(output)));
}
private static class Observer {
private static void observe(Path output) {
try {
while (true) {
Thread.sleep(100);
var inspect = new FutureTask<>(() -> inspect(output));
try {
Platform.runLater(inspect);
} catch (IllegalStateException toolkitStarting) {
continue;
}
if (inspect.get(10, TimeUnit.SECONDS)) return;
}
} catch (InterruptedException stopped) {
Thread.currentThread().interrupt();
} catch (Throwable error) {
try {
Files.writeString(output.resolve("target-error.txt"), error.toString());
} catch (Exception writeFailure) {
error.addSuppressed(writeFailure);
error.printStackTrace();
}
}
}
private static boolean inspect(Path output) throws Exception {
var stage = Window.getWindows().stream()
.filter(w -> w instanceof Stage window && window.isShowing() && window.getOpacity() > 0
&& window.getTitle() != null && window.getTitle().startsWith("Neitzel preview"))
.findFirst();
if (stage.isEmpty()) return false;
String attempt = Files.readString(output.resolve("spring-attempt"));
boolean book = attempt.startsWith("book-");
var scene = stage.get().getScene();
var field = (TextField) scene.lookup(book ? "#bookName" : "#entryName");
String expected = book ? "Preview contact book" : "Preview entry";
if (field == null || !expected.equals(field.getText()))
throw new AssertionError("Expected fresh " + expected + " in " + attempt);
field.setText("Edited in preview");
if (book && !"[Edited in preview]".equals(((Label) scene.lookup("#convertedName")).getText()))
throw new AssertionError("Spring Converter did not update the live interactive View");
Files.writeString(output.resolve(attempt + ".txt"), expected);
return true;
}
}
}
@@ -0,0 +1,44 @@
package qualification;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupActivity;
import com.intellij.openapi.vfs.LocalFileSystem;
import de.neitzel.fxdesigner.kit.SpringPreviewHostChecks;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import static qualification.WorkflowProbe.edt;
import static qualification.WorkflowProbe.openDesigner;
import static qualification.WorkflowProbe.output;
public final class SpringWorkflowProbe implements StartupActivity.DumbAware {
public void runActivity(Project project) {
if (!WorkflowProbe.started.compareAndSet(false, true)) return;
ApplicationManager.getApplication().executeOnPooledThread(() -> {
try {
var path = Path.of(project.getBasePath(), "app/src/main/resources/fixture/spring/ui");
verify(project, path.resolve("Book.fxml"), "Spring contact book", true);
verify(project, path.resolve("EntryCard.fxml"), "Spring entry", false);
Files.writeString(output.resolve("SUCCESS.txt"),
"PASS Spring canvas, form and interactive previews in the registered IntelliJ editor");
} catch (Throwable failure) {
var trace = new StringWriter();
failure.printStackTrace(new PrintWriter(trace));
try {
Files.writeString(output.resolve("FAILURE.txt"), trace.toString());
} catch (Exception writeFailure) {
failure.addSuppressed(writeFailure);
failure.printStackTrace();
}
}
});
}
private static void verify(Project project, Path path, String label, boolean book) throws Exception {
var file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path));
SpringPreviewHostChecks.verify(openDesigner(project, file), label, book, output);
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ def run(command):
wrapper = ROOT / ("mvnw.cmd" if os.name == "nt" else "mvnw")
run([sys.executable, ROOT / "scripts/check-neitzellib-artifact.py", "--resolve"])
run([wrapper, "-B", "-ntp", "clean", "install"])
run([wrapper, "-B", "-ntp", "-pl", "designer-target-tools", "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:build-classpath", "-DincludeScope=runtime", "-Dmdep.outputFile=target/runtime-classpath.txt"])
run([wrapper, "-B", "-ntp", "-pl", "designer-target-tools", "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:build-classpath", "-DincludeScope=compile", "-Dmdep.outputFile=target/runtime-classpath.txt"])
for module in ("contracts", "model-processor", "preview-api", "core", "kit-ui", "standalone", "target-tools", "maven-plugin"):
name = "designer-" + module
expected = 69
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Run the migrated Person Desk provider against the current Designer target worker."""
import argparse
import os
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parent.parent
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--library", type=Path, required=True)
parser.add_argument("--target-java-home", type=Path, required=True)
args = parser.parse_args()
library = args.library.resolve()
example = library / "fx-example"
java = args.target_java_home.resolve()
env = dict(os.environ, JAVA_HOME=str(java))
def run(command, timeout, cwd=ROOT):
return subprocess.run(list(map(str, command)), env=env, cwd=cwd, check=True, timeout=timeout)
run([library / "mvnw", "-B", "-ntp", "-f", example / "pom.xml", "-Pdesigner-preview",
"test-compile", "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:build-classpath",
"-DincludeScope=test", "-Dmdep.outputFile=target/adapter-preview-runtime.txt"], 180, cwd=library)
target = example / "target"
tools = [ROOT / f"designer-{module}/target/designer-{module}-0.1.1-SNAPSHOT.jar"
for module in ("target-tools", "contracts", "preview-api")]
classpath = os.pathsep.join([str(target / "test-classes"), str(target / "classes"),
*map(str, tools), (target / "adapter-preview-runtime.txt").read_text().strip()])
for mode in ("application", "desk", "row", "raw-context"):
run([java / "bin/java", "--enable-native-access=ALL-UNNAMED", "-cp", classpath,
ROOT / "integration-tests/fx-example/NeitzelAdapterPreviewCheck.java", mode], 45)
+12 -1
View File
@@ -7,15 +7,21 @@ from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
ROOT = Path(__file__).resolve().parent.parent
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--target-java-home", required=True)
parser.add_argument("--neitzellib-version", help="Use this preinstalled legacy FX version for the old fixtures")
parser.add_argument("--spring-di", action="store_true",
help="Also run Spring previews with the locally installed DI adapter snapshot")
args = parser.parse_args()
java_home = Path(args.target_java_home).resolve()
env = dict(os.environ, JAVA_HOME=str(java_home))
output = ROOT / "designer-target-tools/target/preview-fixtures"
if args.neitzellib_version:
output = output / args.neitzellib_version
output.mkdir(parents=True, exist_ok=True)
results = []
@@ -33,7 +39,8 @@ def run(label, command, timeout=180):
def build(path, label):
run(label, [ROOT / "mvnw", "-B", "-ntp", "-f", path / "pom.xml", "package",
"org.apache.maven.plugins:maven-dependency-plugin:3.6.1:build-classpath",
"-DincludeScope=test", "-Dmdep.outputFile=target/runtime.txt"])
"-DincludeScope=test", "-Dmdep.outputFile=target/runtime.txt",
*([f"-Dneitzellib.version={args.neitzellib_version}"] if args.neitzellib_version else [])])
def launch(path, arrangement, mode, label):
@@ -81,3 +88,7 @@ with tempfile.TemporaryDirectory(prefix="designer-preview-") as temp:
descriptor.write_text(original)
(output / "results.json").write_text(json.dumps(results, indent=2) + "\n")
print(f"PASS {len(results)} target processes, {sum(r['checks'] for r in results)} fixture checks")
if args.spring_di:
subprocess.run([sys.executable, ROOT / "scripts/check-spring-preview.py",
"--target-java-home", java_home], env=env, cwd=ROOT, check=True)
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Exercise the Spring fixture in native standalone and registered IntelliJ hosts."""
import argparse
import os
from pathlib import Path
import re
import signal
import subprocess
import sys
import time
from native_crashes import NativeCrashGuard, await_worker_exit, descendant_workers
ROOT = Path(__file__).resolve().parent.parent
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--java-home", type=Path, required=True)
parser.add_argument("--target-java-home", type=Path, required=True)
parser.add_argument("--idea-home", type=Path)
parser.add_argument("--host", choices=("all", "standalone", "intellij"), default="all")
args = parser.parse_args()
hosts = ("standalone", "intellij") if args.host == "all" else (args.host,)
if "intellij" in hosts and args.idea_home is None:
parser.error("--idea-home is required for the IntelliJ check")
for host in hosts:
crashes = NativeCrashGuard(ROOT)
idea = ["--idea-home", args.idea_home] if host == "intellij" else []
result = subprocess.run([sys.executable, ROOT / "scripts/run-fixture-host.py", host,
"--spring-di", "--check", "--java-home", args.java_home,
"--target-java-home", args.target_java_home, *idea],
cwd=ROOT, capture_output=True, text=True, timeout=90)
if result.returncode:
raise RuntimeError(result.stdout + result.stderr)
pid = int(re.search(r"Host PID: (\d+)", result.stdout)[1])
evidence = Path(re.search(r"Disposable host: (.+)", result.stdout)[1])
print(f"{host} evidence: {evidence}", flush=True)
log = evidence / "launcher.log"
success = evidence / "SUCCESS.txt"
failure = evidence / "FAILURE.txt"
try:
deadline = time.monotonic() + 240
while time.monotonic() < deadline:
if success.exists():
print(success.read_text(), flush=True)
break
if failure.exists():
raise RuntimeError(failure.read_text())
try:
os.kill(pid, 0)
except ProcessLookupError:
raise RuntimeError(log.read_text()[-12000:]) from None
if subprocess.run(["ps", "-p", str(pid), "-o", "state="], capture_output=True,
text=True).stdout.lstrip().startswith("Z"):
raise RuntimeError(log.read_text()[-12000:])
time.sleep(0.25)
else:
raise RuntimeError("Host qualification timed out\n" + log.read_text()[-12000:])
finally:
workers = descendant_workers(pid)
try:
os.kill(pid, signal.SIGTERM)
except ProcessLookupError:
pass
await_worker_exit(workers)
crashes.check()
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Run the Spring app and preview in fresh JavaFX processes on classpath and module path."""
import argparse
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parent.parent
FIXTURE = ROOT / "integration-fixtures/spring-di"
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--target-java-home", type=Path, required=True)
args = parser.parse_args()
java = args.target_java_home.resolve() / "bin"
env = dict(os.environ, JAVA_HOME=str(java.parent))
logs = ROOT / "target/spring-preview"
logs.mkdir(parents=True, exist_ok=True)
def run(label, command, timeout=120):
result = subprocess.run(list(map(str, command)), env=env, cwd=ROOT,
capture_output=True, text=True, timeout=timeout)
log = result.stdout + result.stderr
(logs / (label + ".log")).write_text(log)
if result.returncode:
raise RuntimeError(label + "\n" + log[-10000:])
return log
with tempfile.TemporaryDirectory(prefix="designer-spring-preview-") as temporary:
project = Path(temporary) / "spring-di"
shutil.copytree(FIXTURE, project, ignore=shutil.ignore_patterns("target", ".neitzel-fx-designer"))
run("build", [ROOT / "mvnw", "-B", "-ntp", "-f", project / "pom.xml", "package",
"org.apache.maven.plugins:maven-dependency-plugin:3.6.1:build-classpath",
"org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree",
"-Dmdep.outputFile=target/runtime.txt", "-DoutputFile=target/dependencies.txt"])
for module in ("app", "preview"):
tree = (project / module / "target/dependencies.txt").read_text()
(logs / f"{module}-dependencies.txt").write_text(tree)
if re.search(r"de\.neitzel\.lib:(?:fx-)?injection:|org\.reflections:reflections:", tree):
raise AssertionError(f"Unexpected DI dependency in {module}\n{tree}")
target = project / "preview/target"
tools = [ROOT / f"designer-{module}/target/designer-{module}-0.1.1-SNAPSHOT.jar"
for module in ("target-tools", "contracts", "preview-api")]
resolved = [Path(path) for path in (target / "runtime.txt").read_text().strip().split(os.pathsep)]
entries = list(dict.fromkeys([target / "spring-di-preview-1.jar", *resolved, *tools[:2]]))
(logs / "runtime-entries.txt").write_text("\n".join(map(str, entries)) + "\n")
cp = os.pathsep.join(map(str, entries))
classes = Path(temporary) / "checks"
run("compile-checks", [java / "javac", "-cp", cp, "-d", classes,
*sorted((project / "checks").glob("*.java"))])
results = []
def launch(label, mode, options, main="SpringChecks"):
access = "ALL-UNNAMED,javafx.graphics" if "--module-path" in options else "ALL-UNNAMED"
log = run(label, [java / "java", "--enable-native-access=" + access,
*options, main, mode], timeout=40)
match = re.search(r"^PASS " + re.escape(mode) + r" (\d+)$", log, re.MULTILINE)
assert match, log
if mode in ("application", "book", "card"):
arrangement = "module-path" if "--module-path" in options else "classpath"
assert f"SPRING FX ISOLATION {arrangement} " in log, log
results.append(int(match[1]))
print(label + ": " + match[0], flush=True)
for arrangement in ("classpath", "modulepath"):
options = (["-cp", str(classes) + os.pathsep + cp] if arrangement == "classpath"
else ["--module-path", cp, "--add-modules", "ALL-MODULE-PATH", "-cp", classes])
for mode in ("application", "book", "book-fresh", "card", "invalid", "readiness", "cancel",
"wrong-context", "missing-resource", "release-failure"):
launch(arrangement + "-" + mode, "book" if mode == "book-fresh" else mode, options)
if arrangement == "modulepath":
launch("modulepath-closed-resource", "closed-resource", options)
legacy_path = Path(temporary) / "legacy-runtime.txt"
run("resolve-legacy-runtime", [
ROOT / "mvnw", "-B", "-ntp", "-f", project / "checks/legacy/pom.xml",
"org.apache.maven.plugins:maven-dependency-plugin:3.6.1:build-classpath",
f"-Dmdep.outputFile={legacy_path}"])
legacy_runtime = os.pathsep.join([str(classes), *map(str, tools), legacy_path.read_text().strip()])
launch("classpath-missing-capability", "missing-capability", ["-cp", legacy_runtime], main="CapabilityCheck")
print(f"PASS {len(results)} Spring target processes, {sum(results)} checks", flush=True)
+28
View File
@@ -18,6 +18,7 @@ p.add_argument("--target-java-home", type=Path, required=True)
p.add_argument("--idea-home", type=Path)
p.add_argument("--check", action="store_true", help="Install the disposable IDE qualification companion")
p.add_argument("--mode", choices=["classpath","modulepath"], default="classpath")
p.add_argument("--spring-di", action="store_true", help="Use the Spring DI preview fixture")
p.add_argument("--archiver", type=Path, help="Use a disposable copy of the Archiver project")
forms = p.add_mutually_exclusive_group()
forms.add_argument("--connection-form", action="store_true", help="Open and qualify the Archiver connection form")
@@ -36,6 +37,8 @@ forms.add_argument("--saved-document", action="store_true", help="Open the Archi
args = p.parse_args()
if (args.connection_form or args.grid_docking or args.saved_document or args.document_tabs or args.import_form or args.folder_actions or args.reader_states or args.viewer_import or args.row_menus or args.folder_profiles or args.management_readers or args.media_layout_grid or args.dock_rules) and not args.archiver:
p.error("Selecting an Archiver view requires --archiver")
if args.spring_di and args.archiver:
p.error("Choose only one fixture")
base = Path(tempfile.mkdtemp(prefix="neitzel-designer-host-")).resolve()
project = base / "project"
if args.archiver:
@@ -88,17 +91,39 @@ if args.archiver:
raise ValueError(f"Expected the shipped sample binding for {control}.{prop}")
source = source.replace(declaration, "")
file.write_text(source)
elif args.spring_di:
shutil.copytree(ROOT / "integration-fixtures/spring-di", project,
ignore=shutil.ignore_patterns("target", ".neitzel-fx-designer"))
subprocess.run([sys.executable, ROOT / "scripts/configure-library-example.py", "--project", project,
"--target-java-home", args.target_java_home], check=True)
file = project / "app/src/main/resources/fixture/spring/ui/Book.fxml"
else:
subprocess.run([sys.executable, ROOT / "scripts/prepare-fixture-host.py", "--destination", project,
"--target-java-home", args.target_java_home, "--mode", args.mode], check=True)
file = project / "app/src/main/resources/fixture/components/Person.fxml"
settings = project / ".neitzel-fx-designer/host.properties"
env = dict(os.environ)
if args.spring_di and args.check:
agent_classes = base / "agent-classes"
classpath = (ROOT / "designer-standalone/target/smoke-classpath.txt").read_text().strip()
subprocess.run([args.java_home / "bin/javac", "-cp", classpath, "-d", agent_classes,
ROOT / "integration-tests/idea/SpringTargetProbe.java"], check=True)
agent = base / "spring-ui-check.jar"
with zipfile.ZipFile(agent, "w") as archive:
archive.writestr("META-INF/MANIFEST.MF",
"Manifest-Version: 1.0\nPremain-Class: qualification.SpringTargetProbe\n\n")
for item in agent_classes.rglob("*.class"):
archive.write(item, item.relative_to(agent_classes))
env["JAVA_TOOL_OPTIONS"] = env.get("JAVA_TOOL_OPTIONS", "") + f' "-javaagent:{agent}={base}"'
if args.host == "standalone":
cp = os.pathsep.join([str(ROOT / "designer-standalone/target/classes"),
(ROOT / "designer-standalone/target/smoke-classpath.txt").read_text().strip()])
command = [str(args.java_home / "bin/java"), "--enable-native-access=ALL-UNNAMED", "-cp", cp,
"de.neitzel.fxdesigner.standalone.Launcher", str(settings), str(file)]
if args.spring_di and args.check:
command[3] = str(ROOT / "designer-standalone/target/test-classes") + os.pathsep + cp
command[4] = "de.neitzel.fxdesigner.standalone.SpringPreviewHostSmoke"
command.append(str(base))
else:
if args.idea_home is None:
p.error("--idea-home is required for IntelliJ")
@@ -142,6 +167,9 @@ else:
suite = "SavedDocument"
probe = f"{suite}WorkflowProbe" if args.archiver else "WorkflowProbe"
files = [sources / "WorkflowProbe.java"]
if args.spring_di:
probe = "SpringWorkflowProbe"
files.append(sources / f"{probe}.java")
if args.connection_form or args.saved_document or args.document_tabs or args.import_form or args.folder_actions or args.reader_states or args.viewer_import or args.row_menus or args.folder_profiles or args.management_readers or args.media_layout_grid or args.dock_rules:
files.append(sources / "FormWorkflowProbe.java")
if args.media_layout_grid or args.dock_rules or args.reader_states or args.viewer_import or args.row_menus or args.folder_profiles: