package de.neitzel.fxdesigner.kit; import com.oracle.javafx.scenebuilder.kit.editor.panel.content.ContentPanelController; import com.oracle.javafx.scenebuilder.kit.editor.panel.hierarchy.HierarchyPanelController; import com.oracle.javafx.scenebuilder.kit.editor.panel.inspector.InspectorPanelController; import com.oracle.javafx.scenebuilder.kit.fxom.*; import de.neitzel.fxdesigner.build.BuildRefresh; import de.neitzel.fxdesigner.contracts.*; import de.neitzel.fxdesigner.host.*; import de.neitzel.fxdesigner.workflow.*; import java.nio.file.*; import java.util.*; import java.util.concurrent.*; import javafx.animation.*; import javafx.application.Platform; import javafx.scene.control.*; import javafx.scene.image.*; import javafx.scene.layout.*; import javafx.util.Duration; /** One shared Kit UI. Both hosts own the authoritative DocumentSession and native history. */ public final class DesignerPane extends BorderPane implements AutoCloseable { private final HostServices host; private final HostLaunch launch; private final Path file; private final KitView kit; private final Label status = new Label("Opening document"); private final DiagnosticTextArea source = new DiagnosticTextArea(); private final TextArea output = new TextArea(); private final ComboBox examples = new ComboBox<>(); private final SplitPane design; private final ContentPanelController content; public ContentPanelController content() { return content; } private GridDockEditor gridDockEditor; private FormEditor formEditor; private final ImageView wholeImage = new ImageView(); private final Spinner previewWidth = new Spinner<>(120, 1600, 760, 40); private final Spinner previewHeight = new Spinner<>(100, 1200, 520, 40); private final Label previewState = new Label("Build and Refresh, then select an example."); private boolean showWhole; private final VBox componentInspector = new VBox(4); private void componentSelection() { componentInspector.getChildren().clear(); if (projection == null) return; var hit = kit.editor().getSelection().getHitItem(); if (hit == null) return; String id = hit.getFxId(); if (formEditor != null) formEditor.selectIndex(projection.sourceIndex(id)); if (bindingEditor != null) bindingEditor.selectControl(id); if (computedEditor != null) computedEditor.selectControl(id); if (repeatEditor != null) repeatEditor.selectControl(id); if (commandEditor != null) commandEditor.selectControl(id); if (tableEditor != null) tableEditor.selectControl(id); if (referenceEditor != null) referenceEditor.selectIndex(projection.sourceIndex(id)); if (id == null || !projection.components().containsKey(id)) return; componentInspector.getChildren().add(new Label(projection.components().get(id) + " · " + id)); componentInspector .getChildren() .add(new Label("Declared FXML properties (validated by target runtime)")); projection .componentAttributes(id) .forEach( (name, value) -> { var field = new TextField(value); field.setId("component-property-" + name); field.setOnAction( e -> { try { submit( projection.componentAttribute(id, name, field.getText()), "Edit Component " + name); } catch (Exception error) { report(error); } }); componentInspector.getChildren().add(new HBox(4, new Label(name), field)); }); } private final Timeline poll; private final PauseTransition typing = new PauseTransition(Duration.millis(250)), resize = new PauseTransition(Duration.millis(350)); private String submittedSource; private List pendingVisual; private String pendingBase; private static String apply(String text, List edits) { return new EditBatch(0, "projection", edits) .applyTo( new DocumentSnapshot(java.net.URI.create("file:/projection"), 0, text, true, false)); } private static List difference(String before, String after) { int start = 0, end = before.length(), last = after.length(); while (start < end && start < last && before.charAt(start) == after.charAt(start)) start++; while (end > start && last > start && before.charAt(end - 1) == after.charAt(last - 1)) { end--; last--; } return start == end && start == last ? List.of() : List.of(new EditBatch.Replacement(start, end, after.substring(start, last))); } private static int mapped(int offset, List edits) { int delta = 0; var sorted = new ArrayList<>(edits); sorted.sort(Comparator.comparingInt(EditBatch.Replacement::start)); for (var edit : sorted) { if (offset < edit.start()) break; if (offset <= edit.end()) return edit.start() + delta + Math.min(offset - edit.start(), edit.text().length()); delta += edit.text().length() - (edit.end() - edit.start()); } return offset + delta; } private DocumentSession document; private DocumentSnapshot draft; private FxmlProjection projection; private final Path reactorRoot; private DesignerWorkflow workflow; private DesignerWorkflow interactiveWorkflow; private DesignerWorkflow bindingWorkflow; private ViewGenerationPane viewGeneration; private BindingBrowser bindingBrowser; private BindingEditor bindingEditor, computedEditor, repeatEditor, commandEditor; private TableEditor tableEditor; private ReferenceEditor referenceEditor; private DiagnosticsPane diagnosticsPane; private final String diagnosticsOwner = java.util.UUID.randomUUID().toString(); private long diagnosticsRevision = -1; private long diagnosticGeneration; private SplitPane sourceSplit; private Integer pendingSourceOffset; private String pendingReferenceValidation; private String validatedSource, validatingSource; private boolean validationPreview; private java.util.List bindingProblems = java.util.List.of(); private Tab directBindingTab; private long bindingRequest; private boolean interactiveRequested, interactiveRestart; private long interactiveRequest; private final java.util.concurrent.atomic.AtomicLong draftChanges = new java.util.concurrent.atomic.AtomicLong(); private final Label interactiveStatus = new Label(); private AutoCloseable saves; public long interactivePid() { return interactiveWorkflow.renderingPid(); } private int layoutPasses; private boolean loading, closed, pending, last, canvasCommitQueued; private long canvasGeneration; private final java.util.concurrent.atomic.AtomicLong renderSequence = new java.util.concurrent.atomic.AtomicLong(); private AutoCloseable changes; private final Map images = new HashMap<>(); private BuildRefresh.Run buildRun; public DesignerPane(HostServices host, HostLaunch launch, Path file) throws Exception { this.host = host; this.launch = launch; this.file = file; Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); kit = new KitView(host); content = new ContentPanelController(kit.editor()); design = new SplitPane( new HierarchyPanelController(kit.editor()).getPanelRoot(), content.getPanelRoot(), new InspectorPanelController(kit.editor()).getPanelRoot()); design.setDividerPositions(.18, .72); kit.editor().getSelection().revisionProperty().addListener((o, a, b) -> componentSelection()); workflow = new DesignerWorkflow( host, launch.configuration(), launch.context(), launch.maven(), launch.tools(), this::log); interactiveWorkflow = new DesignerWorkflow( host, launch.configuration(), launch.context(), launch.maven(), launch.tools(), this::log); bindingWorkflow = new DesignerWorkflow( host, launch.configuration(), launch.context(), launch.maven(), launch.tools(), this::log); bindingEditor = editor(BindingDocument.Kind.DIRECT); computedEditor = editor(BindingDocument.Kind.COMPUTED); repeatEditor = editor(BindingDocument.Kind.REPEAT); commandEditor = editor(BindingDocument.Kind.COMMAND); tableEditor = new TableEditor( this::editTable, this::navigateComponent, values -> validateBindings(values, false)); referenceEditor = new ReferenceEditor(file.toUri().toString(), this::editStructure); diagnosticsPane = new DiagnosticsPane(() -> validateBindings(null, false), this::navigateDiagnostic); bindingBrowser = new BindingBrowser( this::discoverBindings, values -> { bindingEditor.newBinding(values); directBindingTab.getTabPane().getSelectionModel().select(directBindingTab); }); interactiveWorkflow.onInteractiveClosed( () -> fx( () -> { interactiveRequested = false; interactiveRequest++; interactiveStatus.setText("Interactive preview closed"); })); Path reactor = launch.configuration().getParent().toRealPath(); reactorRoot = reactor; changes = host.documents() .onChange( uri -> { if (Path.of(uri).startsWith(reactor)) { draftChanges.incrementAndGet(); renderSequence.incrementAndGet(); workflow.cancel(); fx( () -> { invalidateBindings("Document changed; discover bindings again."); if (interactiveRequested && affectsInteractive(uri)) interactiveStatus.setText( "Interactive preview uses earlier drafts; rerun or save to" + " restart"); }); fx( () -> { layoutPasses = 0; resize.playFromStart(); }); } }); saves = host.documents() .onSave( uri -> { if (Path.of(uri).startsWith(reactorRoot)) fx( () -> { if (interactiveRequested && affectsInteractive(uri)) { interactiveRestart = true; interactiveRequest++; interactiveWorkflow.cancel(); } resize.playFromStart(); }); }); var bar = new ToolBar( button("Build and Refresh", () -> build(Map.of())), button( "Cancel", () -> { if (buildRun != null) buildRun.cancel(); workflow.cancel(); renderSequence.incrementAndGet(); }), examples, button( "Render drafts", () -> { layoutPasses = 0; render(); }), button( "Interactive preview", () -> { interactiveRequested = true; interactiveRequest++; interactiveRestart = true; interactiveWorkflow.cancel(); render(); }), button( "Stop preview", () -> { interactiveRequested = false; interactiveRequest++; interactiveRestart = false; interactiveStatus.setText(""); interactiveWorkflow.cancel(); }), button("Preview last successful", () -> discover(true)), button( "Save", () -> withDraft(() -> document.save(draft.revision()).whenComplete(this::updated))), button("Undo", () -> history(false)), button("Redo", () -> history(true)), button("Open Component", this::openComponent), button("Open Row Component", this::openRowComponent), button( "Open Java", () -> { var selected = kit.editor().getSelection().getHitItem(); if (selected != null && projection != null && projection.navigationTypes().containsKey(selected.getFxId())) workflow .javaSource(projection.navigationTypes().get(selected.getFxId())) .thenCompose( uri -> host.navigation().open(new HostServices.Location(uri, 0))) .exceptionally( error -> { fx(() -> report(error)); return null; }); })); examples.setConverter( new javafx.util.StringConverter<>() { public String toString(DesignerWorkflow.Example value) { return value == null ? "Select example" : value.label(); } public DesignerWorkflow.Example fromString(String value) { return null; } }); examples.setId("preview-example"); examples .valueProperty() .addListener( (o, before, after) -> { renderSequence.incrementAndGet(); clearFormPreview( after == null ? "Build and Refresh, then select an example." : "Rendering " + after.label() + "…"); if (interactiveRequested) { interactiveRequest++; interactiveWorkflow.cancel(); interactiveRestart = true; } resize.playFromStart(); }); previewWidth.setId("preview-width"); previewHeight.setId("preview-height"); previewState.setId("preview-state"); wholeImage.setId("full-preview-image"); wholeImage.setPreserveRatio(true); var picture = new ScrollPane(wholeImage); picture.setMinSize(0, 0); picture .viewportBoundsProperty() .addListener( (o, a, bounds) -> { wholeImage.setFitWidth(Math.max(1, bounds.getWidth())); wholeImage.setFitHeight(Math.max(1, bounds.getHeight())); }); VBox.setVgrow(picture, Priority.ALWAYS); var fullPreview = new VBox( 4, new FlowPane( 5, 4, new Label("Width"), previewWidth, new Label("Height"), previewHeight), previewState, picture); previewWidth.valueProperty().addListener((o, a, b) -> previewSizeChanged()); previewHeight.valueProperty().addListener((o, a, b) -> previewSizeChanged()); var split = new SplitPane(source, design); split .getItems() .addListener( (javafx.collections.ListChangeListener) change -> { showWhole = split.getItems().contains(fullPreview); }); sourceSplit = split; split.setDividerPositions(.3); var modes = new ToolBar( button("Source", () -> split.getItems().setAll(source)), button("Design", () -> split.getItems().setAll(design)), button( "Form preview", () -> { split.getItems().setAll(design, fullPreview); split.setDividerPositions(.48); render(); }), button( "Split", () -> { split.getItems().setAll(source, design); split.setDividerPositions(.3); })); var center = new BorderPane(split); center.setTop(modes); var properties = new ScrollPane(componentInspector); properties.setFitToWidth(true); properties.setPrefViewportHeight(100); var discoveryTab = new Tab("Discover targets", bindingBrowser); discoveryTab.setClosable(false); directBindingTab = new Tab("Direct bindings", bindingEditor); directBindingTab.setClosable(false); var computedTab = new Tab("Computed bindings", computedEditor); computedTab.setClosable(false); var commandTab = new Tab("Command bindings", commandEditor); commandTab.setClosable(false); var repeatTab = new Tab("Repeat bindings", repeatEditor); repeatTab.setClosable(false); var tableTab = new Tab("Table / Columns", tableEditor); tableTab.setClosable(false); gridDockEditor = new GridDockEditor( this::editForm, values -> { directBindingTab.getTabPane().getSelectionModel().select(directBindingTab); bindingEditor.editProperty(values); }); var gridDockTab = new Tab("DataGrid / Docking", gridDockEditor); gridDockTab.setClosable(false); var problemsTab = new Tab("Problems", diagnosticsPane); problemsTab.setClosable(false); var structureTab = new Tab("Structure", referenceEditor); structureTab.setClosable(false); viewGeneration = new ViewGenerationPane(host, launch, file); var generationTab = new Tab("Generate View", new ScrollPane(viewGeneration)); generationTab.setClosable(false); var bindings = new TitledPane( "Bindings", new TabPane( directBindingTab, computedTab, commandTab, repeatTab, tableTab, gridDockTab, structureTab, problemsTab, discoveryTab, generationTab)); bindings.setExpanded(false); formEditor = new FormEditor( this::editForm, index -> { if (loading || projection == null || kit.editor().getFxomDocument() == null) return; String id = projection.canvasId(index); if (id == null) return; var object = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id); if (object != null && kit.editor().getSelection().getHitItem() != object) kit.editor().getSelection().select(object); }, values -> { bindings.setExpanded(true); directBindingTab.getTabPane().getSelectionModel().select(directBindingTab); bindingEditor.editProperty(values); }); var formPane = new TitledPane("Form controls", formEditor); formPane.setExpanded(false); formPane .expandedProperty() .addListener( (o, a, b) -> { if (b) bindings.setExpanded(false); }); bindings .expandedProperty() .addListener( (o, a, b) -> { if (b) formPane.setExpanded(false); }); center.setBottom(new VBox(properties, formPane, bindings)); output.setEditable(false); output.setPrefRowCount(5); Path origin = file.resolveSibling(file.getFileName() + ".origin"); setTop( java.nio.file.Files.isRegularFile(origin) ? new VBox( new Label("Read-only origin: " + java.nio.file.Files.readString(origin)), bar) : bar); setCenter(center); setBottom(new VBox(status, interactiveStatus, output)); source .textProperty() .addListener( (o, a, b) -> { if (!loading) { flushCanvas(); if (pending && submittedSource == null) submittedSource = pendingBase; commitSource(); workflow.cancel(); renderSequence.incrementAndGet(); } }); typing.setOnFinished(e -> commitSource()); resize.setOnFinished(e -> render()); poll = new Timeline( new KeyFrame( Duration.millis(400), e -> { if (document != null && !pending && !typing.getStatus().equals(Animation.Status.RUNNING)) document .snapshot() .whenComplete( (d, error) -> fx( () -> { if (error != null) report(error); else if (!pending && (draft == null || d.revision() > draft.revision())) load(d); })); })); poll.setCycleCount(Animation.INDEFINITE); host.documents() .open(file.toUri()) .whenComplete( (d, error) -> fx( () -> { if (error != null) { report(error); return; } if (closed) { d.close(); return; } document = d; d.snapshot().whenComplete(this::updated); poll.play(); })); } private Button button(String text, Runnable action) { var b = new Button(text); b.setOnAction( e -> { try { action.run(); } catch (Throwable error) { report(error); } }); return b; } private void fx(Runnable action) { Platform.runLater( () -> { if (!closed) action.run(); }); } private void log(String text) { fx( () -> { output.appendText(text + "\n"); if (output.getLength() > 60000) output.deleteText(0, output.getLength() - 50000); }); } private void report(Throwable error) { host.diagnostics() .report( new HostServices.Diagnostic( "Designer", HostServices.Severity.ERROR, String.valueOf(error), Optional.empty())); if (draft != null && diagnosticsPane != null) validationUnavailable(error); if (showWhole) clearFormPreview( "Preview unavailable · " + error.getMessage() + " · use Build and Refresh after correcting the problem."); status.setText("Designer: " + error.getMessage()); log(error.toString()); } private void updated(DocumentSnapshot value, Throwable error) { fx( () -> { pending = false; if (error != null) { submittedSource = null; report(error); return; } if (submittedSource != null && !source.getText().equals(submittedSource)) { // Source typing can arrive before an asynchronous visual command completes. // Rebase disjoint visual ranges; an overlapping later source edit wins explicitly // in the next host command, whose Undo still restores the visual command. if (submittedSource.equals(pendingBase) && pendingVisual != null) { var typed = difference(pendingBase, source.getText()); var rebased = new ArrayList(); for (var visual : pendingVisual) { if (typed.stream() .noneMatch(t -> t.start() <= visual.end() && visual.start() <= t.end())) rebased.add( new EditBatch.Replacement( mapped(visual.start(), typed), mapped(visual.end(), typed), visual.text())); } int anchor = source.getAnchor(), caret = source.getCaretPosition(); loading = true; try { rebased.sort(Comparator.comparingInt(EditBatch.Replacement::start).reversed()); for (var edit : rebased) source.replaceText(edit.start(), edit.end(), edit.text()); source.selectRange(mapped(anchor, rebased), mapped(caret, rebased)); } finally { loading = false; } } draft = value; formEditor.load(value.text(), value.writable()); clearFormPreview("Draft changed · select an example to render the current revision."); publishDiagnostics("Source checked; target validation outdated", java.util.List.of()); bindingEditor.load(value.text(), value.writable()); computedEditor.load(value.text(), value.writable()); repeatEditor.load(value.text(), value.writable()); commandEditor.load(value.text(), value.writable()); tableEditor.load(value.text(), value.writable()); gridDockEditor.load(value.text(), value.writable()); referenceEditor.load(value.text(), value.writable()); submittedSource = null; commitSource(); return; } submittedSource = null; load(value); }); } private void load(DocumentSnapshot value) { if (closed) return; // A newer host revision can have identical text (edit/revert or native reload). // Its predecessor's validation reply will be rejected by revision, so it must // not leave an in-flight marker that absorbs every subsequent render request. if (draft == null || draft.revision() != value.revision() || !draft.text().equals(value.text())) invalidateBindings("Document synchronized; target validation outdated."); loading = true; layoutPasses = 0; canvasCommitQueued = false; canvasGeneration++; renderSequence.incrementAndGet(); workflow.cancel(); try { var hit = kit.editor().getSelection().getHitItem(); String selectedId = hit == null ? null : hit.getFxId(); draft = value; String requestedSelection = formEditor.load(value.text(), value.writable()); if (!requestedSelection.isEmpty()) selectedId = requestedSelection; clearFormPreview("Draft changed · select an example to render the current revision."); publishDiagnostics("Source checked; target validation outdated", java.util.List.of()); bindingEditor.load(value.text(), value.writable()); computedEditor.load(value.text(), value.writable()); repeatEditor.load(value.text(), value.writable()); commandEditor.load(value.text(), value.writable()); tableEditor.load(value.text(), value.writable()); gridDockEditor.load(value.text(), value.writable()); referenceEditor.load(value.text(), value.writable()); if (!source.getText().equals(value.text())) { int anchor = source.getAnchor(), caret = source.getCaretPosition(); var edits = pendingVisual != null && source.getText().equals(pendingBase) && apply(pendingBase, pendingVisual).equals(value.text()) ? pendingVisual : difference(source.getText(), value.text()); var descending = new ArrayList<>(edits); descending.sort(Comparator.comparingInt(EditBatch.Replacement::start).reversed()); for (var edit : descending) source.replaceText(edit.start(), edit.end(), edit.text()); source.selectRange(mapped(anchor, edits), mapped(caret, edits)); } pendingVisual = null; source.setEditable(value.writable()); // End an inspector editing session before replacing FXOM (also after native undo). if (getScene() != null && getScene().getFocusOwner() instanceof TextInputControl text && text != source) text.getParent().requestFocus(); projection = new FxmlProjection(value.text()); String projected = projection.project(); kit.editor().setFxmlTextAndLocation(projected, file.toUri().toURL()); design.setDisable(!value.writable()); componentInspector.setDisable(!value.writable()); kit.editor() .getFxomDocument() .sceneGraphRevisionProperty() .addListener((o, a, b) -> canvasChanged()); for (String id : projection.components().keySet()) { var region = proxy(id); if (region != null) { region.show( images.get(id), images.containsKey(id) ? "Previous preview" : "Render preview"); region .widthProperty() .addListener( (o, a, b) -> { if (!loading) resize.playFromStart(); }); region .heightProperty() .addListener( (o, a, b) -> { if (!loading) resize.playFromStart(); }); } } if (selectedId != null) { var selected = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(selectedId); if (selected != null) kit.editor().getSelection().select(selected); } componentSelection(); status.setText( "Context " + launch.context() + " · document revision " + value.revision() + (value.dirty() ? " · unsaved" : "")); } catch (Throwable error) { design.setDisable(true); componentInspector.setDisable(true); gridDockEditor.setDisable(true); projection = null; report(error); } finally { loading = false; // The change debounce may already have fired against the previous draft. // Render only after the authoritative revision and its projection agree. if ((projection != null || showWhole) && examples.getValue() != null) resize.playFromStart(); if (pendingSourceOffset != null) { int offset = pendingSourceOffset; pendingSourceOffset = null; showSource(offset); } if (value.text().equals(pendingReferenceValidation)) { pendingReferenceValidation = null; Platform.runLater(() -> validateBindings(null, false)); } } } private SnapshotRegion proxy(String id) { var object = new FXOMFxIdIndex(kit.editor().getFxomDocument()).lookup(id); return object instanceof FXOMInstance instance && instance.getSceneGraphObject() instanceof SnapshotRegion region ? region : null; } private void editForm(FormDocument.Edit edit) { flush() .whenComplete( (ok, error) -> fx( () -> { if (error != null) { report(error); return; } if (pending) { status.setText("Finishing the previous edit; repeat the form action."); return; } pending = true; pendingBase = edit.source(); pendingVisual = edit.changes(); document .snapshot() .thenCompose( latest -> document.apply( new EditBatch( latest.revision(), "Edit form", FormDocument.forCurrentText(edit, latest.text())))) .whenComplete(this::updated); })); } private void replace(String text, String name) { if (draft == null || pending) return; submit(difference(draft.text(), text), name); } private void submit(List edits, String name) { if (draft == null || pending || edits.isEmpty()) return; pending = true; pendingVisual = edits; pendingBase = draft.text(); document.apply(new EditBatch(draft.revision(), name, edits)).whenComplete(this::updated); } private void commitSource() { if (draft != null && !pending && !source.getText().equals(draft.text())) { submittedSource = source.getText(); replace(submittedSource, "Edit FXML source"); } } private void canvasChanged() { if (loading || pending || closed || canvasCommitQueued) return; // Kit's corner-resize gesture pushes one job per dimension on the same FX event turn. // Capture the completed gesture, not the intermediate width-only document. canvasCommitQueued = true; long generation = ++canvasGeneration; var projectedDocument = kit.editor().getFxomDocument(); var expectedDraft = draft; Platform.runLater( () -> { if (generation != canvasGeneration || closed) return; if (projectedDocument != kit.editor().getFxomDocument() || draft != expectedDraft) { canvasCommitQueued = false; return; } flushCanvas(); }); } private void flushCanvas() { if (!canvasCommitQueued) return; canvasCommitQueued = false; canvasGeneration++; if (loading || pending || closed) return; try { submit( projection.edits(kit.editor().getFxomDocument().getFxmlText(false)), "Component layout / property edit"); } catch (Throwable error) { report(error); load(draft); } } private void withDraft(Runnable action) { if (document == null) return; flushCanvas(); if (pending || !source.getText().equals(draft.text())) { commitSource(); status.setText("Finishing source edit; repeat the action when synchronized"); return; } action.run(); } private void history(boolean redo) { withDraft(() -> (redo ? document.redo() : document.undo()).whenComplete(this::updated)); } private void invalidateBindings(String message) { bindingRequest++; host.diagnostics().clear(diagnosticsOwner); if (diagnosticsPane != null) diagnosticsPane.show(java.util.List.of(), message); diagnosticsRevision = -1; diagnosticGeneration++; source.diagnostics("", java.util.List.of()); validatedSource = null; validatingSource = null; validationPreview = false; bindingWorkflow.cancel(); formEditor.eventHandlers(Optional.empty()); bindingBrowser.invalidate(message); repeatEditor.invalidateDiscovery(); commandEditor.invalidateDiscovery(); tableEditor.invalidateDiscovery(); } private void publishDiagnostics(String context, java.util.List target) { if (closed || draft == null) return; var all = new java.util.LinkedHashSet<>(FxmlDiagnostics.local(draft)); all.addAll(target); var diagnostics = java.util.List.copyOf(all); diagnosticsRevision = draft.revision(); String label = context + " · draft revision " + draft.revision(); var captured = draft; long generation = ++diagnosticGeneration; java.util.function.Consumer apply = fix -> fx(() -> applyDiagnosticFix(captured, generation, diagnostics, fix)); diagnosticsPane.show(diagnostics, label, apply); source.diagnostics(captured.text(), diagnostics); host.diagnostics().replace(diagnosticsOwner, captured, label, diagnostics, apply); } private void applyDiagnosticFix( DocumentSnapshot captured, long generation, java.util.List diagnostics, HostServices.QuickFix fix) { if (closed || generation != diagnosticGeneration) return; withDraft( () -> { if (generation != diagnosticGeneration || draft.revision() != captured.revision() || !draft.text().equals(captured.text()) || !draft.writable() || diagnostics.stream().noneMatch(d -> d.fixes().contains(fix))) { status.setText("Diagnostic changed; validate again before applying a fix"); return; } pendingReferenceValidation = apply(draft.text(), fix.edits()); submit(fix.edits(), fix.label()); }); } private void validationUnavailable(Throwable error) { publishDiagnostics( "Validation unavailable; results are not a clean bill of health", java.util.List.of( new HostServices.Diagnostic( "Designer", HostServices.Severity.ERROR, String.valueOf(error.getMessage()), Optional.of(new HostServices.Location(draft.document(), 0))))); } private void navigateDiagnostic(HostServices.Diagnostic problem) { long revision = diagnosticsRevision; withDraft( () -> { if (revision != draft.revision()) { publishDiagnostics( "Document changed; validate again before navigating", java.util.List.of()); return; } problem .location() .ifPresent( location -> { if (location.document().equals(draft.document())) showSource(location.offset()); else host.navigation() .openSource(location) .exceptionally( error -> { fx(() -> report(error)); return null; }); }); }); } /** Select authoritative FXML source, preserving the host-owned draft and undo history. */ public void showSource(int offset) { if (closed) return; if (draft == null) { pendingSourceOffset = offset; return; } sourceSplit.getItems().setAll(source); source.positionCaret(Math.min(Math.max(0, offset), source.getLength())); source.requestFocus(); } private void editStructure(ReferenceEditor.Intent intent) { withDraft( () -> { try { if (!draft.writable()) throw new IllegalStateException("Document is read-only"); if (!draft.text().equals(intent.source())) throw new IllegalStateException("Document changed; select the source object again"); if (!intent.change().importedCommandTargets().isEmpty()) { validateCommandPaste(intent); return; } if (intent.validate()) pendingReferenceValidation = apply(draft.text(), intent.change().edits()); submit(intent.change().edits(), intent.label()); } catch (Exception e) { referenceEditor.error(e.getMessage()); } }); } /** Validate imported Command paths against the destination snapshot before the first write. */ private void validateCommandPaste(ReferenceEditor.Intent intent) { var original = draft; String proposed = apply(original.text(), intent.change().edits()); var candidate = new DocumentSnapshot( original.document(), original.revision(), proposed, original.writable(), true); bindingWorkflow .bindingDetails(last, candidate, "", "view", "", "") .whenComplete( (metadata, error) -> fx( () -> { if (closed) return; if (error != null) { referenceEditor.error( "Cannot validate the destination Commands: " + error.getMessage()); return; } if (draft.revision() != original.revision() || !source.getText().equals(original.text())) { referenceEditor.error( "Destination changed. Select the destination and paste again."); return; } if (!metadata .commandTargets() .containsAll(intent.change().importedCommandTargets())) { referenceEditor.error( "The destination build could not resolve the copied Command targets."); return; } var conflicts = metadata.problems().stream() .filter( p -> p.severity().equals("ERROR") && intent .change() .importedCommandTargets() .contains(p.control())) .map(p -> p.message()) .toList(); if (!conflicts.isEmpty()) { referenceEditor.error(String.join("; ", conflicts)); return; } pendingReferenceValidation = proposed; submit(intent.change().edits(), intent.label()); })); } private void editTable(TableEditor.Intent intent) { withDraft( () -> { try { if (!draft.writable()) throw new IllegalStateException("Document is read-only"); if (!draft.text().equals(intent.source())) throw new IllegalStateException("Document changed; select the Table again"); submit(intent.edits(), intent.label()); } catch (Exception error) { tableEditor.error(error.getMessage()); } }); } private BindingEditor editor(BindingDocument.Kind kind) { return new BindingEditor( kind, this::editBinding, id -> { var document = kit.editor().getFxomDocument(); if (document == null) return; var selection = new FXOMFxIdIndex(document).lookup(id); if (selection != null) kit.editor().getSelection().select(selection); }, values -> validateBindings(kind == BindingDocument.Kind.COMMAND ? null : values, false)); } private void editBinding(BindingEditor.Intent intent) { withDraft( () -> { try { if (!draft.writable()) throw new IllegalStateException("Document is read-only"); if (!draft.text().equals(intent.source())) throw new IllegalStateException("Document changed; select the binding again"); var bindings = new BindingDocument(draft.text(), intent.kind()); var edits = intent.remove() ? bindings.remove(java.util.Objects.requireNonNull(intent.index())) : bindings.write(intent.index(), intent.values(), intent.replace()); submit( edits, intent.remove() ? "Remove " + intent.kind().element() : (intent.index() == null ? "Create " : "Edit ") + intent.kind().element()); } catch (Exception error) { (intent.kind() == BindingDocument.Kind.REPEAT ? repeatEditor : intent.kind() == BindingDocument.Kind.COMPUTED ? computedEditor : intent.kind() == BindingDocument.Kind.COMMAND ? commandEditor : bindingEditor) .error(error.getMessage()); } }); } private boolean bindingPreviewAllowed() { try { var errors = new ArrayList<>(new BindingDocument(draft.text()).errors()); errors.addAll(new TableDocument(draft.text()).errors()); errors.addAll(new ReferenceDocument(draft.text()).referenceErrors()); if (errors.isEmpty()) return true; status.setText("Preview blocked: " + String.join("; ", errors)); clearFormPreview(status.getText()); if (projection != null) for (String id : projection.components().keySet()) { var region = proxy(id); if (region != null) region.show(images.get(id), "Binding errors; preview outdated"); } } catch (Exception error) { report(error); } return false; } private void validateBindings(BindingDocument.Values values, boolean preview) { withDraft( () -> { if (preview && draft.text().equals(validatingSource)) { validationPreview = true; return; } long ticket = ++bindingRequest; var captured = draft; validatingSource = captured.text(); validationPreview |= preview; publishDiagnostics("Validating target types…", java.util.List.of()); status.setText("Validating binding types in target runtime…"); bindingWorkflow .bindingDetails( last, captured, values == null ? "" : values.pane().isEmpty() && values.collection().isEmpty() ? values.path() : values.collection(), values == null ? "both" : values.direction(), values == null ? "" : values.control(), values == null ? "" : values.property()) .whenComplete( (metadata, error) -> fx( () -> { if (closed || ticket != bindingRequest || draft.revision() != captured.revision()) return; validatingSource = null; boolean resumePreview = validationPreview; validationPreview = false; if (error != null) { validationUnavailable(error); status.setText( "Binding validation unavailable: " + error.getMessage()); clearFormPreview( status.getText() + " · use Build and Refresh, or choose Preview last" + " successful."); return; } validatedSource = captured.text(); bindingProblems = metadata.problems(); formEditor.eventHandlers(metadata.actionEventHandlers()); publishDiagnostics( last ? "Explicit retained build (outdated)" : "Current successful build", FxmlDiagnostics.target(captured, metadata.problems())); bindingEditor.metadata( metadata, values, (last ? "Explicit retained build (outdated)" : "Current successful build") + " · draft revision " + captured.revision()); computedEditor.metadata( metadata, values, (last ? "Explicit retained build (outdated)" : "Current successful build") + " · draft revision " + captured.revision()); commandEditor.metadata( metadata, values, last ? "Retained build" : "Current successful build"); repeatEditor.metadata( metadata, values, (last ? "Explicit retained build (outdated)" : "Current successful build") + " · draft revision " + captured.revision()); tableEditor.metadata( metadata, values, (last ? "Explicit retained build (outdated)" : "Current successful build") + " · draft revision " + captured.revision()); status.setText( "Binding validation complete: " + metadata.problems().size() + " diagnostics"); if (resumePreview) render(); })); }); } private void discoverBindings(String path, String direction) { withDraft( () -> { long ticket = ++bindingRequest; bindingBrowser.invalidate("Discovering declared types in target runtime…"); var captured = draft; validatingSource = captured.text(); bindingWorkflow .bindings(last, captured, path, direction) .whenComplete( (metadata, error) -> fx( () -> { if (closed || ticket != bindingRequest || draft.revision() != captured.revision()) return; validatingSource = null; boolean resumePreview = validationPreview; validationPreview = false; if (error != null) { validationUnavailable(error); bindingBrowser.invalidate( "Discovery unavailable: " + error.getMessage() + ". Build and Refresh, then retry."); return; } validatedSource = captured.text(); bindingProblems = metadata.problems(); formEditor.eventHandlers(metadata.actionEventHandlers()); publishDiagnostics( last ? "Explicit retained build (outdated)" : "Current successful build", FxmlDiagnostics.target(captured, metadata.problems())); bindingBrowser.show( metadata, (last ? "explicitly retained build (outdated)" : "current successful build") + " · draft revision " + captured.revision()); bindingEditor.metadata( metadata, null, "Discovery · draft revision " + captured.revision()); if (resumePreview) render(); })); }); } private void build(Map approvals) { invalidateBindings("Build changed; discover bindings after Build and Refresh."); withDraft( () -> { renderSequence.incrementAndGet(); clearFormPreview("Building selected context…"); status.setText("Building selected context…"); buildRun = workflow.build(approvals); buildRun .completion() .whenComplete( (result, error) -> fx( () -> { if (error != null) { report(error); return; } status.setText(result.message()); if (result.status() == BuildRefresh.Status.NEEDS_SAVE) { var alert = new Alert( Alert.AlertType.CONFIRMATION, "Save these build inputs?\n" + String.join( "\n", result.unsaved().stream() .map(d -> d.document().toString()) .toList()), ButtonType.OK, ButtonType.CANCEL); alert.setHeaderText("Save affected files and build"); if (alert.showAndWait().orElse(ButtonType.CANCEL) == ButtonType.OK) { var approved = new HashMap(); result .unsaved() .forEach(d -> approved.put(d.document(), d.revision())); build(approved); } } else if (result.status() == BuildRefresh.Status.READY) discover(false); else clearFormPreview( result.message() + " · correct the build and use Build and Refresh, or choose" + " Preview last successful."); })); }); } public void discover(boolean useLast) { withDraft( () -> { last = useLast; status.setText( useLast ? "Discovering explicitly retained build…" : "Discovering successful build…"); workflow .examplesFor(useLast, file.toUri()) .whenComplete( (entries, error) -> fx( () -> { if (error != null) { report(error); return; } examples.getItems().setAll(entries); if (!entries.isEmpty()) { String preferred = de.neitzel.fxdesigner.config.ConfigurationFiles.load( launch.configuration()) .contexts() .get(launch.context()) .preview() .defaultExample(); examples .getSelectionModel() .select( entries.stream() .filter(e -> e.id().equals(preferred)) .findFirst() .orElse(entries.getFirst())); } status.setText( (last ? "Outdated build explicitly selected · " : "") + entries.size() + " examples"); render(); })); }); } private void clearFormPreview(String message) { wholeImage.setImage(null); previewState.setText(message); } private void previewSizeChanged() { renderSequence.incrementAndGet(); wholeImage.setImage(null); previewState.setText("Rendering selected size…"); resize.playFromStart(); } private boolean affectsInteractive(java.net.URI uri) { if (file.toUri().equals(uri) || Path.of(uri).equals(file)) return true; if (projection == null) return false; String path = Path.of(uri).toString().replace(java.io.File.separatorChar, '/'); return java.util.stream.Stream.concat( projection.navigationTypes().values().stream(), projection.rowComponents().stream()) .anyMatch(type -> path.endsWith("/" + type.replace('.', '/') + ".fxml")); } public void render() { withDraft( () -> { if (!bindingPreviewAllowed()) return; if (!draft.text().equals(validatedSource)) { validateBindings(null, true); return; } if (bindingProblems.stream().anyMatch(p -> p.severity().equals("ERROR"))) { status.setText( "Preview blocked: " + bindingProblems.stream() .filter(p -> p.severity().equals("ERROR")) .map(p -> p.message()) .collect(java.util.stream.Collectors.joining("; "))); clearFormPreview(status.getText()); return; } var selected = examples.getValue(); if (selected == null) { previewState.setText( "Select a preview example after Build and Refresh. If none is listed, register an" + " example for this FXML."); status.setText(previewState.getText()); return; } if (projection == null && !interactiveRequested && !showWhole) return; long ticket = renderSequence.incrementAndGet(); host.documents() .snapshots() .whenComplete( (dirty, error) -> fx( () -> { if (error != null) { report(error); return; } if (ticket != renderSequence.get()) return; var drafts = new LinkedHashMap(); drafts.put(draft.document(), draft); dirty.stream() .filter( d -> d.document().toString().endsWith(".fxml") && !Path.of(d.document()) .startsWith( launch .configuration() .getParent() .resolve(".neitzel-fx-designer")) && Path.of(d.document()).startsWith(reactorRoot)) .forEach(d -> drafts.put(d.document(), d)); drafts.put( draft.document(), new DocumentSnapshot( draft.document(), draft.revision(), projection == null ? draft.text() : projection.previewText(), draft.writable(), draft.dirty())); renderComponents(List.copyOf(drafts.values()), selected.id(), ticket); })); }); } private void renderComponents(List drafts, String example, long ticket) { if (ticket != renderSequence.get() || closed) return; var nodes = new LinkedHashMap(); for (String id : projection == null ? Set.of() : projection.components().keySet()) { var region = proxy(id); if (region == null) continue; int width = (int) Math.max( 1, Math.min( 1600, region.getWidth() > 0 ? region.getWidth() : region.prefWidth(-1))), height = (int) Math.max( 1, Math.min( 1200, region.getHeight() > 0 ? region.getHeight() : region.prefHeight(-1))); nodes.put(id, new DesignerWorkflow.Size(width, height)); region.updating(); } if (interactiveRequested && interactiveRestart) { interactiveRestart = false; long request = ++interactiveRequest, changes = draftChanges.get(); interactiveStatus.setText("Starting interactive preview of current drafts…"); interactiveWorkflow .interactive(last, example, drafts) .whenComplete( (value, error) -> fx( () -> { if (!interactiveRequested || request != interactiveRequest) return; if (error != null) { interactiveStatus.setText( "Interactive preview failed; use Interactive preview to retry"); report(error); } else interactiveStatus.setText( changes == draftChanges.get() ? "Interactive preview running from captured drafts" : "Interactive preview uses earlier drafts; rerun or save to" + " restart"); })); } if (showWhole) nodes.put("", new DesignerWorkflow.Size(previewWidth.getValue(), previewHeight.getValue())); if (nodes.isEmpty()) { status.setText( projection == null ? "Canvas projection unavailable; interactive preview uses the FXML draft" : "No embedded Components; use Interactive preview for this View"); return; } workflow .renderImages(last, example, nodes, drafts) .whenComplete( (frames, error) -> fx( () -> { if (ticket != renderSequence.get()) return; if (error != null) { if (showWhole) { wholeImage.setImage(null); previewState.setText("Preview failed: " + error.getMessage()); } if (projection != null) projection .components() .keySet() .forEach( id -> { var region = proxy(id); if (region != null) region.failed(); }); report(error); return; } boolean measurementsChanged = false; for (var frame : frames) { int width = frame.width(), height = frame.height(); var image = new WritableImage(width, height); byte[] rgba = frame.rgba(); int[] argb = new int[width * height]; for (int i = 0; i < argb.length; i++) argb[i] = ((rgba[i * 4 + 3] & 255) << 24) | ((rgba[i * 4] & 255) << 16) | ((rgba[i * 4 + 1] & 255) << 8) | (rgba[i * 4 + 2] & 255); image .getPixelWriter() .setPixels( 0, 0, width, height, PixelFormat.getIntArgbInstance(), argb, 0, width); if (frame.node().isEmpty()) { wholeImage.setImage(image); previewState.setText( (last ? "Retained build · Build and Refresh for current sources · " : "") + examples.getValue().label() + " · " + width + " × " + height + " · revision " + draft.revision()); continue; } images.put(frame.node(), image); var region = proxy(frame.node()); if (region != null) { if (layoutPasses < 8) measurementsChanged |= region.measurements(frame.metrics()); region.show(image, last ? "Explicit retained build" : "Target runtime"); } } layoutPasses = measurementsChanged ? layoutPasses + 1 : 0; if (layoutPasses >= 8) { resize.stop(); if (projection != null) projection .components() .keySet() .forEach( id -> { var region = proxy(id); if (region != null) region.failed(); }); status.setText("Target layout did not stabilize; retaining last layout"); return; } status.setText( "Rendered snapshot " + frames.getFirst().snapshot() + " · revision " + draft.revision()); })); } private void openComponent() { if (projection == null || projection.components().isEmpty()) return; var choice = new ChoiceDialog<>( projection.components().keySet().iterator().next(), projection.components().keySet()); choice.setHeaderText("Open Component in a separate editor"); choice .showAndWait() .ifPresent( id -> { String type = projection.navigationTypes().get(id); navigateComponent(type); }); } private void openRowComponent() { if (projection == null || projection.rowComponents().isEmpty()) { status.setText("No declared Row Component in this View"); return; } var rows = projection.rowComponents(); var choice = new ChoiceDialog<>(rows.iterator().next(), rows); choice.setHeaderText("Open Row Component without changing its layout"); choice.showAndWait().ifPresent(this::navigateComponent); } private void navigateComponent(String type) { host.navigation() .componentSources(type) .thenCompose( attached -> { if (attached.isEmpty()) return workflow.componentSources(type); return java.util.concurrent.CompletableFuture.completedFuture( attached.stream() .map( location -> new DesignerWorkflow.ComponentSource( location.document(), location.document().toString(), true)) .toList()); }) .whenComplete( (sources, error) -> fx( () -> { if (error != null) { report(error); return; } DesignerWorkflow.ComponentSource selected; if (sources.size() == 1) selected = sources.getFirst(); else { var choice = new ChoiceDialog<>(sources.getFirst(), sources); choice.setHeaderText("Choose Component source origin"); selected = choice.showAndWait().orElse(null); } if (selected != null) host.navigation() .open(new HostServices.Location(selected.document(), 0)) .exceptionally( failure -> { fx(() -> report(failure)); return null; }); })); } public CompletionStage flush() { var result = new CompletableFuture(); flushInto(result, System.nanoTime() + TimeUnit.SECONDS.toNanos(5)); return result; } private void flushInto(CompletableFuture result, long deadline) { flushCanvas(); if (System.nanoTime() > deadline) { result.completeExceptionally( new IllegalStateException("Source edit could not be synchronized")); return; } if (closed) { result.completeExceptionally(new IllegalStateException("Editor closed")); return; } if (!pending && draft != null && source.getText().equals(draft.text())) { result.complete(null); return; } commitSource(); var wait = new PauseTransition(Duration.millis(50)); wait.setOnFinished(e -> flushInto(result, deadline)); wait.play(); } public KitView kit() { return kit; } public void close() { if (closed) return; closed = true; diagnosticGeneration++; source.diagnostics("", java.util.List.of()); host.diagnostics().clear(diagnosticsOwner); try { changes.close(); saves.close(); } catch (Exception ignored) { } poll.stop(); typing.stop(); resize.stop(); workflow.close(); interactiveWorkflow.close(); bindingWorkflow.close(); viewGeneration.close(); bindingRequest++; if (document != null) document.close(); } }