From f9c3de2d2b9cc377e5deb3298f258807516bfaba Mon Sep 17 00:00:00 2001 From: Konrad Neitzel Date: Tue, 24 Nov 2026 17:54:36 +0100 Subject: [PATCH] Render WebView content and qualify Archiver document previews in IntelliJ --- README.md | 2 + .../fxdesigner/target/TargetPreview.java | 129 ++++++++-- .../neitzel/fxdesigner/target/WorkerMain.java | 33 ++- .../idea/ConnectionWorkflowProbe.java | 135 +---------- integration-tests/idea/FormWorkflowProbe.java | 144 +++++++++++ .../idea/SavedDocumentTargetProbe.java | 224 ++++++++++++++++++ .../idea/SavedDocumentWorkflowProbe.java | 114 +++++++++ scripts/check-ide-host.py | 16 +- scripts/run-fixture-host.py | 31 ++- 9 files changed, 653 insertions(+), 175 deletions(-) create mode 100644 integration-tests/idea/FormWorkflowProbe.java create mode 100644 integration-tests/idea/SavedDocumentTargetProbe.java create mode 100644 integration-tests/idea/SavedDocumentWorkflowProbe.java diff --git a/README.md b/README.md index 1a955e5..34efb84 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,8 @@ Open **Bindings → DataGrid / Docking** in `FolderTab.fxml` to select the grid In `ArchiveWindow.fxml`, select a layout branch to split it or an outer side area to move it. **Add area with group** creates a destination in an unused area. The **Beispielarchiv** example opens a document and its details in the declared destinations. Both the embedded image and the interactive window use this layout. To repeat both acceptance scenarios, add `--grid-docking ../NeitzelLib/fx-example/src/main/resources/de/neitzel/fx/example/docking/workspace/ReferenceWorkspace.fxml` to the Archiver host check. +Add `--saved-document` to the Archiver launcher or host check to open the designer-profile view `SavedDocument.fxml`. Under **Form controls**, select **HtmlViewer #article** to edit the media button labels and tooltips. Select **AutoCompleteTextField #fixed** and edit **suggestions**, one tag per line. **Build and Refresh** discovers **HTML · Rechnung** and **HTML · Lieferschein**. **Form preview** shows the rendered HTML at the selected dimensions. In **Interactive preview**, use **Dokument wechseln**, edit **HTML-Quelle**, or type **Re** and **Li** into **Dokument-Tags** before and after switching. The example controller forwards HTML to the viewer and binds the contents of the dynamic tag list. + For an existing Archiver checkout, install the built plugin ZIP and create the ignored local JDK and worker mappings once with `python3 scripts/configure-library-example.py --project ../Archiver --target-java-home "$JAVA_HOME"`. Launch the IDE with access to the Maven repository containing the qualified snapshots. The [save/startup reliability follow-up](docs/ide-host-reliability.md) covers queued IntelliJ VFS writes and host-revision/validation races, including repeated registered module-path qualification. Add `--mode modulepath --repeat 3` to the IDE runner to repeat that gate. diff --git a/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/TargetPreview.java b/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/TargetPreview.java index f34754b..53e70a9 100644 --- a/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/TargetPreview.java +++ b/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/TargetPreview.java @@ -21,6 +21,10 @@ public final class TargetPreview implements AutoCloseable { private Scene scene; private final Occurrences occurrences = new Occurrences(); private javafx.stage.Stage interactive; + + private record WindowGeometry(double x, double y, double width, double height, double opacity) {} + + private WindowGeometry beforeWebSnapshot; private boolean closed; private final CompletableFuture ready = new CompletableFuture<>(); private final CompletableFuture cleanup = new CompletableFuture<>(); @@ -195,6 +199,15 @@ public final class TargetPreview implements AutoCloseable { } public byte[] renderNode(String nodeId, int width, int height) { + return snapshotNode(nodeId, width, height, false).toCompletableFuture().join(); + } + + CompletionStage frame(String nodeId, int width, int height) { + return snapshotNode(nodeId, width, height, true); + } + + private CompletionStage snapshotNode( + String nodeId, int width, int height, boolean waitForWeb) { fx(); if (closed || !ready.isDone() || ready.isCompletedExceptionally()) throw new IllegalStateException("Preview not ready"); @@ -205,7 +218,31 @@ public final class TargetPreview implements AutoCloseable { || (long) width * height * 4 > 16 * 1024 * 1024) throw new IllegalArgumentException("Image exceeds protocol limits"); var node = occurrences.resolve(view.getRoot(), nodeId); - if (node == view.getRoot()) layout(width, height); + boolean web = waitForWeb && node != null && node.lookup("WebView") != null; + if (web && !interactive.isShowing()) { + beforeWebSnapshot = + new WindowGeometry( + interactive.getX(), + interactive.getY(), + interactive.getWidth(), + interactive.getHeight(), + interactive.getOpacity()); + double right = + javafx.stage.Screen.getScreens().stream() + .mapToDouble(s -> s.getBounds().getMaxX()) + .max() + .orElse(0); + interactive.setX(right + 1); + interactive.setOpacity(0); + interactive.show(); + } + if (node == view.getRoot()) { + if (web && beforeWebSnapshot != null) { + interactive.setWidth(width + Math.max(0, interactive.getWidth() - scene.getWidth())); + interactive.setHeight(height + Math.max(0, interactive.getHeight() - scene.getHeight())); + } + layout(width, height); + } if (node == null) throw new IllegalArgumentException("Unknown rendered node: " + nodeId); boolean isolate = node != view.getRoot() && node.isResizable(); boolean managed = node.isManaged(); @@ -222,23 +259,75 @@ public final class TargetPreview implements AutoCloseable { parameters.setFill(Color.TRANSPARENT); var bounds = node.getBoundsInParent(); parameters.setViewport(new Rectangle2D(bounds.getMinX(), bounds.getMinY(), width, height)); - var image = node.snapshot(parameters, new WritableImage(width, height)); - byte[] bytes = new byte[width * height * 4]; - var pixels = image.getPixelReader(); - for (int y = 0; y < height; y++) - for (int x = 0; x < width; x++) { - int argb = pixels.getArgb(x, y), i = (y * width + x) * 4; - bytes[i] = (byte) (argb >>> 16); - bytes[i + 1] = (byte) (argb >>> 8); - bytes[i + 2] = (byte) argb; - bytes[i + 3] = (byte) (argb >>> 24); - } - return bytes; - } finally { + var image = new WritableImage(width, height); + if (web) { + var frame = webFrame(node, parameters, image); + return frame.whenComplete( + (ignored, error) -> { + if (isolate) node.setManaged(managed); + }); + } + var bytes = pixels(node.snapshot(parameters, image)); if (isolate) node.setManaged(managed); + return CompletableFuture.completedFuture(bytes); + } catch (Throwable error) { + if (isolate) node.setManaged(managed); + throw error; } } + /** + * WebKit updates its render queue on a stage pulse, before scene layout. Give it a pulse at the + * new layout size before reading the next snapshot. + */ + private CompletionStage webFrame( + Node node, SnapshotParameters parameters, WritableImage image) { + var result = new CompletableFuture(); + Scene owner = scene; + owner.addPostLayoutPulseListener( + new Runnable() { + public void run() { + owner.removePostLayoutPulseListener(this); + Platform.runLater( + () -> { + try { + if (closed) throw new CancellationException("Preview closed"); + node.snapshot( + snapshot -> { + try { + result.complete(pixels(snapshot.getImage())); + } catch (Throwable error) { + result.completeExceptionally(error); + } + return null; + }, + parameters, + image); + } catch (Throwable error) { + result.completeExceptionally(error); + } + }); + } + }); + Platform.requestNextPulse(); + return result; + } + + private static byte[] pixels(javafx.scene.image.Image image) { + int width = (int) image.getWidth(), height = (int) image.getHeight(); + byte[] bytes = new byte[width * height * 4]; + var pixels = image.getPixelReader(); + for (int y = 0; y < height; y++) + for (int x = 0; x < width; x++) { + int argb = pixels.getArgb(x, y), i = (y * width + x) * 4; + bytes[i] = (byte) (argb >>> 16); + bytes[i + 1] = (byte) (argb >>> 8); + bytes[i + 2] = (byte) argb; + bytes[i + 3] = (byte) (argb >>> 24); + } + return bytes; + } + public de.neitzel.fxdesigner.protocol.LayoutMetrics measure(String key, int width, int height) { fx(); var node = occurrences.resolve(view.getRoot(), key); @@ -264,6 +353,18 @@ public final class TargetPreview implements AutoCloseable { public void showInteractive(String title, Runnable onClosed) { fx(); + if (beforeWebSnapshot != null) { + var previous = beforeWebSnapshot; + beforeWebSnapshot = null; + interactive.hide(); + interactive.setOpacity(previous.opacity()); + if (Double.isFinite(previous.width())) interactive.setWidth(previous.width()); + if (Double.isFinite(previous.height())) interactive.setHeight(previous.height()); + if (Double.isFinite(previous.x()) && Double.isFinite(previous.y())) { + interactive.setX(previous.x()); + interactive.setY(previous.y()); + } else interactive.centerOnScreen(); + } interactive.setOnHidden(e -> onClosed.run()); interactive.setTitle(title); interactive.show(); diff --git a/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/WorkerMain.java b/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/WorkerMain.java index 1f78ad6..8391796 100644 --- a/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/WorkerMain.java +++ b/designer-target-tools/src/main/java/de/neitzel/fxdesigner/target/WorkerMain.java @@ -205,13 +205,30 @@ public final class WorkerMain { () -> { if (stopping.get()) return; try { - send( - socket, - new Packet( - Kind.RESULT, - p.operation(), - p.identity(), - response(ready, p, data))); + var result = + p.operation() == Operation.RENDER + ? ready.frame( + data.get("node"), + p.identity().width(), + p.identity().height()) + : java.util.concurrent.CompletableFuture.completedFuture( + response(ready, p, data)); + result.whenComplete( + (payload, failure) -> { + if (stopping.get()) return; + if (failure != null) { + error(socket, p, failure); + return; + } + try { + send( + socket, + new Packet( + Kind.RESULT, p.operation(), p.identity(), payload)); + } catch (IOException e) { + error(socket, p, e); + } + }); } catch (Throwable e) { error(socket, p, e); } @@ -231,8 +248,6 @@ public final class WorkerMain { private static byte[] response(TargetPreview ready, Packet p, Map data) throws Exception { return switch (p.operation()) { - case RENDER -> - ready.renderNode(data.get("node"), p.identity().width(), p.identity().height()); case MEASURE -> PreviewMessages.encode( ready diff --git a/integration-tests/idea/ConnectionWorkflowProbe.java b/integration-tests/idea/ConnectionWorkflowProbe.java index c2fd4fa..c09f9a2 100644 --- a/integration-tests/idea/ConnectionWorkflowProbe.java +++ b/integration-tests/idea/ConnectionWorkflowProbe.java @@ -2,13 +2,10 @@ package qualification; import static qualification.WorkflowProbe.*; -import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.project.Project; -import com.intellij.openapi.startup.StartupActivity; import com.intellij.openapi.vfs.*; -import de.neitzel.fxdesigner.kit.DesignerPane; import java.nio.file.*; import java.util.*; import javafx.embed.swing.SwingFXUtils; @@ -16,112 +13,8 @@ import javafx.scene.control.*; import javafx.scene.image.*; import javax.imageio.ImageIO; -/** Drives the registered editor against a disposable copy of the real Archiver form. */ -public final class ConnectionWorkflowProbe implements StartupActivity.DumbAware { - private DesignerPane pane; - private VirtualFile file; - - public void runActivity(Project project) { - if (!started.compareAndSet(false, true)) return; - ApplicationManager.getApplication() - .executeOnPooledThread( - () -> { - try { - verify(project); - } catch (Throwable ex) { - try { - var trace = new java.io.StringWriter(); - ex.printStackTrace(new java.io.PrintWriter(trace)); - if (pane != null) - trace.append( - fx( - () -> - pane.lookupAll(".label").stream() - .filter(Label.class::isInstance) - .map(n -> Objects.toString(((Label) n).getText(), "")) - .filter(s -> !s.isEmpty()) - .toList() - .toString())); - Files.writeString(output.resolve("FAILURE.txt"), trace.toString()); - } catch (Exception failure) { - failure.printStackTrace(); - } - } - }); - } - - private void step(String message) throws Exception { - Files.writeString( - output.resolve("steps.txt"), - message + "\n", - StandardOpenOption.CREATE, - StandardOpenOption.APPEND); - } - - private String source() throws Exception { - return edt(() -> FileDocumentManager.getInstance().getDocument(file).getText()); - } - - private void controls(boolean expanded) throws Exception { - fx( - () -> { - var panel = - (TitledPane) - pane.lookupAll(".titled-pane").stream() - .filter(n -> n instanceof TitledPane t && t.getText().equals("Form controls")) - .findFirst() - .orElseThrow(); - panel.setAnimated(false); - panel.setExpanded(expanded); - pane.applyCss(); - pane.layout(); - return null; - }); - } - - private void choose(String selector, String text) throws Exception { - fx( - () -> { - var combo = (ComboBox) pane.lookup("#" + selector); - for (int i = 0; i < combo.getItems().size(); i++) { - if (combo.getItems().get(i).toString().equals(text)) { - combo.getSelectionModel().select(i); - return null; - } - } - for (int i = 0; i < combo.getItems().size(); i++) { - String label = combo.getItems().get(i).toString(); - if (label.equals(text) || label.contains(text)) { - combo.getSelectionModel().select(i); - return null; - } - } - throw new AssertionError(selector + " missing " + text + " in " + combo.getItems()); - }); - } - - private void edited(String before, String expected) throws Exception { - await( - () -> { - String now = source(); - String error = - fx( - () -> { - var label = (Label) pane.lookup("#form-message"); - return label == null ? "" : label.getText(); - }); - if (!error.isEmpty()) throw new AssertionError(error); - return !before.equals(now) - && now.contains(expected) - && fx( - () -> - ((TextArea) pane.lookup("#fxml-source")) == null - || ((TextArea) pane.lookup("#fxml-source")).getText().equals(now)); - }); - // Both the native document and visual selection are refreshed asynchronously. - fx(pane::flush).toCompletableFuture().get(10, java.util.concurrent.TimeUnit.SECONDS); - } - +/** Drives the registered editor against a disposable copy of the real Archiver connection form. */ +public final class ConnectionWorkflowProbe extends FormWorkflowProbe { private void add(String type, String destination, String id) throws Exception { step("Inserting " + type + " as " + id); choose("form-palette", type); @@ -151,18 +44,6 @@ public final class ConnectionWorkflowProbe implements StartupActivity.DumbAware step("Inserted " + type + " into " + destination); } - private void set(String name, String value, String expected) throws Exception { - choose("form-property", name); - fx( - () -> { - ((TextArea) pane.lookup("#form-value")).setText(value); - return null; - }); - String before = source(); - click(pane, "Set property"); - edited(before, expected); - } - private void bind(String name, String path) throws Exception { choose("form-property", name); click(pane, "Bind property"); @@ -211,16 +92,8 @@ public final class ConnectionWorkflowProbe implements StartupActivity.DumbAware step("In-editor " + id + " target frame " + width + " × 720"); } - private void awaitTarget(String name) throws Exception { - await( - () -> { - var error = output.resolve("target-error.txt"); - if (Files.exists(error)) throw new AssertionError(Files.readString(error)); - return Files.exists(output.resolve(name)); - }); - } - - private void verify(Project project) throws Exception { + @Override + void verify(Project project) throws Exception { var path = Path.of( project.getBasePath(), "src/main/resources/de/neitzel/archiver/ui/ConnectionForm.fxml"); diff --git a/integration-tests/idea/FormWorkflowProbe.java b/integration-tests/idea/FormWorkflowProbe.java new file mode 100644 index 0000000..bda0d40 --- /dev/null +++ b/integration-tests/idea/FormWorkflowProbe.java @@ -0,0 +1,144 @@ +package qualification; + +import static qualification.WorkflowProbe.*; + +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.fileEditor.*; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.startup.StartupActivity; +import com.intellij.openapi.vfs.*; +import de.neitzel.fxdesigner.kit.DesignerPane; +import java.nio.file.*; +import java.util.*; +import javafx.scene.control.*; +import javafx.scene.image.*; + +/** Shared actions on the real form inspector in the registered editor. */ +abstract class FormWorkflowProbe implements StartupActivity.DumbAware { + DesignerPane pane; + VirtualFile file; + + public void runActivity(Project project) { + if (!started.compareAndSet(false, true)) return; + ApplicationManager.getApplication() + .executeOnPooledThread( + () -> { + try { + verify(project); + } catch (Throwable ex) { + try { + var trace = new java.io.StringWriter(); + ex.printStackTrace(new java.io.PrintWriter(trace)); + if (pane != null) + trace.append( + fx( + () -> + pane.lookupAll(".label").stream() + .filter(Label.class::isInstance) + .map(n -> Objects.toString(((Label) n).getText(), "")) + .filter(s -> !s.isEmpty()) + .toList() + .toString())); + Files.writeString(output.resolve("FAILURE.txt"), trace.toString()); + } catch (Exception failure) { + failure.printStackTrace(); + } + } + }); + } + + void step(String message) throws Exception { + Files.writeString( + output.resolve("steps.txt"), + message + "\n", + StandardOpenOption.CREATE, + StandardOpenOption.APPEND); + } + + String source() throws Exception { + return edt(() -> FileDocumentManager.getInstance().getDocument(file).getText()); + } + + void controls(boolean expanded) throws Exception { + fx( + () -> { + var panel = + (TitledPane) + pane.lookupAll(".titled-pane").stream() + .filter(n -> n instanceof TitledPane t && t.getText().equals("Form controls")) + .findFirst() + .orElseThrow(); + panel.setAnimated(false); + panel.setExpanded(expanded); + pane.applyCss(); + pane.layout(); + return null; + }); + } + + void choose(String selector, String text) throws Exception { + fx( + () -> { + var combo = (ComboBox) pane.lookup("#" + selector); + for (int i = 0; i < combo.getItems().size(); i++) { + if (combo.getItems().get(i).toString().equals(text)) { + combo.getSelectionModel().select(i); + return null; + } + } + for (int i = 0; i < combo.getItems().size(); i++) { + String label = combo.getItems().get(i).toString(); + if (label.equals(text) || label.contains(text)) { + combo.getSelectionModel().select(i); + return null; + } + } + throw new AssertionError(selector + " missing " + text + " in " + combo.getItems()); + }); + } + + void edited(String before, String expected) throws Exception { + await( + () -> { + String now = source(); + String error = + fx( + () -> { + var label = (Label) pane.lookup("#form-message"); + return label == null ? "" : label.getText(); + }); + if (!error.isEmpty()) throw new AssertionError(error); + return !before.equals(now) + && now.contains(expected) + && fx( + () -> + ((TextArea) pane.lookup("#fxml-source")) == null + || ((TextArea) pane.lookup("#fxml-source")).getText().equals(now)); + }); + // Both the native document and visual selection are refreshed asynchronously. + fx(pane::flush).toCompletableFuture().get(10, java.util.concurrent.TimeUnit.SECONDS); + } + + void set(String name, String value, String expected) throws Exception { + choose("form-property", name); + fx( + () -> { + ((TextArea) pane.lookup("#form-value")).setText(value); + return null; + }); + String before = source(); + click(pane, "Set property"); + edited(before, expected); + } + + void awaitTarget(String name) throws Exception { + await( + () -> { + var error = output.resolve("target-error.txt"); + if (Files.exists(error)) throw new AssertionError(Files.readString(error)); + return Files.exists(output.resolve(name)); + }); + } + + abstract void verify(Project project) throws Exception; +} diff --git a/integration-tests/idea/SavedDocumentTargetProbe.java b/integration-tests/idea/SavedDocumentTargetProbe.java new file mode 100644 index 0000000..abf46ed --- /dev/null +++ b/integration-tests/idea/SavedDocumentTargetProbe.java @@ -0,0 +1,224 @@ +package qualification; + +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import javafx.application.Platform; +import javafx.scene.Parent; +import javafx.scene.control.*; +import javafx.scene.input.*; +import javafx.stage.*; +import org.w3c.dom.Document; + +/** Observes the target JVM launched by the IDE. No application or WebKit classes enter the IDE. */ +public final class SavedDocumentTargetProbe { + public static void premain(String directory) { + if (System.getProperty("sun.java.command", "") + .startsWith("de.neitzel.fxdesigner.target.WorkerMain ")) + Thread.ofPlatform().daemon().start(() -> new Probe().run(Path.of(directory))); + } + + private static final class Probe { + private Path evidence; + private Parent root; + private Object viewer, engine; + private TextField fixed, dynamic; + + private T fx(Callable action) throws Exception { + var task = new FutureTask<>(action); + Platform.runLater(task); + return task.get(10, TimeUnit.SECONDS); + } + + private void await(Callable check) throws Exception { + long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(30); + while (System.nanoTime() < end) { + if (fx(check)) return; + Thread.sleep(80); + } + throw new AssertionError("Timed out waiting for " + check); + } + + private void run(Path directory) { + evidence = directory; + try { + // The same agent is present in discovery and off-screen render workers. + while (true) { + try { + if (fx( + () -> { + var stage = + Window.getWindows().stream() + .filter(Stage.class::isInstance) + .map(Stage.class::cast) + .filter( + w -> + w.isShowing() + && w.getOpacity() > 0 + && w.getTitle() != null + && w.getTitle().startsWith("Neitzel preview")) + .findFirst(); + if (stage.isEmpty()) return false; + stage.get().setWidth(800); + stage.get().setHeight(580); + stage.get().requestFocus(); + root = stage.get().getScene().getRoot(); + viewer = root.lookup("#article"); + return viewer != null; + })) break; + } catch (IllegalStateException starting) { + } + Thread.sleep(120); + } + fx( + () -> { + var browser = root.lookup("WebView"); + engine = browser.getClass().getMethod("getEngine").invoke(browser); + fixed = (TextField) root.lookup("#fixed"); + dynamic = (TextField) root.lookup("#dynamic"); + var media = (Button) root.lookup(".html-viewer-media-load"); + require( + media.getText().equals("Belegbilder laden") + && media.getTooltip().getText().equals("Keine externen Belegbilder") + && media.isDisabled(), + "edited offline media labels"); + require( + "Belegbilder erneut laden".equals(call("getMediaReloadText")) + && "Bilder dieses Belegs laden".equals(call("getMediaTooltipText")), + "remaining media labels"); + require(!Boolean.TRUE.equals(call("isExternalImagesAllowed")), "offline viewer"); + return null; + }); + body("Rechnung RE-042"); + popup(fixed, "Pr", List.of("Prüfung", "Privat")); + popup(dynamic, "Re", List.of("Rechnung", "Reise")); + fx( + () -> { + ((Button) root.lookup("#next")).fire(); + return null; + }); + body("Lieferschein LS-018"); + require( + fx(() -> suggestions(dynamic).equals(List.of("Lieferung", "Lieferschein"))), + "replacement removes old document tags"); + popup(dynamic, "Li", List.of("Lieferung", "Lieferschein")); + popup(fixed, "Pr", List.of("Prüfung", "Privat")); + fx( + () -> { + ((TextArea) root.lookup("#source")) + .setText("

Geänderter Beleg

"); + return null; + }); + body("Geänderter Beleg"); + fx( + () -> { + viewer + .getClass() + .getMethod("load", Path.class) + .invoke(viewer, directory.resolve("missing-preview.html")); + return null; + }); + await(() -> !Boolean.TRUE.equals(call("isLoading")) && call("getError") != null); + fx( + () -> { + ((Button) root.lookup("#next")).fire(); + return null; + }); + body("Rechnung RE-042"); + Files.writeString( + directory.resolve("saved-document-result"), + "Rechnung RE-042 → Lieferschein LS-018 → Geänderter Beleg; load error and recovery;" + + " popup Pr: Prüfung, Privat; Re: Rechnung, Reise; Li: Lieferung, Lieferschein." + + " PID " + + ProcessHandle.current().pid()); + } catch (Throwable ex) { + try { + var trace = new java.io.StringWriter(); + ex.printStackTrace(new java.io.PrintWriter(trace)); + Files.writeString(directory.resolve("target-error.txt"), trace.toString()); + } catch (Exception ignored) { + ex.printStackTrace(); + } + } + } + + private Object call(String method) throws Exception { + return viewer.getClass().getMethod(method).invoke(viewer); + } + + private void body(String text) throws Exception { + await( + () -> { + if (call("getError") != null) throw new AssertionError(call("getError")); + var doc = (Document) engine.getClass().getMethod("getDocument").invoke(engine); + return !Boolean.TRUE.equals(call("isLoading")) + && doc != null + && doc.getDocumentElement().getTextContent().contains(text); + }); + } + + private List suggestions(TextField field) throws Exception { + return (List) field.getClass().getMethod("getSuggestions").invoke(field); + } + + private void popup(TextField field, String prefix, List expected) throws Exception { + await( + () -> { + if (field.isFocused()) return true; + var stage = (Stage) root.getScene().getWindow(); + stage.toFront(); + stage.requestFocus(); + field.requestFocus(); + return field.isFocused(); + }); + fx( + () -> { + field.setText(""); + field.setText(prefix); + return null; + }); + await( + () -> { + for (var window : Window.getWindows()) { + if (!(window instanceof Popup) + || !window.isShowing() + || !(window.getScene().lookup(".list-view") instanceof ListView list) + || !list.getItems().equals(expected)) continue; + var image = window.getScene().snapshot(null); + int w = (int) image.getWidth(), h = (int) image.getHeight(); + var png = + new java.awt.image.BufferedImage( + w, h, java.awt.image.BufferedImage.TYPE_INT_ARGB); + var pixels = new int[w * h]; + image + .getPixelReader() + .getPixels( + 0, + 0, + w, + h, + javafx.scene.image.PixelFormat.getIntArgbInstance(), + pixels, + 0, + w); + png.setRGB(0, 0, w, h, pixels, 0, w); + javax.imageio.ImageIO.write( + png, "png", evidence.resolve("tags-" + prefix + ".png").toFile()); + return true; + } + return false; + }); + fx( + () -> { + field.fireEvent( + new KeyEvent( + KeyEvent.KEY_PRESSED, "", "", KeyCode.ESCAPE, false, false, false, false)); + return null; + }); + } + + private static void require(boolean condition, String label) { + if (!condition) throw new AssertionError(label); + } + } +} diff --git a/integration-tests/idea/SavedDocumentWorkflowProbe.java b/integration-tests/idea/SavedDocumentWorkflowProbe.java new file mode 100644 index 0000000..6096f1f --- /dev/null +++ b/integration-tests/idea/SavedDocumentWorkflowProbe.java @@ -0,0 +1,114 @@ +package qualification; + +import static qualification.WorkflowProbe.*; + +import com.intellij.openapi.fileEditor.FileEditorManager; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.LocalFileSystem; +import java.nio.file.*; +import javafx.embed.swing.SwingFXUtils; +import javafx.scene.control.*; +import javafx.scene.image.ImageView; +import javax.imageio.ImageIO; + +/** Configures the Archiver HTML viewer and both tag fields in the registered form inspector. */ +public final class SavedDocumentWorkflowProbe extends FormWorkflowProbe { + @Override + void verify(Project project) throws Exception { + var path = + Path.of( + project.getBasePath(), + "src/designer/resources/de/neitzel/archiver/preview/SavedDocument.fxml"); + file = edt(() -> LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path)); + pane = openDesigner(project, file); + controls(true); + choose("form-control", "HtmlViewer #article"); + set("mediaLoadText", "Belegbilder laden", "mediaLoadText=\"Belegbilder laden\""); + set( + "mediaReloadText", + "Belegbilder erneut laden", + "mediaReloadText=\"Belegbilder erneut laden\""); + set( + "mediaTooltipText", + "Bilder dieses Belegs laden", + "mediaTooltipText=\"Bilder dieses Belegs laden\""); + set( + "noExternalMediaText", + "Keine externen Belegbilder", + "noExternalMediaText=\"Keine externen Belegbilder\""); + set("mediaButtonVisible", "false", "mediaButtonVisible=\"false\""); + click(pane, "Undo"); + await(() -> source().contains("mediaButtonVisible=\"true\"")); + choose("form-control", "AutoCompleteTextField #fixed"); + set("suggestions", "Prüfung\nPrivat", "fx:value=\"Prüfung\""); + click(pane, "Bind property"); + if (!fx( + () -> + ((Label) pane.lookup("#form-message")) + .getText() + .contains("no writable JavaFX property"))) + throw new AssertionError("Static collection was offered as a direct binding target"); + var current = source(); + click(pane, "Save"); + await(() -> Files.readString(path).equals(current)); + edt( + () -> { + FileEditorManager.getInstance(project).closeFile(file); + return null; + }); + pane = openDesigner(project, file); + if (!source().equals(current)) throw new AssertionError("Reopen lost document settings"); + step("Edited four media labels, visibility and fixed suggestions; saved and reopened"); + click(pane, "Form preview"); + click(pane, "Build and Refresh"); + await(() -> fx(() -> ((ComboBox) pane.lookup("#preview-example")).getItems().size() == 2)); + choose("preview-example", "saved-invoice"); + frame("invoice", "Rechnung", 0xff294973); + click(pane, "Interactive preview"); + awaitTarget("saved-document-result"); + click(pane, "Stop preview"); + choose("preview-example", "saved-delivery"); + frame("delivery", "Lieferschein", 0xff38643e); + fx( + () -> { + ImageIO.write( + SwingFXUtils.fromFXImage(pane.snapshot(null, null), null), + "png", + output.resolve("intellij.png").toFile()); + return null; + }); + Files.writeString( + output.resolve("SUCCESS.txt"), + "PASS registered IntelliJ Archiver saved documents: inspector configuration, two WebView" + + " frames, document replacement, error recovery and live suggestion popups.\n"); + } + + private void frame(String id, String title, int accent) throws Exception { + await( + () -> + fx( + () -> { + var image = ((ImageView) pane.lookup("#full-preview-image")).getImage(); + var state = ((Label) pane.lookup("#preview-state")).getText(); + if (state.startsWith("Preview failed") + || state.startsWith("Preview unavailable") + || state.startsWith("Preview blocked")) throw new AssertionError(state); + if (image == null || !state.contains(title)) return false; + ImageIO.write( + SwingFXUtils.fromFXImage(image, null), + "png", + output.resolve(id + ".png").toFile()); + int ink = 0; + for (int y = 0; y < (int) image.getHeight(); y++) + for (int x = 0; x < (int) image.getWidth(); x++) + if (image.getPixelReader().getArgb(x, y) == accent) ink++; + if (ink < 1800 + || image.getPixelReader().getArgb((int) image.getWidth() - 32, 104) + != 0xffffffff) + throw new AssertionError( + title + " missing HTML accent in the embedded frame: " + ink); + return true; + })); + step("Embedded " + title + " rendered its document-specific HTML colour"); + } +} diff --git a/scripts/check-ide-host.py b/scripts/check-ide-host.py index 2df3466..2e91692 100644 --- a/scripts/check-ide-host.py +++ b/scripts/check-ide-host.py @@ -23,13 +23,13 @@ p.add_argument("--idea-home", type=Path, required=True) p.add_argument("--mode", choices=["all", "classpath", "modulepath"], default="all") p.add_argument("--repeat", type=int, default=1, help="Consecutive independent runs per mode") p.add_argument("--archiver", type=Path, help="Qualify ArchiveWindow.fxml in a disposable project copy") -p.add_argument("--connection-form", action="store_true", help="Qualify the Archiver connection form") -p.add_argument("--grid-docking", type=Path, metavar="REFERENCE_FXML", help="Qualify the Archiver grid, dock layout and the supplied reference workspace") +forms = p.add_mutually_exclusive_group() +forms.add_argument("--connection-form", action="store_true", help="Qualify the Archiver connection form") +forms.add_argument("--grid-docking", type=Path, metavar="REFERENCE_FXML", help="Qualify the Archiver grid, dock layout and the supplied reference workspace") +forms.add_argument("--saved-document", action="store_true", help="Open the Archiver saved HTML and tag example") args = p.parse_args() -if args.grid_docking and (not args.archiver or args.connection_form): - p.error("--grid-docking requires --archiver and a separate run from --connection-form") -if args.connection_form and not args.archiver: - p.error("--connection-form requires --archiver") +if (args.connection_form or args.grid_docking or args.saved_document) and not args.archiver: + p.error("Selecting an Archiver view requires --archiver") if args.repeat < 1: p.error("--repeat must be positive") output = ROOT / "target/ide-workflow" @@ -40,7 +40,7 @@ modes = ("classpath",) if args.archiver else (("classpath", "modulepath") if arg for run_number, mode in ((n, mode) for n in range(1, args.repeat + 1) for mode in modes): crashes = NativeCrashGuard(ROOT) launch = subprocess.run([sys.executable, ROOT / "scripts/run-fixture-host.py", "intellij", - "--check", *(["--grid-docking", str(args.grid_docking.resolve())] if args.grid_docking else []), *(["--connection-form"] if args.connection_form else []), *(["--archiver", str(args.archiver.resolve())] if args.archiver else []), "--mode", mode, "--java-home", args.java_home, + "--check", *(["--saved-document"] if args.saved_document else []), *(["--grid-docking", str(args.grid_docking.resolve())] if args.grid_docking else []), *(["--connection-form"] if args.connection_form else []), *(["--archiver", str(args.archiver.resolve())] if args.archiver else []), "--mode", mode, "--java-home", args.java_home, "--target-java-home", args.target_java_home, "--idea-home", args.idea_home], cwd=ROOT, text=True, capture_output=True, timeout=60) if launch.returncode: @@ -84,7 +84,7 @@ for run_number, mode in ((n, mode) for n in range(1, args.repeat + 1) for mode i shutil.copyfile(base / "intellij.png", output / (mode + ".png")) (evidence / "proof.json").write_text(json.dumps(proof, indent=2) + "\n") finally: - for name in ("SUCCESS.txt", "FAILURE.txt", "ui-state.txt", "launcher.log", "steps.txt", "target-error.txt", "preview-restored.png", "imap.png", "jmap.png", "folder.png", "right.png", "bottom.png", "result-folder", "result-right", "result-bottom", "intellij.png"): + for name in ("SUCCESS.txt", "FAILURE.txt", "ui-state.txt", "launcher.log", "steps.txt", "target-error.txt", "preview-restored.png", "imap.png", "jmap.png", "invoice.png", "delivery.png", "saved-document-result", "tags-Pr.png", "tags-Re.png", "tags-Li.png", "folder.png", "right.png", "bottom.png", "result-folder", "result-right", "result-bottom", "intellij.png"): if (base / name).exists(): shutil.copyfile(base / name, evidence / name) workers = descendant_workers(pid) diff --git a/scripts/run-fixture-host.py b/scripts/run-fixture-host.py index b22f5c4..d2654e6 100644 --- a/scripts/run-fixture-host.py +++ b/scripts/run-fixture-host.py @@ -19,13 +19,13 @@ 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("--archiver", type=Path, help="Use a disposable copy of the Archiver project") -p.add_argument("--connection-form", action="store_true", help="Open and qualify the Archiver connection form") -p.add_argument("--grid-docking", type=Path, metavar="REFERENCE_FXML", help="Qualify the Archiver grid, dock layout and the supplied reference workspace") +forms = p.add_mutually_exclusive_group() +forms.add_argument("--connection-form", action="store_true", help="Open and qualify the Archiver connection form") +forms.add_argument("--grid-docking", type=Path, metavar="REFERENCE_FXML", help="Qualify the Archiver grid, dock layout and the supplied reference workspace") +forms.add_argument("--saved-document", action="store_true", help="Open the Archiver saved HTML and tag example") args = p.parse_args() -if args.grid_docking and (not args.archiver or args.connection_form): - p.error("--grid-docking requires --archiver and a separate run from --connection-form") -if args.connection_form and not args.archiver: - p.error("--connection-form requires --archiver") +if (args.connection_form or args.grid_docking or args.saved_document) and not args.archiver: + p.error("Selecting an Archiver view requires --archiver") base = Path(tempfile.mkdtemp(prefix="neitzel-designer-host-")).resolve() project = base / "project" if args.archiver: @@ -39,6 +39,8 @@ if args.archiver: view = "FolderTab" shutil.copyfile(args.grid_docking, project / "src/main/resources/ReferenceWorkspace.fxml") file = project / f"src/main/resources/de/neitzel/archiver/ui/{view}.fxml" + if args.saved_document: + file = project / "src/designer/resources/de/neitzel/archiver/preview/SavedDocument.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) @@ -64,17 +66,20 @@ else: shutil.copyfile(ROOT / "designer-kit-ui/target/designer-kit-ui-0.1.0-SNAPSHOT-tests.jar", checks) jars = [*(args.idea_home / "lib").glob("*.jar"), *(base / "plugins").rglob("*.jar"), *(args.idea_home / "plugins/platform-problemView-plugin").rglob("*.jar")] sources = ROOT / "integration-tests/idea" - probe = "ArchiveWorkflowProbe" if args.archiver else "WorkflowProbe" + suite = "Archive" if args.connection_form: - probe = "ConnectionWorkflowProbe" - if args.grid_docking: - probe = "GridDockWorkflowProbe" + suite = "Connection" + elif args.grid_docking: + suite = "GridDock" + elif args.saved_document: + suite = "SavedDocument" + probe = f"{suite}WorkflowProbe" if args.archiver else "WorkflowProbe" files = [sources / "WorkflowProbe.java"] + if args.connection_form or args.saved_document: + files.append(sources / "FormWorkflowProbe.java") if args.archiver: files.append(sources / f"{probe}.java") - target_probe = "ConnectionTargetProbe" if args.connection_form else "ArchiveTargetProbe" - if args.grid_docking: - target_probe = "GridDockTargetProbe" + target_probe = f"{suite}TargetProbe" agent_classes = base / "agent-classes" agent_classes.mkdir() subprocess.run([args.java_home / "bin/javac", "-cp", os.pathsep.join(map(str,jars)), "-d", agent_classes,