better semantic style for PBS

This commit is contained in:
2026-04-02 18:35:58 +01:00
parent 275a7aa408
commit 4c1a5317dd
14 changed files with 1051 additions and 44 deletions
@@ -0,0 +1,93 @@
package p.studio.workspaces.editor;
import javafx.scene.Node;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
final class EditorDocumentScopeGuideGraphicFactory {
private static final double COLUMN_WIDTH = 10.0;
private static final double CANVAS_PADDING = 6.0;
private static final Color GUIDE_COLOR = Color.web("#384657");
private static final Color GUIDE_CAP_COLOR = Color.web("#6fa8dc");
private EditorDocumentScopeGuideGraphicFactory() {
}
static Node create(
final Node lineNumberNode,
final int paragraphIndex,
final EditorDocumentScopeGuideModel model) {
final var container = new HBox(lineNumberNode);
final int maxDepth = model.maxDepth();
if (maxDepth > 0) {
container.getChildren().add(new ScopeGuideCanvas(model.segmentsForLine(paragraphIndex), maxDepth));
}
return container;
}
private static final class ScopeGuideCanvas extends Region {
private final Canvas canvas = new Canvas();
private final java.util.List<EditorDocumentScopeGuideModel.GuideSegment> segments;
private final int maxDepth;
private ScopeGuideCanvas(
final java.util.List<EditorDocumentScopeGuideModel.GuideSegment> segments,
final int maxDepth) {
this.segments = segments;
this.maxDepth = maxDepth;
getStyleClass().add("editor-workspace-scope-guide-gutter");
getChildren().add(canvas);
setMinWidth(computeGuideWidth(maxDepth));
setPrefWidth(computeGuideWidth(maxDepth));
setMaxWidth(computeGuideWidth(maxDepth));
}
@Override
protected double computePrefWidth(final double height) {
return computeGuideWidth(maxDepth);
}
@Override
protected void layoutChildren() {
final double width = snapSizeX(getWidth());
final double height = Math.max(1.0, snapSizeY(getHeight()));
canvas.setWidth(width);
canvas.setHeight(height);
draw(width, height);
}
private void draw(final double width, final double height) {
final GraphicsContext graphics = canvas.getGraphicsContext2D();
graphics.clearRect(0, 0, width, height);
if (segments.isEmpty()) {
return;
}
final double centerY = Math.floor(height / 2.0);
for (final var segment : segments) {
final double x = CANVAS_PADDING + (segment.depth() * COLUMN_WIDTH) + (COLUMN_WIDTH / 2.0);
graphics.setLineWidth(1.2);
graphics.setStroke(GUIDE_COLOR);
switch (segment.kind()) {
case START -> {
graphics.strokeLine(x, centerY, x, height);
graphics.setStroke(GUIDE_CAP_COLOR);
graphics.strokeLine(x, centerY, x + 4.0, centerY);
}
case CONTINUE -> graphics.strokeLine(x, 0, x, height);
case END -> {
graphics.strokeLine(x, 0, x, centerY);
graphics.setStroke(GUIDE_CAP_COLOR);
graphics.strokeLine(x, centerY, x + 4.0, centerY);
}
}
}
}
private static double computeGuideWidth(final int maxDepth) {
return maxDepth <= 0 ? 0.0 : CANVAS_PADDING * 2.0 + (maxDepth * COLUMN_WIDTH);
}
}
}
@@ -0,0 +1,163 @@
package p.studio.workspaces.editor;
import p.studio.lsp.dtos.LspRangeDTO;
import p.studio.lsp.dtos.LspSymbolDTO;
import p.studio.lsp.messages.LspSymbolKind;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
final class EditorDocumentScopeGuideModel {
private static final EditorDocumentScopeGuideModel EMPTY = new EditorDocumentScopeGuideModel(List.of(), 0);
private final List<List<GuideSegment>> lines;
private final int maxDepth;
private EditorDocumentScopeGuideModel(
final List<List<GuideSegment>> lines,
final int maxDepth) {
this.lines = lines;
this.maxDepth = maxDepth;
}
static EditorDocumentScopeGuideModel empty() {
return EMPTY;
}
static EditorDocumentScopeGuideModel from(
final String content,
final List<LspSymbolDTO> symbols) {
final int totalLines = totalLines(content);
final List<List<GuideSegment>> lines = new ArrayList<>(totalLines);
for (int line = 0; line < totalLines; line++) {
lines.add(new ArrayList<>());
}
final List<Integer> lineStarts = lineStarts(content);
final int[] maxDepth = new int[] {0};
for (final LspSymbolDTO symbol : symbols) {
appendSymbol(lines, lineStarts, content.length(), symbol, 0, maxDepth);
}
final List<List<GuideSegment>> frozen = lines.stream()
.map(List::copyOf)
.toList();
return new EditorDocumentScopeGuideModel(frozen, maxDepth[0]);
}
List<GuideSegment> segmentsForLine(final int lineIndex) {
if (lineIndex < 0 || lineIndex >= lines.size()) {
return List.of();
}
return lines.get(lineIndex);
}
int maxDepth() {
return maxDepth;
}
private static void appendSymbol(
final List<List<GuideSegment>> lines,
final List<Integer> lineStarts,
final int contentLength,
final LspSymbolDTO symbol,
final int depth,
final int[] maxDepth) {
if (symbol.kind() != LspSymbolKind.UNKNOWN) {
appendRange(lines, lineStarts, contentLength, symbol.range(), depth, maxDepth);
}
for (final LspSymbolDTO child : symbol.children()) {
appendSymbol(lines, lineStarts, contentLength, child, depth + 1, maxDepth);
}
}
private static void appendRange(
final List<List<GuideSegment>> lines,
final List<Integer> lineStarts,
final int contentLength,
final LspRangeDTO range,
final int depth,
final int[] maxDepth) {
if (lines.isEmpty()) {
return;
}
final int startLine = lineForOffset(lineStarts, clamp(range.startOffset(), 0, contentLength));
final int inclusiveEndOffset = Math.max(range.startOffset(), Math.min(contentLength, range.endOffset()) - 1);
final int endLine = lineForOffset(lineStarts, clamp(inclusiveEndOffset, 0, contentLength));
if (endLine <= startLine) {
return;
}
maxDepth[0] = Math.max(maxDepth[0], depth + 1);
for (int line = startLine; line <= endLine; line++) {
final GuideSegmentKind kind;
if (line == startLine) {
kind = GuideSegmentKind.START;
} else if (line == endLine) {
kind = GuideSegmentKind.END;
} else {
kind = GuideSegmentKind.CONTINUE;
}
lines.get(line).add(new GuideSegment(depth, kind));
}
}
private static int totalLines(final String content) {
if (content.isEmpty()) {
return 1;
}
int total = 1;
for (int index = 0; index < content.length(); index++) {
if (content.charAt(index) == '\n') {
total++;
}
}
return total;
}
private static List<Integer> lineStarts(final String content) {
if (content.isEmpty()) {
return List.of(0);
}
final List<Integer> starts = new ArrayList<>();
starts.add(0);
for (int index = 0; index < content.length(); index++) {
if (content.charAt(index) == '\n') {
starts.add(index + 1);
}
}
return Collections.unmodifiableList(starts);
}
private static int lineForOffset(final List<Integer> lineStarts, final int offset) {
int low = 0;
int high = lineStarts.size() - 1;
while (low <= high) {
final int mid = (low + high) >>> 1;
final int start = lineStarts.get(mid);
final int nextStart = mid + 1 < lineStarts.size() ? lineStarts.get(mid + 1) : Integer.MAX_VALUE;
if (offset < start) {
high = mid - 1;
continue;
}
if (offset >= nextStart) {
low = mid + 1;
continue;
}
return mid;
}
return Math.max(0, Math.min(lineStarts.size() - 1, low));
}
private static int clamp(final int value, final int minimum, final int maximum) {
return Math.max(minimum, Math.min(maximum, value));
}
enum GuideSegmentKind {
START,
CONTINUE,
END
}
record GuideSegment(int depth, GuideSegmentKind kind) {
}
}
@@ -5,6 +5,7 @@ import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import p.studio.lsp.dtos.LspSymbolDTO;
import p.studio.lsp.messages.LspSymbolKind;
import p.studio.Container;
import p.studio.controls.WorkspaceDockPane;
import p.studio.utilities.i18n.I18n;
@@ -64,24 +65,38 @@ public final class EditorOutlinePanel extends WorkspaceDockPane {
private void rebuildSymbols(final List<LspSymbolDTO> symbols) {
symbolsBox.getChildren().clear();
if (symbols.isEmpty()) {
symbolsBox.getChildren().add(placeholderLabel(I18n.CODE_EDITOR_OUTLINE_EMPTY_SYMBOLS));
return;
}
int visible = 0;
for (final LspSymbolDTO symbol : symbols) {
appendSymbol(symbol, 0);
visible += appendSymbol(symbol, 0);
}
if (visible == 0) {
symbolsBox.getChildren().add(placeholderLabel(I18n.CODE_EDITOR_OUTLINE_EMPTY_SYMBOLS));
}
}
private void appendSymbol(final LspSymbolDTO symbol, final int depth) {
final var label = new Label(symbol.name() + " • " + symbol.kind().name().toLowerCase());
label.setWrapText(true);
label.setPadding(new Insets(0, 0, 0, depth * 12));
label.getStyleClass().add("editor-workspace-outline-item");
symbolsBox.getChildren().add(label);
for (final LspSymbolDTO child : symbol.children()) {
appendSymbol(child, depth + 1);
private int appendSymbol(final LspSymbolDTO symbol, final int depth) {
int visible = 0;
int childDepth = depth;
if (showInOutline(symbol.kind())) {
final var label = new Label(symbol.name() + " • " + symbol.kind().name().toLowerCase());
label.setWrapText(true);
label.setPadding(new Insets(0, 0, 0, depth * 12));
label.getStyleClass().add("editor-workspace-outline-item");
symbolsBox.getChildren().add(label);
visible++;
childDepth++;
}
for (final LspSymbolDTO child : symbol.children()) {
visible += appendSymbol(child, childDepth);
}
return visible;
}
private boolean showInOutline(final LspSymbolKind kind) {
return switch (kind) {
case IF, SWITCH, FOR, WHILE, HANDLE -> false;
default -> true;
};
}
private Label sectionTitle(final I18n key) {
@@ -24,6 +24,7 @@ import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.IntFunction;
public final class EditorWorkspace extends Workspace {
private final BorderPane root = new BorderPane();
@@ -42,6 +43,8 @@ public final class EditorWorkspace extends Workspace {
private final VfsProjectDocument vfsProjectDocument;
private final EditorOpenFileSession openFileSession = new EditorOpenFileSession();
private final List<String> activePresentationStylesheets = new ArrayList<>();
private final IntFunction<Node> lineNumberFactory = LineNumberFactory.get(codeArea);
private EditorDocumentScopeGuideModel scopeGuideModel = EditorDocumentScopeGuideModel.empty();
private boolean syncingEditor;
public EditorWorkspace(
@@ -52,7 +55,7 @@ public final class EditorWorkspace extends Workspace {
this.vfsProjectDocument = Objects.requireNonNull(vfsProjectDocument, "vfsProjectDocument");
this.prometeuLspService = Objects.requireNonNull(prometeuLspService, "prometeuLspService");
root.getStyleClass().add("editor-workspace");
codeArea.setParagraphGraphicFactory(LineNumberFactory.get(codeArea));
refreshParagraphGraphics();
codeArea.setEditable(false);
codeArea.setWrapText(false);
codeArea.textProperty().addListener((ignored, previous, current) -> syncActiveDocumentToVfs(current));
@@ -134,6 +137,8 @@ public final class EditorWorkspace extends Workspace {
fileBuffer,
presentation,
analysis);
scopeGuideModel = guidesFor(fileBuffer, analysis);
refreshParagraphGraphics();
applyPresentationStylesheets(presentation);
syncingEditor = true;
try {
@@ -178,6 +183,8 @@ public final class EditorWorkspace extends Workspace {
private void showEditorPlaceholder() {
final EditorDocumentPresentation presentation = presentationRegistry.resolve("text");
scopeGuideModel = EditorDocumentScopeGuideModel.empty();
refreshParagraphGraphics();
applyPresentationStylesheets(presentation);
syncingEditor = true;
try {
@@ -209,6 +216,13 @@ public final class EditorWorkspace extends Workspace {
root.getStylesheets().addAll(activePresentationStylesheets);
}
private void refreshParagraphGraphics() {
codeArea.setParagraphGraphicFactory(paragraphIndex -> EditorDocumentScopeGuideGraphicFactory.create(
lineNumberFactory.apply(paragraphIndex),
paragraphIndex,
scopeGuideModel));
}
private VBox buildLayout() {
final var content = new SplitPane(buildLeftColumn(), buildRightColumn());
content.setDividerPositions(0.30);
@@ -354,4 +368,13 @@ public final class EditorWorkspace extends Workspace {
outlinePanel.showSemanticReadResult(fileBuffer.path(), analysis.documentSymbols());
helperPanel.showSemanticReadResult(fileBuffer.path(), analysis.diagnostics());
}
private EditorDocumentScopeGuideModel guidesFor(
final EditorOpenFileBuffer fileBuffer,
final LspAnalyzeDocumentResult analysis) {
if (!fileBuffer.frontendDocument() || analysis == null) {
return EditorDocumentScopeGuideModel.empty();
}
return EditorDocumentScopeGuideModel.from(fileBuffer.content(), analysis.documentSymbols());
}
}
@@ -9,6 +9,7 @@ import p.studio.lsp.messages.LspAnalyzeDocumentResult;
import p.studio.vfs.messages.VfsDocumentAccessMode;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -107,4 +108,47 @@ final class EditorDocumentHighlightingRouterTest {
assertEquals(EditorDocumentHighlightOwner.LOCAL, result.owner());
assertTrue(result.styleSpans().getStyleSpan(0).getStyle().isEmpty());
}
@Test
void frontendServiceHighlightsProjectToDedicatedServiceCssClass() {
final EditorDocumentPresentationRegistry registry = new EditorDocumentPresentationRegistry();
final EditorOpenFileBuffer fileBuffer = new EditorOpenFileBuffer(
Path.of("/tmp/example/src/main.pbs"),
"main.pbs",
"pbs",
"declare service Game {}",
"LF",
true,
VfsDocumentAccessMode.READ_ONLY,
false);
final LspAnalyzeDocumentResult analysis = new LspAnalyzeDocumentResult(
new LspSessionStateDTO(true, List.of("highlight")),
new LspSemanticPresentationDTO(
List.of("pbs-service"),
List.of("/themes/pbs/semantic-highlighting.css")),
List.of(),
List.of(new LspHighlightSpanDTO(new LspRangeDTO(16, 20), "pbs-service")),
List.of(),
List.of());
final EditorDocumentHighlightingResult result = EditorDocumentHighlightingRouter.route(
fileBuffer,
registry.resolve("pbs", analysis.semanticPresentation()),
analysis);
assertEquals(EditorDocumentHighlightOwner.LSP, result.owner());
assertTrue(containsStyle(result.styleSpans(), "editor-semantic-pbs-service"));
}
private boolean containsStyle(
final org.fxmisc.richtext.model.StyleSpans<Collection<String>> styleSpans,
final String styleClass) {
for (int index = 0; index < styleSpans.getSpanCount(); index++) {
if (styleSpans.getStyleSpan(index).getStyle().contains(styleClass)) {
return true;
}
}
return false;
}
}
@@ -14,11 +14,11 @@ final class EditorDocumentPresentationRegistryTest {
final EditorDocumentPresentation presentation = registry.resolve(
"pbs",
new LspSemanticPresentationDTO(
java.util.List.of("pbs-keyword"),
java.util.List.of("pbs-keyword", "pbs-service"),
java.util.List.of("/themes/pbs/semantic-highlighting.css")));
assertEquals("pbs", presentation.styleKey());
assertEquals(java.util.List.of("pbs-keyword"), presentation.semanticKeys());
assertEquals(java.util.List.of("pbs-keyword", "pbs-service"), presentation.semanticKeys());
assertEquals(1, presentation.stylesheetUrls().size());
assertTrue(presentation.stylesheetUrls().getFirst().endsWith("/themes/pbs/semantic-highlighting.css"));
}
@@ -0,0 +1,94 @@
package p.studio.workspaces.editor;
import org.junit.jupiter.api.Test;
import p.studio.lsp.dtos.LspRangeDTO;
import p.studio.lsp.dtos.LspSymbolDTO;
import p.studio.lsp.messages.LspSymbolKind;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
final class EditorDocumentScopeGuideModelTest {
@Test
void buildsNestedGuidesForMultilineStructuralSymbols() {
final String content = """
struct Hero {
fn attack() {
let value = 1
}
}
enum Kind {
Unit
}
""";
final LspSymbolDTO attack = symbol(content, "fn attack()", "}", LspSymbolKind.METHOD, List.of());
final LspSymbolDTO hero = new LspSymbolDTO(
"struct Hero",
LspSymbolKind.STRUCT,
Path.of("/tmp/example/main.pbs"),
new LspRangeDTO(
content.indexOf("struct Hero"),
content.indexOf("\n\nenum Kind")),
List.of(attack));
final LspSymbolDTO kind = symbol(content, "enum Kind", "}\n", LspSymbolKind.ENUM, List.of());
final EditorDocumentScopeGuideModel model = EditorDocumentScopeGuideModel.from(content, List.of(hero, kind));
assertEquals(2, model.maxDepth());
assertKinds(model, 0, "START");
assertKinds(model, 1, "CONTINUE", "START");
assertKinds(model, 2, "CONTINUE", "CONTINUE");
assertKinds(model, 3, "CONTINUE", "END");
assertKinds(model, 4, "END");
assertKinds(model, 5);
assertKinds(model, 6, "START");
assertKinds(model, 7, "CONTINUE");
assertKinds(model, 8, "END");
}
@Test
void ignoresSingleLineSymbols() {
final String content = "const VALUE = 1\n";
final LspSymbolDTO symbol = new LspSymbolDTO(
"VALUE",
LspSymbolKind.CONST,
Path.of("/tmp/example/main.pbs"),
new LspRangeDTO(0, content.indexOf('\n')),
List.of());
final EditorDocumentScopeGuideModel model = EditorDocumentScopeGuideModel.from(content, List.of(symbol));
assertEquals(0, model.maxDepth());
assertKinds(model, 0);
}
private static LspSymbolDTO symbol(
final String content,
final String startMarker,
final String endMarker,
final LspSymbolKind kind,
final List<LspSymbolDTO> children) {
final int start = content.indexOf(startMarker);
final int end = content.indexOf(endMarker, start) + endMarker.length();
return new LspSymbolDTO(
startMarker,
kind,
Path.of("/tmp/example/main.pbs"),
new LspRangeDTO(start, end),
children);
}
private static void assertKinds(
final EditorDocumentScopeGuideModel model,
final int line,
final String... expectedKinds) {
assertEquals(
List.of(expectedKinds),
model.segmentsForLine(line).stream()
.map(segment -> segment.kind().name())
.toList());
}
}