From 101c205c7b716ddf2d7ba50a6147a7fc32a59dbc Mon Sep 17 00:00:00 2001 From: xtof Date: Sat, 14 Nov 2026 12:49:52 +0100 Subject: [PATCH] Structured SVG export, export decorations, fanout bands, role grouping Role grouping: group_by "role" gathers a wide net's sinks by the naja role of the receiving pin (clock, reset, set, enable, scan, address, data), sent as a sparse "role" on term and occurrence entries by both providers (shared cases in tests/data/role_protocol_cases.json). SVG structure: every net, instance box, top-level port flag, fanout summary and module frame is a with data-* attributes (data-net, data-driver, data-path, data-id-path, data-model, ...; JSON paths when a name holds "/" or ":" or is anonymous). The drawing is unchanged: tests/SvgExportTest.cpp compares it to a golden file. Export decorations (view options, export_svg()/export_png() keywords, CLI flags): title and caption bands, a legend of traces and labeled nets, and hide_ui_glyphs (no open-pin stubs or "more pins" dots). The PNG export draws the same page. Fanout layout: a sink grid with several drivers gives each driver a band of rows level with it, all bands starting in the same column, so no net's wires cross another net's sinks. Sinks are in natural name order (lut_111 before lut_1037), which also picks the first max_sinks drawn. The convergence outline is never drawn on a styled box, and the new view option convergence_outline (--no-convergence-outline) turns it off. --help and the README say max_sinks defaults to 32 and 0 disables it. --- CLAUDE.md | 67 +++- CMakeLists.txt | 3 + README.md | 75 +++- REUSE.toml | 4 + python/README.md | 42 +- python/naja_schematic/__init__.py | 2 +- python/naja_schematic/protocol.py | 85 +++- python/naja_schematic/render.py | 64 ++- python/naja_schematic/server.py | 35 +- python/naja_schematic/session.py | 49 ++- python/naja_schematic/widget.py | 12 +- python/tests/data/py_prims.py | 16 + python/tests/data/role_fanout.v | 40 ++ python/tests/protocol_cases.py | 12 + python/tests/test_render.py | 199 ++++++++- python/tests/test_style.py | 55 +++ src/AppLogic.cpp | 11 +- src/EquipotentialView.cpp | 53 ++- src/LocalSNLProvider.cpp | 35 ++ src/SchematicLayout.cpp | 172 +++++++- src/SchematicLayout.h | 42 +- src/SchematicPainter.h | 14 + src/SchematicView.cpp | 300 ++++++++++++-- src/SchematicView.h | 25 ++ src/StyleStore.cpp | 8 + src/SvgPainter.cpp | 8 + src/Types.cpp | 2 + src/Types.h | 6 + src/ViewOptions.cpp | 32 +- src/ViewOptions.h | 27 +- src/main_native.cpp | 20 +- tests/FanoutTest.cpp | 361 ++++++++++++++++- tests/StyleStoreTest.cpp | 6 +- tests/SvgExportTest.cpp | 376 ++++++++++++++++++ tests/data/export_golden.svg | 200 ++++++++++ tests/data/role_protocol_cases.json | 54 +++ .../provider/LocalSNLProviderProtocolTest.cpp | 33 ++ 37 files changed, 2422 insertions(+), 123 deletions(-) create mode 100644 python/tests/data/role_fanout.v create mode 100644 tests/SvgExportTest.cpp create mode 100644 tests/data/export_golden.svg create mode 100644 tests/data/role_protocol_cases.json diff --git a/CLAUDE.md b/CLAUDE.md index 4df9ae1..f7f5a4d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -552,7 +552,8 @@ each visible trace in its own `TraceStore` color. A wire tree two visible traces go through is striped in their colors (`NetRoute::stripeColors`, dashes anchored to world coordinates; plain convergence color when zoomed too far out to read them), and a gate they share is outlined in the -near-black convergence color -- only a gate each trace's own reply listed +near-black convergence color (unless the gate is styled or +`convergence_outline` is off) -- only a gate each trace's own reply listed on the net (`Equipotential::traceInstances`): a trace's partial net folded into a fuller one already shown doesn't reach that net's other readers. A diagnosis color @@ -722,7 +723,8 @@ intercepts it (`Renderer.render_outputs()`); the session doesn't. `view_options` is a server push setting how the viewer draws, not what: `{"response":"view_options","instance_label":"name|model|both", -"sink_rows":8,"max_sinks":32,"group_by":"model|hierarchy|role"}`, keys +"sink_rows":8,"max_sinks":32,"group_by":"model|hierarchy|role|pin", +"convergence_outline":true}`, keys absent kept (`ViewOptions::apply()`; `protocol.view_options()` validates, `DEFAULT_VIEW_OPTIONS` mirrors the C++ defaults). Not cleared by a root load; the session re-sends it after each `root_response` anyway, first. @@ -730,6 +732,32 @@ render.py sends it in full at the start of every drawing. Also the View menu (Instance Labels, Fanout) and the CLIs' flags. Fanout summaries are pseudo-instances under a made-up path segment (id >= `kSummaryIdBase` in `EquipotentialView.cpp`), never sent to the host; see `planFanout()`. +`convergence_outline` (`--no-convergence-outline`, View > Outline Trace +Convergence): the near-black outline of a box two visible traces go +through; never drawn on a box a style names (`StyleStore::instanceStyle()`), +since it reads as an error or a selection in a figure. Like the four +export decorations below, it's left out of `ViewOptions::layoutJson()`. +Four keys only decorate exports (SVG and PNG), never the canvas, and are +left out of `ViewOptions::layoutJson()` so changing them doesn't refit: +`"title"`/`"caption"` (text bands above/below the drawing, `\n` breaks +lines), `"legend"` (a swatch + label per visible trace and per net a style +labels, `SchematicView::legend`, filled by `EquipotentialView`) and +`"hide_ui_glyphs"` (no open-pin stubs or "•••" dots, +`SchematicView::hideUiGlyphs` on the export copy). `export_svg()`/ +`export_png()` take them as keywords too (`protocol.EXPORT_DECORATIONS`); +CLIs: `--title`, `--caption`, `--legend`, `--hide-ui-glyphs`. +`group_by: "role"` groups sinks by the receiving pin's naja role +(`fanoutRoleGroup()`: "clock", "reset", "set", "enable", "scan", +"address", else "data"), read from the sparse `"role"` on term and +occurrence entries: naja's `SNLDesignModeling::getTermRole()` in snake +case (`"clock"`, `"async_reset"`, `"enable"`, `"memory_write_enable"`, +...), sent only for a non-data role (DataInput/DataOutput/Other: none), +from the `SNLInstTerm` on occurrences (parameter-driven roles) -- +`termRoleName()`/`setTermRole()` in `LocalSNLProvider.cpp`, +`term_role()`/`with_clock()` in `protocol.py`, kept in step (shared +cases: `tests/data/role_protocol_cases.json`). A pin naja +models as a clock with no role set counts as "clock". `"pin"` is the +older grouping: by pin name, clock pins together. `export_svg` is a server push too, `{"response":"export_svg"}`, from `Schematic.export_svg()` (`ViewerSession.export_svg()`): the viewer sets @@ -806,8 +834,13 @@ it must name a pin the viewer draws -- a leaf pin or a top-level port. Python resolves every item (`session.style_response()`, `ValueError` on a bad one) and sends a `net` item once per bit on its net's driver (a top-level port, else an output leaf pin: the pin a trace's partial net -also lists), whatever pin or `target` (an instance or pin as -`show_instance()`/`show_net()` take) named it. An `instance` item fills +also lists), whatever pin or `target` named it: an instance or pin as +`show_instance()`/`show_net()` take, or -- what a JSON style file can +say -- `render`'s `--instance`/`--net` text (`"u1/u2"`, `"u1:A[3]"`, +`"y"`, matched against the design), a pin as a `[instance, terminal(, +bit)]` list or a `{"path"|"id_path", "terminal", "bit"}` object +(`session.style_target()`). `target` is the Python host's: the native +`StyleStore::parse()` refuses it. An `instance` item fills the box (also gate symbols, port flags; module frames keep their translucency), outlines it in `color`/`width`, and `label` replaces the drawn name (`InstanceShape::label`, so the layout makes room for it). A @@ -1119,7 +1152,16 @@ path the host read, used by the native "Open in Editor". - `layoutHierarchyGroups()`: module frames. - Fanout: `layeredPlacement(..., maxSinkRows)` deals a column's sinks (nodes driving nothing placed) into a grid of columns, each its own - level; `planFanout()` picks which sinks of a wide net are drawn and + level, with a band of rows per driver (a sink's nearest one): every + band starts in the grid's first column and is placed level with its + driver, `kBandGap` under the band above, so no net's wire crosses + another net's sinks (`MultiDriverFanout` tests in + `tests/FanoutTest.cpp`). Sinks a crossing-reduction sweep can't tell + apart (the loads of one pin) keep `PlaceNode::rank` order: the + natural order of their names (`naturalLess()`/`naturalPathLess()`, + `lut_111` before `lut_1037`), summaries last; the receivers + `planFanout()` sees are sorted the same way, so the first max_sinks + drawn are the naturally first. `planFanout()` picks which sinks of a wide net are drawn and gathers the rest into groups (never a driver, a pinned instance, an expanded group or a group of one). The model label is a `kNameH` row under the symbol (`shownModel()`, `modelRect()`, `footprintHeight()`). @@ -1159,6 +1201,21 @@ path the host read, used by the native "Open in Editor". (native: `NativeFileDialog::saveFile()`; WASM: a Blob download, `najaDownloadText` in `AppLogic.cpp`). New drawing code goes through the painter, never straight to an `ImDrawList`, or it won't reach exports. + `BeginGroup()`/`EndGroup()` give the SVG its structure (no-ops for the + other painters): `SchematicView::render()` wraps each route/net + (`netGroup()`: `class="net"`, `data-net`, `data-driver` "path:pin" or a + port name, `data-driver-id-path`, `data-label`), box + (`instanceGroup()`: `class="instance"`, `data-path`, `data-id-path`, + `data-model`), port flag (`class="port"`, `data-name`, + `data-direction`), summary (`class="summary"`, `data-group`, + `data-count`) and module frame (`class="module"`), plus + `data-path-json`/`data-driver-json` when a name is empty or holds `/` or + `:`. Groups and decorations must not change the drawing: + `tests/SvgExportTest.cpp` compares an undecorated export, group tags + stripped, to `tests/data/export_golden.svg` (rewrite it with + `NAJA_SCHEMATIC_UPDATE_GOLDEN=1` only for a deliberate drawing change). + The decorated page (`layoutPage()`/`paintPage()`) is shared by + `exportSvg()` and `exportPng()`. - **`SchematicInteraction`** — the pure side of the schematic's pin interactions: `pickPin()` (nearest-pin hit test, radius capped in world units so a pin doesn't swallow box-body clicks at low zoom) and diff --git a/CMakeLists.txt b/CMakeLists.txt index a5a1478..4ebadd7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -354,6 +354,9 @@ if(NOT EMSCRIPTEN_BUILD) ${NAJA_SCHEMATIC_TEST_SOURCES} ) target_link_libraries(naja-schematic-tests PRIVATE gtest_main) + target_compile_definitions(naja-schematic-tests PRIVATE + NAJA_SCHEMATIC_TEST_DATA="${CMAKE_CURRENT_SOURCE_DIR}/tests/data" + ) # LocalSNLProvider against the wire-protocol cases shared with the # Python backend (tests/data/anonymous_protocol_cases.json, also run by diff --git a/README.md b/README.md index e80c804..d56b170 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ plus options, in any order. Their flags differ slightly: | `--liberty a.lib --liberty b.lib` | `--liberty a.lib b.lib` | Liberty cell libraries (Verilog only) | | | `--py-primitives prims.py` | Primitives defined in Python: a `.py` file or module whose `load(db)` builds them (repeatable) | | `--diagnosis report.json` | `--diagnosis report.json` | Show a diagnosis report on the design | -| `--style styles.json` | `--style styles.json` | Color, widen, fill and label nets, instances and pins (`{"items": [...]}`, see `style_response` in [CLAUDE.md](CLAUDE.md)) | +| `--style styles.json` | `--style styles.json` | Color, widen, fill and label nets, instances and pins (see [Style files](#style-files)) | | `--yosys-src` | `--yosys-src` | Read Yosys `(* src *)` attributes, so Show Sources leads back to the RTL (Verilog only) | | `--source-root dir` | `--source-root dir` | Where to look for relative source paths (repeatable) | | `--source-map FROM=TO` | `--source-map FROM=TO` | Rewrite source paths recorded on another machine (repeatable) | @@ -111,6 +111,51 @@ order, then in the current directory. `--source-map /home/ci/flow=/work/flow` finds a file recorded as `/home/ci/flow/rtl/top.v` at `/work/flow/rtl/top.v`. +### Style files + +`--style` reads a JSON file listing what to color, widen, fill or label. +It's kept across reloads and in SVG/PNG exports: + +```json +{"items": [ + {"kind": "net", "target": "en", "color": "#ff7f0e", "width": 3, "label": "en"}, + {"kind": "net", "target": "u_ctrl/en_reg:Q", "color": "#1f77b4", "width": 2.5}, + {"kind": "net", "target": [["u_core", "u_alu"], "A", 3], "color": "#2ca02c"}, + {"kind": "instance", "target": "u_core/u_alu", "fill": "#2ca02c55", "label": "ALU"}, + {"kind": "term", "path": ["u_ctrl", "en_reg"], "terminal": "CE", "color": "#d62728"} +]} +``` + +A bare list of items works too. Each item has: + +- `kind`: `"net"` (every wire of the net through that pin), `"instance"` + (the default; also gate symbols and port flags) or `"term"` (one pin). +- What it styles, either as a `target` or as `path`/`id_path` plus, for a + pin, `terminal`/`term_id` and `bit`: + - an instance: `"u1/u2"`, as `naja-schematic render --instance` takes + it, or a list of names or ids (`["u1", "u2"]`, `[3, 7]`); + - a pin: `"u1/u2:A"`, `"u1/u2:A[3]"`, or `"y"` / `"d[1]"` for a + top-level port, as `--net` takes it; or a list `[instance, terminal]` + / `[instance, terminal, bit]`, the instance as above and `[]` for a + top-level port (`[[], "en"]`); or `{"path": [...], "terminal": "A", + "bit": 3}`. + + Text is matched against the design, so an escaped name containing `/` + or `:` still resolves. If the text could mean more than one object, + the item is refused and you need the list form. `path` is a list of + instance names (`[]` = the top), and `id_path` the same with instance + ids (needed for anonymous instances). +- Any of `color` (`"#rrggbb"` or `"#rrggbbaa"`), `width` (wires and pins, + in SVG pixels at 1x), `fill` (instances; a translucent fill tints the + box) and `label` (replaces the drawn name). + +Items on one object merge in order. A diagnosis color beats a style +color, and a style color beats a trace color. The browser server and +`naja-schematic render` check every item before drawing: one that doesn't +resolve is an error, and nothing is drawn. `target` is resolved by those +Python hosts. The desktop app's `--style` takes `path`/`id_path` and +`terminal`/`bit` only. + ### Headless SVG export The desktop app can draw a schematic to an SVG file without opening a @@ -154,14 +199,36 @@ On the command line they're flags (desktop app, `naja-schematic` server and | Option | Values | | |---|---|---| | `--instance-label` | `name` (default), `model`, `both` | The instance name above a box, its cell model under it, or both | -| `--sink-rows N` | default 8, 0 = no limit | A column with more sinks (boxes driving nothing shown) than this becomes a grid of columns | -| `--max-sinks N` | default 32, 0 = no limit | A net with more sinks draws the first N. The rest go into stacked summary boxes ("DFF ×812"), and clicking one shows its sinks | -| `--group-by` | `model` (default), `hierarchy`, `role` | How sinks are gathered into summaries: by cell model, by the module holding them, or by the pin they're on (clock pins together, other pins by name) | +| `--sink-rows N` | default 8, 0 = no limit | A column with more sinks (boxes driving nothing shown) than this becomes a grid of columns. With several drivers, each driver's sinks get a band of rows level with it, all bands starting in the same column, so no net's wires cross another net's sinks | +| `--max-sinks N` | default 32, applied when not given; `0` turns it off | A net with more sinks draws the first N, in natural name order (`lut_111` before `lut_1037`). The rest go into stacked summary boxes ("DFF ×812"), and clicking one shows its sinks. To draw every sink, pass `--max-sinks 0` (`view_options={"max_sinks": 0}`) | +| `--group-by` | `model` (default), `hierarchy`, `role`, `pin` | How sinks are gathered into summaries: by cell model, by the module holding them, by the role naja gives the pin they're on (`SNLBitTerm.getRole()`: "clock ×812", "reset ×40", "enable ×8", and "data ×165" for pins with a data role or none), or by that pin's name (clock pins together, other pins by name) | +| `--no-convergence-outline` | outline on by default | A box two or more traces go through gets a near-black outline (never a box a style names). This turns it off (View > Outline Trace Convergence, `convergence_outline`) | A net's driver is always drawn as a box. So is an instance that is drawn for another reason: it drives something shown, is selected, has a diagnosis or a style. +These only change exports (SVG and PNG), never the canvas: + +| Option | Values | | +|---|---|---| +| `--title TEXT` | default none | Text in a band above the drawing | +| `--caption TEXT` | default none | Text in a band below the drawing | +| `--legend` | off by default | A color swatch and label below the drawing for each trace, and each net a style labels | +| `--hide-ui-glyphs` | off by default | No hollow stubs on open pins, no "•••" on boxes showing some of their pins | + +An exported SVG is structured, so a script or a page can find what's in it +without reading geometry. Every net is a `` (wires, junction +dots, bus marks, label) with `data-net`, `data-driver` (`u1/u2:Q`, or a +top-level port's name) and `data-driver-id-path`; every box a +`` with `data-path` (`u1/u2`), `data-id-path` (`3,7`) +and `data-model`; every top-level port flag a `` with +`data-name` and `data-direction`; every summary box a +`` with `data-group` and `data-count`; every module +frame a ``. When a name holds `/` or `:` (escaped +Verilog names can) or is empty, `data-path-json`/`data-driver-json` give +the path as JSON too. The groups change nothing in the drawing. + ## Controls The same list is in the app under **Help > Keyboard Shortcuts**. "Ctrl" is diff --git a/REUSE.toml b/REUSE.toml index e6b0ff4..3d7ddba 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -46,6 +46,7 @@ path = [ "python/tests/data/design.v", "python/tests/data/fanout.v", "python/tests/data/wide_fanout.v", + "python/tests/data/role_fanout.v", "python/tests/data/py_design.v", "python/tests/data/py_prims.py", "python/tests/test_design_generations.py", @@ -156,6 +157,7 @@ path = [ "tests/StyleStoreTest.cpp", "tests/RasterTest.cpp", "tests/FanoutTest.cpp", + "tests/SvgExportTest.cpp", "tests/SchematicLayoutTest.cpp", "tests/SourceStoreTest.cpp", "tests/TraceTest.cpp", @@ -163,6 +165,8 @@ path = [ "tests/VerilogLanguageTest.cpp", "tests/data/anonymous_protocol_cases.json", "tests/data/source_protocol_cases.json", + "tests/data/role_protocol_cases.json", + "tests/data/export_golden.svg", "tests/data/sv/gates.sv", "tests/data/sv/operators.sv", "tests/data/sv/two_tops.sv", diff --git a/python/README.md b/python/README.md index 81aa1d5..e053098 100644 --- a/python/README.md +++ b/python/README.md @@ -45,18 +45,45 @@ view Nets, instances and pins can also be styled -- a color and width for a net's wires, a fill for a box, labels -- kept across reloads and in SVG exports. A `"net"` item colors the whole net through the pin it names; -`"target"` takes anything `show_instance()`/`show_net()` take: +`"target"` takes anything `show_instance()`/`show_net()` take, and also +the text forms of `naja-schematic render`'s `--instance`/`--net` +(`"u1/u2"`, `"drv_0:O"`, `"en"` for a top-level port): ```python view.style([ {"kind": "net", "target": ([], "en"), "color": "#ff7f0e", "width": 3, "label": "en"}, - {"kind": "net", "target": (["drv_0"], "O"), "color": "#1f77b4"}, + {"kind": "net", "target": "drv_0:O", "color": "#1f77b4"}, {"kind": "instance", "target": ["s0"], "fill": "#1f77b455"}, # a tint ]) ``` Diagnosis colors win over styles, and styles over trace colors. +The same items, in a JSON file, are what `--style FILE` reads (on +`naja-schematic` and `naja-schematic render`). JSON has no tuples: a pin +there is text, a list `[instance, terminal]` / `[instance, terminal, +bit]` (`[]` = a top-level port), or `{"path": [...], "terminal": ..., +"bit": ...}`: + +```json +{"items": [ + {"kind": "net", "target": [[], "en"], "color": "#ff7f0e", "width": 3, "label": "en"}, + {"kind": "net", "target": "drv_0:O", "color": "#1f77b4", "width": 2.5}, + {"kind": "net", "target": [["u_core", "u_alu"], "A", 3], "color": "#2ca02c"}, + {"kind": "instance", "target": "u_core/u_alu", "fill": "#2ca02c55", "label": "ALU"}, + {"kind": "term", "path": ["s0"], "terminal": "CE", "color": "#d62728"} +]} +``` + +`kind` is `"net"`, `"instance"` (the default) or `"term"`. Instead of +`target`, an item can give `path` (instance names, `[]` = the top) or +`id_path` (instance ids), plus `terminal`/`term_id` and `bit` for a pin. +The style fields are `color` (`"#rrggbb"`/`"#rrggbbaa"`), `width`, +`fill` and `label`. Text is matched against the design. Text that names +nothing, or more than one object, is an error. So is any item that +doesn't resolve, and then nothing is drawn. See [Style +files](../README.md#style-files) for details. + The view and your najaeda code can point each other at instances. `show_instance()` takes a najaeda `Instance` or a naja `SNLPath`, a list of instance ids (as `Instance.pathIDs`) or a list of instance names (a plain string is one @@ -129,6 +156,12 @@ naja_schematic.export_svg( view_options={"instance_label": "both", # name above each box, cell model under it "max_sinks": 16, "group_by": "model"}, # a net's sinks past 16: "DFF x812" ) +naja_schematic.export_svg( + traces=[(["u1"], "D")], path="report.svg", + title="Fan-in of u1/D", caption="after the edit", # bands above / below the drawing + legend=True, # a swatch per trace and labeled net + hide_ui_glyphs=True, # no open-pin stubs or "more pins" dots +) svgs = naja_schematic.export_svgs([ # several drawings, one renderer {"instances": [["u1", "u2"]], "path": "u2.svg"}, {"traces": [(["u3"], "A", 0)], "path": "u3_a0.svg"}, @@ -149,7 +182,10 @@ naja-schematic render --verilog design.v --py-primitives prims.py --top top \ ``` `view_options` (and the flags `--instance-label`, `--sink-rows`, -`--max-sinks`, `--group-by`) set how the schematic is drawn: see +`--max-sinks`, `--group-by`; for exports only, `--title`, `--caption`, +`--legend`, `--hide-ui-glyphs`, also `export_svg()`/`export_png()` +keywords) set how the schematic is drawn, and the SVG's `` groups +name every net, instance and port in it: see [How the schematic is drawn](../README.md#how-the-schematic-is-drawn). In a notebook they're `show(view_options=...)` / `view.view_options(...)`, and on a server `ViewerServer(view_options=...)`, the same flags on diff --git a/python/naja_schematic/__init__.py b/python/naja_schematic/__init__.py index 66c6972..053a8c2 100644 --- a/python/naja_schematic/__init__.py +++ b/python/naja_schematic/__init__.py @@ -13,7 +13,7 @@ """ # Single version for the whole project: CMakeLists.txt reads this line into the # C++ app too (NAJA_SCHEMATIC_VERSION_STRING), so keep it a plain literal. -__version__ = "0.2.1" +__version__ = "0.3.0" from .protocol import diagnosis_response, handle_request from .render import RenderError, export_png, export_svg, export_svgs diff --git a/python/naja_schematic/protocol.py b/python/naja_schematic/protocol.py index 7950a00..882040d 100644 --- a/python/naja_schematic/protocol.py +++ b/python/naja_schematic/protocol.py @@ -117,10 +117,49 @@ def output_bit_count(model): return sum(1 for term in model.getBitTerms() if term.getDirection() != naja.SNLTerm.Direction.Input) -def with_clock(entry, term): - # Only sent when set: marks a flip-flop's clock pin (see drawDffInstance). +# naja's term roles (SNLDesignModeling::SNLTermRole), as sent in "role". +# Kept in step with termRoleName() in LocalSNLProvider.cpp. +_TERM_ROLE_NAMES = { + "Clock": "clock", "AsyncReset": "async_reset", "AsyncSet": "async_set", + "SyncReset": "sync_reset", "SyncSet": "sync_set", "Enable": "enable", + "MemoryReadAddress": "memory_read_address", "MemoryReadData": "memory_read_data", + "MemoryWriteAddress": "memory_write_address", "MemoryWriteData": "memory_write_data", + "MemoryWriteEnable": "memory_write_enable", "ScanInput": "scan_input", + "ScanEnable": "scan_enable", + # DataInput, DataOutput and Other (unset) are data: no "role". +} + + +@functools.lru_cache(maxsize=None) +def _term_role_names(): + names = {} + for attr, name in _TERM_ROLE_NAMES.items(): + value = getattr(naja.SNLTermRole, attr, None) + if value is not None: + names[int(value)] = name + return names + + +def term_role(term): + """The pin's naja role (SNLBitTerm/SNLInstTerm.getRole()) as sent in + "role" ("clock", "async_reset", "enable", ...), or None for a data pin + (DataInput, DataOutput, or no role set). An SNLInstTerm also sees the + roles a parameterized primitive takes from its instance's parameters.""" + get_role = getattr(term, "getRole", None) + if get_role is None: + return None + return _term_role_names().get(int(get_role())) + + +def with_clock(entry, term, inst_term=None): + # Only sent when set: "clock" marks a flip-flop's clock pin (see + # drawDffInstance), "role" a pin naja gives a non-data role (fanout + # summaries grouped by role). if term.isClock(): entry["clock"] = True + role = term_role(inst_term if inst_term is not None else term) + if role is not None: + entry["role"] = role return entry def is_anonymous_constant_net(net): @@ -392,7 +431,7 @@ def equipotential_to_json(equipotential, sinks=None): # Net on this inst term inside the instance's parent design -- # shown in the schematic's pin hover tooltip. "net": net_display_name(instTerm.getNet()) - }, term), has_sources(instTerm.getInstance(), inst_model))) + }, term, instTerm), has_sources(instTerm.getInstance(), inst_model))) for term in equipotential.getTerms(): # A top-level output is a receiver of the net; an input/inout drives it. if (sinks is not None @@ -1285,10 +1324,14 @@ def export_png(scale=1.0): INSTANCE_LABELS = ("name", "model", "both") -FANOUT_GROUP_BY = ("model", "hierarchy", "role") +FANOUT_GROUP_BY = ("model", "hierarchy", "role", "pin") # What a viewer draws with until told otherwise (ViewOptions in the C++). DEFAULT_VIEW_OPTIONS = {"instance_label": "name", "sink_rows": 8, "max_sinks": 32, - "group_by": "model"} + "group_by": "model", "convergence_outline": True, + "hide_ui_glyphs": False, "title": "", + "caption": "", "legend": False} +# The keys only exported drawings (SVG, PNG) show, never the canvas. +EXPORT_DECORATIONS = ("hide_ui_glyphs", "title", "caption", "legend") def view_options(options=None, **kwargs): @@ -1302,12 +1345,30 @@ def view_options(options=None, **kwargs): driven by) than this is wrapped into a grid of columns (default 8; 0: never); - "max_sinks": a net with more instance sinks than this draws the first - ones and gathers the rest into summary boxes ("DFF x812") that expand - when clicked; its driver, and a sink shown for another reason, are - always drawn (default 32; 0: never); + ones (in natural name order) and gathers the rest into summary boxes + ("DFF x812") that expand when clicked; its driver, and a sink shown + for another reason, are always drawn (default 32, applied when not + given; 0 turns summaries off: every sink drawn); - "group_by": how the gathered sinks are grouped: "model" (the - default), "hierarchy" (the module holding them) or "role" (the - receiving pin: clock pins together, others by name). + default), "hierarchy" (the module holding them), "role" (the + receiving pin's naja role, SNLBitTerm.getRole(): "clock x812", + "reset x40", "enable x8", "data x165" for the rest) or "pin" (the + receiving pin's name, clock pins together); + - "convergence_outline": a box two or more visible traces go through + is outlined in near-black (default True; never a box a style + names); False draws no such outline. + + And the export decorations, shown only in exported drawings (SVG and + PNG, never on the canvas): + + - "title" / "caption": text in a band above / below the drawing + ("" = none, the default; "\\n" breaks lines); + - "legend": True adds a swatch and label below the drawing for each + visible trace (show_net(), Trace to Driver) and each net a style + labels (default False); + - "hide_ui_glyphs": True leaves out what only means something to a + viewer's user: the "more pins" dots of a partial box and the hollow + stubs of open pins (default False). Keys left out (or None) keep the viewer's current value. Raises ValueError for a bad value, TypeError for an unknown key.""" @@ -1328,6 +1389,10 @@ def view_options(options=None, **kwargs): if key in ("sink_rows", "max_sinks") and ( isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 1000000): raise ValueError(f"{key}: expected a count (0 = no limit), got {value!r}") + if key in ("hide_ui_glyphs", "legend", "convergence_outline") and not isinstance(value, bool): + raise ValueError(f"{key}: expected True or False, got {value!r}") + if key in ("title", "caption") and not isinstance(value, str): + raise ValueError(f"{key}: expected a string, got {value!r}") message[key] = value return message diff --git a/python/naja_schematic/render.py b/python/naja_schematic/render.py index f27cd25..4a25151 100644 --- a/python/naja_schematic/render.py +++ b/python/naja_schematic/render.py @@ -283,13 +283,24 @@ def _render(self, pushes): return outputs +def _with_decorations(view_options, title, caption, legend, hide_ui_glyphs): + """`view_options` with the export decorations given as arguments (None: + not given) over it.""" + given = {key: value for key, value in (("title", title), ("caption", caption), + ("legend", legend), + ("hide_ui_glyphs", hide_ui_glyphs)) + if value is not None} + return {**(view_options or {}), **given} if given else view_options + + def _write_svg(path, svg): # newline="": the same bytes on every platform (no CRLF on Windows). Path(path).write_text(svg, encoding="utf-8", newline="") def export_svg(targets=None, path=None, *, nets=None, instances=None, traces=None, - style=None, view_options=None, timeout=DEFAULT_TIMEOUT, source_roots=(), + style=None, view_options=None, title=None, caption=None, legend=None, + hide_ui_glyphs=None, timeout=DEFAULT_TIMEOUT, source_roots=(), source_maps=()): """Draw part of the design in the current NLUniverse as an SVG schematic, with no browser or display; returns the SVG, also written to @@ -322,13 +333,33 @@ def export_svg(targets=None, path=None, *, nets=None, instances=None, traces=Non cell's model under its box, {"max_sinks": 16, "group_by": "model"} gathers a net's sinks past the 16th into summary boxes. + `title` and `caption` put text in a band above / below the drawing, + `legend=True` a swatch and label below it for each trace and each net + a style labels, `hide_ui_glyphs=True` leaves out the open-pin stubs + and "more pins" dots, which mean something only in a viewer: the + view_options keys of the same names (protocol.view_options()), given + here for short. + + The SVG is structured: each drawn net is a (its + wires, junction dots, bus marks and label) with data-net, data-driver + ("u1/u2:Q", or a top-level port's name), data-driver-id-path ("3,7") + and data-label (a style label); each box a with + data-path ("u1/u2"), data-id-path and data-model; each top-level port + flag a with data-name and data-direction; each + fanout summary a with data-group and data-count; + each module frame a . When a name makes the text + path ambiguous (it holds "/" or ":", or is anonymous), data-path-json + / data-driver-json give it as JSON as well. + Raises ValueError (TypeError for an unsupported kind) when a target doesn't resolve -- nothing is drawn then -- and RenderError when there is no renderer, nothing to draw, or the drawing takes more than `timeout` seconds. `source_roots`/`source_maps` are as for ViewerSession (they don't change the drawing).""" pushes = drawing_pushes(targets, nets=nets, instances=instances, traces=traces, - style=style, view_options=view_options) + style=style, + view_options=_with_decorations(view_options, title, caption, + legend, hide_ui_glyphs)) with Renderer(source_roots, source_maps) as renderer: svg = renderer.render(pushes, timeout) if path is not None: @@ -337,17 +368,21 @@ def export_svg(targets=None, path=None, *, nets=None, instances=None, traces=Non def export_png(targets=None, path=None, *, scale=1.0, nets=None, instances=None, - traces=None, style=None, view_options=None, timeout=DEFAULT_TIMEOUT, + traces=None, style=None, view_options=None, title=None, caption=None, + legend=None, hide_ui_glyphs=None, timeout=DEFAULT_TIMEOUT, source_roots=(), source_maps=()): """export_svg()'s drawing as a PNG image: returns its bytes, also written to `path` when given. `scale` is the number of pixels per SVG pixel (0 < scale <= 64): text, strokes and shapes are drawn at that resolution, not enlarged, over a white background. The other - arguments are export_svg()'s. Raises RenderError also when the image - would be over 120 million pixels.""" + arguments are export_svg()'s (title, caption and legend drawn the same + way). Raises RenderError also when the image would be over 120 million + pixels.""" pushes = drawing_pushes(targets, nets=nets, instances=instances, traces=traces, - style=style, view_options=view_options, svg=False, - png_scale=scale) + style=style, + view_options=_with_decorations(view_options, title, caption, + legend, hide_ui_glyphs), + svg=False, png_scale=scale) with Renderer(source_roots, source_maps) as renderer: png = renderer.render_outputs(pushes, timeout)["png"] if path is not None: @@ -359,11 +394,12 @@ def export_svgs(jobs, *, timeout=DEFAULT_TIMEOUT, source_roots=(), source_maps=( """Several export_svg() drawings with one renderer process; returns their SVGs, in order. Each job is a dict of export_svg()'s arguments: "targets", "path", "nets", "instances", "traces", "style", - "view_options". Every job is + "view_options", "title", "caption", "legend", "hide_ui_glyphs". Every job is resolved before anything is drawn, and files are written only once all are drawn: a bad target raises without writing any. `timeout` applies to each drawing.""" - keys = {"targets", "path", "nets", "instances", "traces", "style", "view_options"} + keys = {"targets", "path", "nets", "instances", "traces", "style", "view_options", + *protocol.EXPORT_DECORATIONS} plans = [] for i, job in enumerate(jobs): if not isinstance(job, dict): @@ -376,7 +412,10 @@ def export_svgs(jobs, *, timeout=DEFAULT_TIMEOUT, source_roots=(), source_maps=( pushes = drawing_pushes(job.get("targets"), nets=job.get("nets"), instances=job.get("instances"), traces=job.get("traces"), style=job.get("style"), - view_options=job.get("view_options")) + view_options=_with_decorations( + job.get("view_options"), job.get("title"), + job.get("caption"), job.get("legend"), + job.get("hide_ui_glyphs"))) except (ValueError, TypeError, RenderError) as e: raise type(e)(f"job {i}: {e}") from e plans.append((job.get("path"), pushes)) @@ -546,7 +585,10 @@ def build_arg_parser(): parser.add_argument("--style", metavar="FILE", help="Style JSON ({\"items\": [...]} or a bare array: colors, " "widths, fills, labels on nets, instances and pins) drawn " - "into the SVG") + "into the SVG. An item names its object by " + "\"target\": --instance/--net text (\"u1/u2\", \"u1:A[3]\", " + "\"y\") or a [path, terminal(, bit)] list; or by " + "\"path\"/\"id_path\" (+ \"terminal\", \"bit\")") parser.add_argument("--verbose", "-v", action="store_true", help="Log to stderr") add_view_arguments(parser) add_design_arguments(parser) diff --git a/python/naja_schematic/server.py b/python/naja_schematic/server.py index 39a0421..58aa548 100644 --- a/python/naja_schematic/server.py +++ b/python/naja_schematic/server.py @@ -298,7 +298,8 @@ def view_options(self, options=None, **kwargs): """Set how every connected viewer, and any that (re)loads later, draws the schematic: "instance_label" ("name", "model", "both"), "sink_rows", "max_sinks", "group_by" ("model", "hierarchy", - "role"); see naja_schematic.protocol.view_options(). Keys not given + "role", "pin"), "convergence_outline"; see + naja_schematic.protocol.view_options(). Keys not given keep their value.""" self._session.view_options(options, **kwargs) @@ -581,17 +582,36 @@ def add_view_arguments(parser): help="Wrap a column of more than N sinks into a grid (default 8; " "0: never)") group.add_argument("--max-sinks", type=int, metavar="N", - help="Draw the first N sinks of a net and gather the others into " - "summary boxes that expand when clicked (default 32; 0: never)") + help="Draw the first N sinks of a net (in natural name order) and " + "gather the others into summary boxes that expand when clicked. " + "Default 32, applied when this flag is not given; 0 turns " + "summaries off (every sink drawn)") group.add_argument("--group-by", choices=FANOUT_GROUP_BY, help="How gathered sinks are grouped: by cell model (default), by " - "the module holding them, or by receiving pin (role)") + "the module holding them, by the receiving pin's naja role " + "(clock, reset, set, enable, scan, address, else data), or by " + "the receiving pin's name (pin; clock pins together)") + group.add_argument("--no-convergence-outline", dest="convergence_outline", + action="store_false", default=None, + help="Don't outline a box two or more traces go through in " + "near-black (a box a style names never is)") + group.add_argument("--title", metavar="TEXT", + help="Exports only: text in a band above the drawing") + group.add_argument("--caption", metavar="TEXT", + help="Exports only: text in a band below the drawing") + group.add_argument("--legend", action="store_true", default=None, + help="Exports only: a swatch and label for each trace and each " + "net a style labels, below the drawing") + group.add_argument("--hide-ui-glyphs", action="store_true", default=None, + help="Exports only: no open-pin stubs and no 'more pins' dots") def view_options_from_args(args): """The view options add_view_arguments()'s flags set (None: none).""" options = {key: getattr(args, key) for key in - ("instance_label", "sink_rows", "max_sinks", "group_by") + ("instance_label", "sink_rows", "max_sinks", "group_by", "convergence_outline", + "hide_ui_glyphs", + "title", "caption", "legend") if getattr(args, key, None) is not None} if not options: return None @@ -632,7 +652,10 @@ def build_arg_parser(): parser.add_argument("--style", metavar="FILE", help="Style JSON ({\"items\": [...]} or a bare array: colors, " "widths, fills, labels on nets, instances and pins) to push " - "to the viewer after the design loads") + "to the viewer after the design loads. An item names its object by " + "\"target\": --instance/--net text (\"u1/u2\", \"u1:A[3]\", " + "\"y\") or a [path, terminal(, bit)] list; or by " + "\"path\"/\"id_path\" (+ \"terminal\", \"bit\")") parser.add_argument("--source-root", action="append", default=[], metavar="DIR", dest="source_roots", help="Directory to look up relative source file references in " diff --git a/python/naja_schematic/session.py b/python/naja_schematic/session.py index 76c7ac8..9e2f2d4 100644 --- a/python/naja_schematic/session.py +++ b/python/naja_schematic/session.py @@ -325,6 +325,37 @@ def _net_driver_pin(ids, term, bit, what): occ.getInstTerm().getBitTerm()) +def style_target(kind, target): + """A style item's "target" turned into its address keys ("path", + "id_path", and for a pin "term_id", "bit"). `kind` "instance" takes an + instance as show_instance() does, or text as `naja-schematic render + --instance` ("u1/u2", or JSON text). "net"/"term" take a pin as + show_net() does, or text as --net ("u1/u2:A", "en_reg:O", "d[1]" for a + bit of a top-level bus), a list [instance, terminal(, bit)] -- the + instance as show_instance() takes it, [] for a top-level port -- or an + object {"id_path"|"path": instance, "terminal": name, "bit": n}. Text + is matched against the design, never split blindly (render.py's + _instances_matching()): ambiguous text raises ValueError.""" + from . import render # (render imports this module) + if kind == "instance": + if isinstance(target, str): + ids = render.parse_instance_arg(target) + return {"path": ids_to_names(ids), "id_path": ids} + names, ids = instance_paths(target) + return {"path": names, "id_path": ids} + if isinstance(target, str): + target = render.parse_pin_arg(target) + elif isinstance(target, dict): + target = render.parse_pin_arg(json.dumps(target)) + elif isinstance(target, list) and len(target) in (2, 3) and isinstance(target[1], (str, int)): + target = tuple(target) + pin = net_pin(target) + address = {"path": pin["path"], "id_path": pin["id_path"], "term_id": pin["term_id"]} + if pin["bit"] is not None: + address["bit"] = pin["bit"] + return address + + def style_response(items): """protocol.style_response() for the design in the current NLUniverse, with every item resolved here, so a bad one raises ValueError instead @@ -333,6 +364,12 @@ def style_response(items): - an item may name its object by "target" instead of "path"/"id_path" (and, for a pin, "terminal"/"term_id"/"bit"): an instance as show_instance() takes it, or a pin as show_net() does (one bit); + or, as in a style JSON file, the text forms of `naja-schematic + render`'s --instance ("u1/u2") and --net ("u1/u2:A[3]", "en_reg:O", + "y" for a top-level port), matched against the design, or a pin as + a list [instance, terminal] / [instance, terminal, bit] (the JSON + spelling of show_net()'s tuple; [] = a top-level port) or an object + {"id_path"|"path", "terminal", "bit"} (see style_target()); - a "net" item is sent once per bit (a bus pin without "bit": every bit), each on its net's driver -- a top-level port, else an output leaf pin -- the pin the viewer draws whatever part of the net it @@ -350,14 +387,10 @@ def style_response(items): target = item.pop("target") for key in ("path", "id_path", "terminal", "term_id", "bit"): item.pop(key, None) - if kind == "instance": - names, ids = instance_paths(target) - item.update(path=names, id_path=ids) - else: - pin = net_pin(target) - item.update(path=pin["path"], id_path=pin["id_path"], term_id=pin["term_id"]) - if pin["bit"] is not None: - item["bit"] = pin["bit"] + try: + item.update(style_target(kind, target)) + except (TypeError, ValueError) as e: + raise type(e)(f"{what}: target {target!r}: {e}") from None item = protocol.style_response([item])["items"][0] # checked, normalized if kind == "instance": if "id_path" in item: diff --git a/python/naja_schematic/widget.py b/python/naja_schematic/widget.py index c495224..9068a75 100644 --- a/python/naja_schematic/widget.py +++ b/python/naja_schematic/widget.py @@ -122,11 +122,15 @@ def view_options(self, options=None, **kwargs): cell model under it) or "both"; - sink_rows: a column of more sinks than this becomes a grid (default 8; 0: never); - - max_sinks: a net with more sinks draws the first ones and gathers - the rest into summary boxes, which expand when clicked (default - 32; 0: never). Its driver is always drawn; + - max_sinks: a net with more sinks draws the first ones (natural + name order) and gathers the rest into summary boxes, which + expand when clicked (default 32, applied when not given; 0 + turns summaries off). Its driver is always drawn; - group_by: how sinks are gathered: "model" (the default), - "hierarchy" or "role" (the receiving pin). + "hierarchy", "role" (the receiving pin's naja role: clock, + reset, enable, ..., data) or "pin" (the receiving pin's name); + - convergence_outline: False drops the near-black outline of a + box two traces go through (default True). Kept in SVG exports.""" self._session.view_options(options, **kwargs) diff --git a/python/tests/data/py_prims.py b/python/tests/data/py_prims.py index 521e248..cc5bf57 100644 --- a/python/tests/data/py_prims.py +++ b/python/tests/data/py_prims.py @@ -23,3 +23,19 @@ def load(db): q = naja.SNLScalarTerm.create(dff, OUTPUT, "Q") naja.SNLDesign.addClockToOutputsArcs(c, [q]) naja.SNLDesign.addInputsToClockArcs([d], c) + + # A flop whose clock, reset and enable pins naja knows by their term + # role (SNLBitTerm.setRole()), not by their names: group_by "role". + ffre = naja.SNLDesign.createPrimitive(lib, "PY_FFRE") + fd = naja.SNLScalarTerm.create(ffre, INPUT, "D") + fc = naja.SNLScalarTerm.create(ffre, INPUT, "CK") + fr = naja.SNLScalarTerm.create(ffre, INPUT, "R") + fl = naja.SNLScalarTerm.create(ffre, INPUT, "L") + fq = naja.SNLScalarTerm.create(ffre, OUTPUT, "Q") + naja.SNLDesign.addClockToOutputsArcs(fc, [fq]) + naja.SNLDesign.addInputsToClockArcs([fd, fr, fl], fc) + fc.setRole(naja.SNLTermRole.Clock) + fd.setRole(naja.SNLTermRole.DataInput) + fr.setRole(naja.SNLTermRole.AsyncReset, naja.SNLActiveLevel.Low) + fl.setRole(naja.SNLTermRole.Enable) + fq.setRole(naja.SNLTermRole.DataOutput) diff --git a/python/tests/data/role_fanout.v b/python/tests/data/role_fanout.v new file mode 100644 index 0000000..f386043 --- /dev/null +++ b/python/tests/data/role_fanout.v @@ -0,0 +1,40 @@ +// One net driving the clock, reset, enable and data pins of PY_FFRE flops +// (and PY_AND2 inputs): the fanout summaries of group_by "role". +module top(input a, input b, output [29:0] q, output [3:0] y); + wire n; + PY_AND2 drv (.A(a), .B(b), .Y(n)); + PY_FFRE f0 (.D(a), .CK(n), .R(b), .L(b), .Q(q[0])); + PY_FFRE f1 (.D(a), .CK(n), .R(b), .L(b), .Q(q[1])); + PY_FFRE f2 (.D(a), .CK(n), .R(b), .L(b), .Q(q[2])); + PY_FFRE f3 (.D(a), .CK(n), .R(b), .L(b), .Q(q[3])); + PY_FFRE f4 (.D(a), .CK(n), .R(b), .L(b), .Q(q[4])); + PY_FFRE f5 (.D(a), .CK(n), .R(b), .L(b), .Q(q[5])); + PY_FFRE f6 (.D(a), .CK(n), .R(b), .L(b), .Q(q[6])); + PY_FFRE f7 (.D(a), .CK(n), .R(b), .L(b), .Q(q[7])); + PY_FFRE f8 (.D(a), .CK(n), .R(b), .L(b), .Q(q[8])); + PY_FFRE f9 (.D(a), .CK(n), .R(b), .L(b), .Q(q[9])); + PY_FFRE f10 (.D(a), .CK(n), .R(b), .L(b), .Q(q[10])); + PY_FFRE f11 (.D(a), .CK(n), .R(b), .L(b), .Q(q[11])); + PY_FFRE f12 (.D(a), .CK(b), .R(n), .L(b), .Q(q[12])); + PY_FFRE f13 (.D(a), .CK(b), .R(n), .L(b), .Q(q[13])); + PY_FFRE f14 (.D(a), .CK(b), .R(n), .L(b), .Q(q[14])); + PY_FFRE f15 (.D(a), .CK(b), .R(n), .L(b), .Q(q[15])); + PY_FFRE f16 (.D(a), .CK(b), .R(n), .L(b), .Q(q[16])); + PY_FFRE f17 (.D(a), .CK(b), .R(n), .L(b), .Q(q[17])); + PY_FFRE f18 (.D(a), .CK(b), .R(b), .L(n), .Q(q[18])); + PY_FFRE f19 (.D(a), .CK(b), .R(b), .L(n), .Q(q[19])); + PY_FFRE f20 (.D(a), .CK(b), .R(b), .L(n), .Q(q[20])); + PY_FFRE f21 (.D(a), .CK(b), .R(b), .L(n), .Q(q[21])); + PY_FFRE f22 (.D(a), .CK(b), .R(b), .L(n), .Q(q[22])); + PY_FFRE f23 (.D(n), .CK(b), .R(b), .L(b), .Q(q[23])); + PY_FFRE f24 (.D(n), .CK(b), .R(b), .L(b), .Q(q[24])); + PY_FFRE f25 (.D(n), .CK(b), .R(b), .L(b), .Q(q[25])); + PY_FFRE f26 (.D(n), .CK(b), .R(b), .L(b), .Q(q[26])); + PY_FFRE f27 (.D(n), .CK(b), .R(b), .L(b), .Q(q[27])); + PY_FFRE f28 (.D(n), .CK(b), .R(b), .L(b), .Q(q[28])); + PY_FFRE f29 (.D(n), .CK(b), .R(b), .L(b), .Q(q[29])); + PY_AND2 g0 (.A(n), .B(a), .Y(y[0])); + PY_AND2 g1 (.A(n), .B(a), .Y(y[1])); + PY_AND2 g2 (.A(n), .B(a), .Y(y[2])); + PY_AND2 g3 (.A(n), .B(a), .Y(y[3])); +endmodule diff --git a/python/tests/protocol_cases.py b/python/tests/protocol_cases.py index 740868b..bb5061e 100644 --- a/python/tests/protocol_cases.py +++ b/python/tests/protocol_cases.py @@ -30,6 +30,12 @@ def _create_terms(design, terms): naja.SNLScalarTerm.create(design, _DIRECTIONS[term[1]], term[0]) +_ROLES = {"clock": "Clock", "data_input": "DataInput", "data_output": "DataOutput", + "async_reset": "AsyncReset", "async_set": "AsyncSet", "sync_reset": "SyncReset", + "sync_set": "SyncSet", "enable": "Enable", "scan_input": "ScanInput", + "scan_enable": "ScanEnable", "memory_write_enable": "MemoryWriteEnable"} + + def build_design(spec): """Build the spec'd netlist with the raw naja API in a DB of its own; returns {design name: design}. Instances are created in list order, so @@ -41,6 +47,8 @@ def build_design(spec): for p in spec["primitives"]: d = naja.SNLDesign.createPrimitive(prims, p["name"]) _create_terms(d, p["terms"]) + for term, role in p.get("roles", {}).items(): + d.getScalarTerm(term).setRole(getattr(naja.SNLTermRole, _ROLES[role])) designs[p["name"]] = d lib = naja.NLLibrary.create(db, "case_work") for spec_d in spec["designs"]: @@ -126,6 +134,10 @@ def matches(expected, actual, where="reply"): if not isinstance(actual, dict): return f"{where}: expected an object, got {actual!r}" for key, value in expected.items(): + if value == "$absent": + if key in actual: + return f"{where}: unexpected {key!r} in {actual!r}" + continue if key not in actual: return f"{where}: missing {key!r}" if (err := matches(value, actual[key], f"{where}.{key}")): diff --git a/python/tests/test_render.py b/python/tests/test_render.py index 68d1ba5..b86f510 100644 --- a/python/tests/test_render.py +++ b/python/tests/test_render.py @@ -15,6 +15,8 @@ from naja_schematic import RenderError, export_png, export_svg, export_svgs from naja_schematic import protocol, render +from najaeda import naja +from protocol_cases import build_design, check_case, load_spec, substitute DATA = Path(__file__).parent / "data" @@ -182,6 +184,102 @@ def test_instance_labels(top): assert "FDRE" in model and "r" not in model +# -- SVG structure and export decorations ------------------------------------------ + +def _groups(svg, cls): + import xml.etree.ElementTree as ET + ns = "{http://www.w3.org/2000/svg}" + root = ET.fromstring(svg.encode("utf-8")) # well-formed XML, or this raises + return [g for g in root.iter(ns + "g") if g.get("class") == cls] + + +def _group_texts(g): + return {t.text for t in g.iter("{http://www.w3.org/2000/svg}text")} + + +@needs_renderer +def test_svg_groups_name_every_net_instance_and_port(top): + svg = export_svg(["r"], traces=[(["r"], "D")], nets=[([], "clk")]) + instances = {g.get("data-path"): g for g in _groups(svg, "instance")} + # The flop and the LUT the cone crosses, by path, ids and model. + assert {"r", "u_sub/u_and"} <= set(instances) + r = instances["r"] + assert r.get("data-id-path") == ",".join(map(str, render.parse_instance_arg("r"))) + assert r.get("data-model") == "FDRE" + assert "r" in _group_texts(r) and "D" in _group_texts(r) # its name and pins + lut = instances["u_sub/u_and"] + assert lut.get("data-id-path") == ",".join(map(str, render.parse_instance_arg("u_sub/u_and"))) + assert lut.get("data-model") == "LUT2" + assert lut.get("data-path-json") is None # plain names: no JSON needed + # The module frame around the LUT. + assert "u_sub" in {g.get("data-path") for g in _groups(svg, "module")} + + # Every top-level port flag drawn. + ports = {g.get("data-name"): g.get("data-direction") for g in _groups(svg, "port")} + assert ports.get("clk") == "input" and {"d[0]", "d[1]"} <= set(ports), ports + + # Every net is a group naming its driver, holding its wires. + nets = _groups(svg, "net") + assert nets and all(g.get("data-driver") for g in nets) + drivers = {g.get("data-driver"): g for g in nets} + assert "clk" in drivers # a top-level port + assert "u_sub/u_and:O" in drivers # an instance pin + assert drivers["u_sub/u_and:O"].get("data-driver-id-path") == \ + lut.get("data-id-path") + assert all(any(e.tag.endswith(("line", "polyline")) for e in g.iter()) for g in nets) + + +@needs_renderer +def test_export_decorations(top, tmp_path): + import math + plain = export_svg(["r"], nets=[([], "clk")]) + assert not _groups(plain, "title") and not _groups(plain, "legend") + decorated = export_svg(["r"], nets=[([], "clk")], title="Clock of r", + caption="line 1\nline 2", legend=True) + assert _group_texts(_groups(decorated, "title")[0]) == {"Clock of r"} + assert _group_texts(_groups(decorated, "caption")[0]) == {"line 1", "line 2"} + entries = [g.get("data-label") for g in _groups(decorated, "legend-entry")] + assert entries == ["clk (net)"], entries + assert _svg_size(decorated)[1] > _svg_size(plain)[1] + 30 + # The drawing itself is the same: same groups. + for cls in ("net", "instance", "port"): + assert len(_groups(decorated, cls)) == len(_groups(plain, cls)) + # The PNG has the same page. + png = export_png(["r"], nets=[([], "clk")], title="Clock of r", caption="line 1\nline 2", + legend=True) + w, h = _svg_size(decorated) + assert _png_size(png) == (math.ceil(w), math.ceil(h)) + # hide_ui_glyphs: r's open pins lose their stubs. + hidden = export_svg(["r"], nets=[([], "clk")], hide_ui_glyphs=True) + def circles(svg): + return sum(1 for g in _groups(svg, "instance") for e in g.iter() if e.tag.endswith("circle")) + assert circles(hidden) == 0 < circles(plain) + # export_svgs takes them per job. + svgs = export_svgs([{"instances": ["r"], "title": "A"}, {"instances": ["r"]}]) + assert _groups(svgs[0], "title") and not _groups(svgs[1], "title") + + +def test_decoration_view_options(): + message = protocol.view_options(title="T", caption="", legend=True, hide_ui_glyphs=False) + assert message == {"response": "view_options", "title": "T", "caption": "", "legend": True, + "hide_ui_glyphs": False} + for bad in ({"legend": "yes"}, {"hide_ui_glyphs": 1}, {"title": 3}): + with pytest.raises(ValueError): + protocol.view_options(bad) + assert set(protocol.EXPORT_DECORATIONS) <= set(protocol.DEFAULT_VIEW_OPTIONS) + + +def test_decoration_flags(): + from naja_schematic.server import add_view_arguments, view_options_from_args + import argparse + parser = argparse.ArgumentParser() + add_view_arguments(parser) + assert view_options_from_args(parser.parse_args([])) is None + args = parser.parse_args(["--title", "T", "--caption", "C", "--legend", "--hide-ui-glyphs"]) + assert view_options_from_args(args) == {"title": "T", "caption": "C", "legend": True, + "hide_ui_glyphs": True} + + def test_session_keeps_view_options_across_reloads(top): from naja_schematic.session import ViewerSession sent = [] @@ -271,11 +369,12 @@ def test_render_cli_gathers_a_wide_fanout(tmp_path): assert result.returncode == 0, result.stderr svg = svg_out.read_text(encoding="utf-8") texts = _texts(svg) - # The driver, the first 8 sinks, and the other 38 in two summaries - # (the 6 LUTs are past the first 8 too): by model, the default. - assert {"drv", "LUT1"} <= texts - assert "FDRE \u00d732" in texts and "LUT1 \u00d76" in texts - assert not {f"g{i}" for i in range(6)} & texts + # The driver, the first 8 sinks in natural name order (g0..g5, s0, s1), + # and the other 38 flops (s2..s9, u_bank's 30) in one summary: by model, + # the default. + assert {"drv", "LUT1", "s0", "s1"} <= texts + assert {f"g{i}" for i in range(6)} <= texts + assert "FDRE \u00d738" in texts and "s2" not in texts w, h = _svg_size(svg) assert _png_size(png_out.read_bytes()) == (int(w * 2 + 0.999), int(h * 2 + 0.999)) @@ -293,6 +392,81 @@ def test_render_cli_gathers_a_wide_fanout(tmp_path): assert {f"g{i}" for i in range(6)} <= _texts(every.read_text(encoding="utf-8")) +# -- group_by "role": the receiving pin's naja term role ------------------------ + +ROLE_SPEC = load_spec("role_protocol_cases.json") + + +@pytest.fixture(scope="module") +def roles(top): + # NLUniverse is process-global: build next to the session's design and + # make it the top design for this module only. + u = naja.NLUniverse.get() + previous = u.getTopDesign() + designs = build_design(ROLE_SPEC["design"]) + u.setTopDesign(designs[ROLE_SPEC["design"]["top"]]) + yield designs + u.setTopDesign(previous) + designs[ROLE_SPEC["design"]["top"]].getDB().destroy() + + +@pytest.mark.parametrize("case", ROLE_SPEC["cases"], ids=[c["name"] for c in ROLE_SPEC["cases"]]) +def test_term_roles_shared_protocol_case(roles, case): + replies = protocol.handle_request(substitute(case["request"], roles)) + check_case(case, json.loads(json.dumps(replies))) + + +def test_term_role_names_cover_every_naja_role(): + # Every non-data role naja has is sent by name (termRoleName() in C++). + data = {"DataInput", "DataOutput", "Other"} + naja_roles = {r for r in dir(naja.SNLTermRole) if not r.startswith("_")} - data + assert naja_roles <= set(protocol._TERM_ROLE_NAMES) + + +def test_group_by_values(): + assert protocol.view_options(group_by="role")["group_by"] == "role" + assert protocol.view_options(group_by="pin")["group_by"] == "pin" + with pytest.raises(ValueError, match="group_by"): + protocol.view_options(group_by="name") + + +ROLE_DESIGN = ("--verilog", "role_fanout.v", "--py-primitives", "py_prims.py") + + +def _summaries(texts): + # {"clock": 12, ...} from the " ×" summary labels. + out = {} + for t in texts: + what, sep, n = t.rpartition(" \u00d7") + if sep and n.isdigit(): + out[what] = int(n) + return out + + +@needs_renderer +def test_render_cli_groups_sinks_by_role(tmp_path): + # 34 sinks: 12 clock, 6 reset, 5 enable pins of flops, and 7 flop D + # pins plus 4 AND inputs with no role (data). 2 drawn, 32 gathered. + out = tmp_path / "role.svg" + result = _cli("render", *ROLE_DESIGN, "--net", "drv:Y", "--max-sinks", "2", + "--group-by", "role", "--svg", str(out)) + assert result.returncode == 0, result.stderr + groups = _summaries(_texts(out.read_text(encoding="utf-8"))) + assert set(groups) == {"clock", "reset", "enable", "data"}, groups + assert sum(groups.values()) == 32 + assert 10 <= groups["clock"] <= 12 and 4 <= groups["reset"] <= 6 + assert 3 <= groups["enable"] <= 5 and 9 <= groups["data"] <= 11 + + # "pin": by pin name, the clock pins together. + out = tmp_path / "pin.svg" + result = _cli("render", *ROLE_DESIGN, "--net", "drv:Y", "--max-sinks", "2", + "--group-by", "pin", "--svg", str(out)) + assert result.returncode == 0, result.stderr + groups = _summaries(_texts(out.read_text(encoding="utf-8"))) + assert set(groups) == {"clock", "R", "L", "D", "A"}, groups + assert sum(groups.values()) == 32 + + def test_render_cli_output_flags(tmp_path): result = _cli("render", *PY_DESIGN, "--instance", "u_ff") assert result.returncode == 2 and "--svg and/or --png" in result.stderr @@ -302,3 +476,18 @@ def test_render_cli_output_flags(tmp_path): result = _cli("render", *PY_DESIGN, "--instance", "u_ff", "--png", str(tmp_path / "x.png"), "--group-by", "colour") assert result.returncode == 2 and "--group-by" in result.stderr + + + +def test_convergence_outline_option(): + assert protocol.DEFAULT_VIEW_OPTIONS["convergence_outline"] is True + assert protocol.view_options(convergence_outline=False)["convergence_outline"] is False + with pytest.raises(ValueError): + protocol.view_options(convergence_outline="no") + from naja_schematic.server import add_view_arguments, view_options_from_args + import argparse + parser = argparse.ArgumentParser() + add_view_arguments(parser) + assert view_options_from_args(parser.parse_args(["--no-convergence-outline"])) == \ + {"convergence_outline": False} + assert "applied when this flag is not given" in " ".join(parser.format_help().split()) diff --git a/python/tests/test_style.py b/python/tests/test_style.py index 4854f82..59b76c5 100644 --- a/python/tests/test_style.py +++ b/python/tests/test_style.py @@ -97,6 +97,39 @@ def test_instances_and_pins_resolve_or_raise(top): style_response([{"kind": "term", "path": ["r"], "terminal": "nope"}]) +def test_targets_in_the_text_and_json_forms(top): + # What a style JSON file can say: the render CLI's --net/--instance text, + # or a pin as [instance, terminal(, bit)] or {"path", "terminal", "bit"}. + expected = {"kind": "net", "id_path": [0, 0], "path": ["u_sub", "u_and"]} + for target in ("u_sub/u_and:O", "r:D", "u_sub:y", [["u_sub", "u_and"], "O"], + [[0, 0], "O"], ["r", "D"], {"path": ["r"], "terminal": "D"}, + {"id_path": [0, 0], "terminal": "O"}): + [got] = style_response([{"kind": "net", "target": target, "color": "#1f77b4"}])["items"] + assert {k: got[k] for k in expected} == expected, target + # A top-level port: its name alone, or [[], name(, bit)]. + for target in ("q", [[], "q"], ":q"): + [got] = style_response([{"kind": "net", "target": target}])["items"] + assert got["id_path"] == [] and "bit" not in got, target + for target in ("d[1]", [[], "d", 1], {"path": [], "terminal": "d", "bit": 1}): + [got] = style_response([{"kind": "term", "target": target}])["items"] + assert (got["id_path"], got["bit"]) == ([], 1), target + # An instance: "u1/u2" text (matched against the design), or JSON text. + for target in ("u_sub/u_and", '["u_sub", "u_and"]', "[0, 0]"): + [got] = style_response([{"kind": "instance", "target": target}])["items"] + assert (got["id_path"], got["path"]) == ([0, 0], ["u_sub", "u_and"]), target + + +def test_bad_targets_name_the_item(top): + for target, error in (("u_sub/nope:O", "no pin"), ([[], "nope"], "no terminal"), + ("d", "a bus"), ([["nope"], "O"], "no instance")): + with pytest.raises(ValueError, match=f"style item 0: target .*{error}"): + style_response([{"kind": "net", "target": target}]) + with pytest.raises(ValueError, match="style item 1: target 'u_sub/x'.*no instance"): + style_response([{"target": "u_sub"}, {"target": "u_sub/x"}]) + with pytest.raises(TypeError, match="style item 0"): + style_response([{"kind": "net", "target": 3.5}]) + + def test_style_is_pushed_now_and_after_each_root(top): sent = [] session = ViewerSession(push=sent.append) @@ -157,6 +190,28 @@ def test_render_cli_draws_a_fanout_report_in_its_colors(tmp_path): assert ">en" in svg +@needs_renderer +def test_render_cli_style_file_targets(tmp_path): + # The file form documented in the README: targets as --net/--instance + # text and as a JSON [path, terminal] list. + style = tmp_path / "style.json" + style.write_text(json.dumps({"items": [ + {"kind": "net", "target": [[], "en"], "color": "#ff7f0e", "width": 3}, + {"kind": "net", "target": "drv_0:O", "color": "#1f77b4", "width": 2.5}, + {"kind": "instance", "target": "s0", "fill": "#1f77b455"}, + ]})) + out = tmp_path / "fanout.svg" + result = subprocess.run( + [sys.executable, "-m", "naja_schematic", "render", "--verilog", "fanout.v", "--xilinx", + "--style", str(style), "--net", "en", "--net", "drv_0:O", "--svg", str(out)], + cwd=DATA, capture_output=True, text=True, timeout=120) + assert result.returncode == 0, result.stderr + svg = out.read_text() + strokes = set(re.findall(r'stroke="(rgb\([^)]*\))" stroke-width="([\d.]+)"', svg)) + assert (_rgb("#ff7f0e"), "3") in strokes and (_rgb("#1f77b4"), "2.5") in strokes + assert _blend("#1f77b4") in set(re.findall(r'fill="(rgb\([^)]*\))"', svg)) + + @needs_renderer def test_render_cli_refuses_a_bad_style(tmp_path): style = tmp_path / "style.json" diff --git a/src/AppLogic.cpp b/src/AppLogic.cpp index dd3e1ca..387d300 100644 --- a/src/AppLogic.cpp +++ b/src/AppLogic.cpp @@ -249,7 +249,7 @@ bool appFrame(AppState& state) { EquipotentialView::setShowHierarchy(!EquipotentialView::showHierarchy()); // How the schematic is drawn (ViewOptions; also the host's // view_options push and the native --instance-label/--sink-rows/ - // --max-sinks/--group-by flags). + // --max-sinks/--group-by/--no-convergence-outline flags). ViewOptions& vo = ViewOptions::current(); if (ImGui::BeginMenu("Instance Labels")) { for (InstanceLabel l : { InstanceLabel::Name, InstanceLabel::Model, InstanceLabel::Both }) { @@ -264,12 +264,17 @@ bool appFrame(AppState& state) { ImGui::SetNextItemWidth(120.0f); ImGui::DragInt("Sinks drawn per net", &vo.maxSinks, 0.2f, 0, 100000, vo.maxSinks ? "%d" : "all"); ImGui::SeparatorText("Gather the others by"); - for (FanoutGroupBy g : { FanoutGroupBy::Model, FanoutGroupBy::Hierarchy, FanoutGroupBy::Role }) { - const char* text = g == FanoutGroupBy::Model ? "Cell Model" : g == FanoutGroupBy::Hierarchy ? "Module" : "Pin (clock / name)"; + for (FanoutGroupBy g : { FanoutGroupBy::Model, FanoutGroupBy::Hierarchy, FanoutGroupBy::Role, FanoutGroupBy::Pin }) { + const char* text = g == FanoutGroupBy::Model ? "Cell Model" + : g == FanoutGroupBy::Hierarchy ? "Module" + : g == FanoutGroupBy::Role ? "Pin Role (clock / reset / enable / data)" + : "Pin Name"; if (ImGui::MenuItem(text, "", vo.groupBy == g)) vo.groupBy = g; } ImGui::EndMenu(); } + if (ImGui::MenuItem("Outline Trace Convergence", "", vo.convergenceOutline)) + vo.convergenceOutline = !vo.convergenceOutline; ImGui::Separator(); if (ImGui::MenuItem("Clear nets", NAJA_SHORTCUT("K"))) { ShowNetStore::forget(); diff --git a/src/EquipotentialView.cpp b/src/EquipotentialView.cpp index d521cc1..3e1eead 100644 --- a/src/EquipotentialView.cpp +++ b/src/EquipotentialView.cpp @@ -1119,6 +1119,16 @@ void EquipotentialView::renderSchematic(const std::vector& equip Equipotential* eq = equipotentials[ei]; if (!eq || (eq->terms.empty() && eq->occurrences.empty())) continue; buildItems(eq, fanNets[ei].drivers, fanNets[ei].receivers); + // Sinks in natural name order: the first max_sinks drawn, the rest + // summarized, both in the order a reader expects (lut_111 < lut_1037). + std::stable_sort(fanNets[ei].receivers.begin(), fanNets[ei].receivers.end(), + [](const Item& a, const Item& b) { + if (a.isTerm != b.isTerm) return a.isTerm; + if (a.isTerm) return naturalLess(a.label, b.label); + if (naturalPathLess(a.path, b.path)) return true; + if (naturalPathLess(b.path, a.path)) return false; + return naturalLess(a.label, b.label); + }); for (const auto& r : fanNets[ei].receivers) if (!r.isTerm && (DiagnosisStore::instanceColor(r.path) != 0 || !StyleStore::instanceStyle(r.path).empty())) pinned.insert(r.path); @@ -1260,8 +1270,11 @@ void EquipotentialView::renderSchematic(const std::vector& equip inst.primitiveType = mi.primitiveType; inst.diagOutline = DiagnosisStore::instanceColor(key); applyInstanceStyle(inst); - // A gate two visible traces go through: where they converge. - if (inst.diagOutline == 0 && traceIdsByInstance[key].size() >= 2) + // A gate two visible traces go through: where they converge -- not + // on a box the host styles (it marks it its own way), nor when the + // convergence_outline view option is off. + if (inst.diagOutline == 0 && traceIdsByInstance[key].size() >= 2 && + viewOptions.convergenceOutline && StyleStore::instanceStyle(key).empty()) inst.diagOutline = TraceStore::convergenceColor(); inst.selected = SelectionStore::isSelected(key); setReviewBadge(inst); @@ -1270,6 +1283,9 @@ void EquipotentialView::renderSchematic(const std::vector& equip const FanoutGroup& g = fanPlan.groups[sit->second]; inst.isSummary = true; inst.summaryCount = int(g.count); + inst.summaryGroup = g.key.clock ? "clock" + : viewOptions.groupBy == FanoutGroupBy::Hierarchy ? displayPath(g.key.module) + : g.key.text; inst.name = g.label; inst.label = g.label; g_summaryByShapeId[inst.id] = { fanNetKeys[g.net], g.key }; @@ -1479,6 +1495,16 @@ void EquipotentialView::renderSchematic(const std::vector& equip placeNodes.push_back({ footprintWidth(inst, instanceNameWidth), footprintHeight(inst, instanceNameWidth) }); } + // Loads of one pin go in natural name order, summaries after them. + { + std::vector byName; + for (const auto& inst : g_schematic.instances) byName.push_back(&inst); + std::stable_sort(byName.begin(), byName.end(), [](const InstanceShape* a, const InstanceShape* b) { + if (a->isSummary != b->isSummary) return b->isSummary; + return a->isSummary ? naturalLess(a->name, b->name) : naturalPathLess(a->path, b->path); + }); + for (size_t r = 0; r < byName.size(); ++r) placeNodes[size_t(nodeOfShape[byName[r]->id])].rank = int(r); + } std::vector placeNets; for (const auto& ends : equiEnds) { PlaceNet pn; @@ -1806,6 +1832,27 @@ void EquipotentialView::renderSchematic(const std::vector& equip // Wiring nested in an expanded instance isn't routed: color it here. for (auto& n : g_schematic.nets) if (!n.routed) n.color = styledWireColor(n.color, n.styleColor, n.traceIds, n.faint); + // The export legend: every visible trace drawn, then every net a + // host style labels, in its drawn color. + { + auto& legend = g_schematic.legend; + legend.clear(); + std::set drawnTraces; + for (const auto& rt : routeTraces) drawnTraces.insert(rt.ids.begin(), rt.ids.end()); + for (const auto& n : g_schematic.nets) drawnTraces.insert(n.traceIds.begin(), n.traceIds.end()); + for (const Trace& t : TraceStore::traces()) + if (drawnTraces.count(t.id) && TraceStore::isVisible(t.id) && !t.label.empty()) + legend.push_back({ TraceStore::color(t.id), t.label }); + auto addStyled = [&](ImU32 color, const std::string& label) { + if (label.empty()) return; + for (const auto& e : legend) + if (e.label == label && e.color == color) return; + legend.push_back({ color, label }); + }; + for (const auto& r : g_schematic.routes) addStyled(r.color, r.label); + for (const auto& n : g_schematic.nets) + if (!n.routed) addStyled(n.color, n.label); + } auto routed = routeNets(routeNetsIn, obstacles, keepOut); for (size_t i = 0; i < routed.size(); ++i) { g_schematic.routes[i].segments = std::move(routed[i].segments); @@ -1815,7 +1862,7 @@ void EquipotentialView::renderSchematic(const std::vector& equip static int lastTotal = -1; static std::string lastViewOptions; - if (const std::string vo = viewOptions.toJson().dump(); vo != lastViewOptions) { + if (const std::string vo = viewOptions.layoutJson().dump(); vo != lastViewOptions) { if (!lastViewOptions.empty()) g_schematic.requestFit(true); lastViewOptions = vo; } diff --git a/src/LocalSNLProvider.cpp b/src/LocalSNLProvider.cpp index e5e102b..ab1e3e3 100644 --- a/src/LocalSNLProvider.cpp +++ b/src/LocalSNLProvider.cpp @@ -228,6 +228,37 @@ static std::string termName(const SNLTerm* t) { return t->getName().getString(); } +// naja's term role as sent in "role", or nullptr for a data pin +// (DataInput, DataOutput, or no role set: Other). Kept in step with +// _TERM_ROLE_NAMES in protocol.py. +static const char* termRoleName(SNLDesignModeling::SNLTermRole role) { + using Role = SNLDesignModeling::SNLTermRole; + switch (role) { + case Role::Clock: return "clock"; + case Role::AsyncReset: return "async_reset"; + case Role::AsyncSet: return "async_set"; + case Role::SyncReset: return "sync_reset"; + case Role::SyncSet: return "sync_set"; + case Role::Enable: return "enable"; + case Role::MemoryReadAddress: return "memory_read_address"; + case Role::MemoryReadData: return "memory_read_data"; + case Role::MemoryWriteAddress: return "memory_write_address"; + case Role::MemoryWriteData: return "memory_write_data"; + case Role::MemoryWriteEnable: return "memory_write_enable"; + case Role::ScanInput: return "scan_input"; + case Role::ScanEnable: return "scan_enable"; + default: return nullptr; + } +} + +// Only sent when set, like "clock": a pin naja gives a non-data role +// (fanout summaries grouped by role). +template +static void setTermRole(json& t, const Term* term) { + if (const char* role = termRoleName(SNLDesignModeling::getTermRole(term))) t["role"] = role; + else t.erase("role"); +} + // Build a bit-term JSON node (shared by terms and occurrence entries). static json bitTermJson(const SNLBitTerm* bt) { json t = { @@ -239,6 +270,7 @@ static json bitTermJson(const SNLBitTerm* bt) { t["bit"] = static_cast(btb->getBit()); // Only sent when set: marks a flip-flop's clock pin (see drawDffInstance). if (SNLDesignModeling::isClock(bt)) t["clock"] = true; + setTermRole(t, bt); return t; } @@ -864,6 +896,9 @@ static json equipotentialJson(const SNLEquipotential& equi, static_cast(theInst->getID()), designName(theInst->getModel())})); auto entry = bitTermJson(bt); + // The instance's own role: a parameterized primitive can take it from + // the instance's parameters. + setTermRole(entry, it); entry["path"] = std::move(pathArr); if (auto* model = theInst->getModel()) { entry["design_ref"] = { diff --git a/src/SchematicLayout.cpp b/src/SchematicLayout.cpp index fa807dd..345a3d6 100644 --- a/src/SchematicLayout.cpp +++ b/src/SchematicLayout.cpp @@ -30,6 +30,7 @@ void buildItems(const Equipotential* eq, item.termChildId = occ.term.child_id; item.termBit = occ.term.bit; item.clock = occ.term.clock; + item.role = occ.term.role; item.pathIds = occ.pathIds; item.hasInstances = occ.has_instances; item.bitTermCount = occ.bit_term_count; @@ -62,6 +63,43 @@ float labelWidth(const std::vector& names) { // --------------------------------------------------------------------------- // Instance names // --------------------------------------------------------------------------- +bool naturalLess(const std::string& a, const std::string& b) { + auto digit = [](char c) { return c >= '0' && c <= '9'; }; + size_t i = 0, j = 0; + while (i < a.size() && j < b.size()) { + if (digit(a[i]) && digit(b[j])) { + size_t i1 = i, j1 = j; + while (i1 < a.size() && digit(a[i1])) ++i1; + while (j1 < b.size() && digit(b[j1])) ++j1; + // Compare values without overflow: leading zeros off, then by + // length, then digit by digit. + size_t i0 = i, j0 = j; + while (i0 + 1 < i1 && a[i0] == '0') ++i0; + while (j0 + 1 < j1 && b[j0] == '0') ++j0; + if (i1 - i0 != j1 - j0) return i1 - i0 < j1 - j0; + const int c = a.compare(i0, i1 - i0, b, j0, j1 - j0); + if (c != 0) return c < 0; + i = i1; + j = j1; + continue; + } + if (a[i] != b[j]) return (unsigned char)a[i] < (unsigned char)b[j]; + ++i; + ++j; + } + if ((i < a.size()) != (j < b.size())) return j < b.size(); + return a < b; +} + +bool naturalPathLess(const InstancePath& a, const InstancePath& b) { + for (size_t k = 0; k < a.size() && k < b.size(); ++k) { + if (naturalLess(a[k].name, b[k].name)) return true; + if (naturalLess(b[k].name, a[k].name)) return false; + } + if (a.size() != b.size()) return a.size() < b.size(); + return a < b; +} + std::string shortenMiddle(const std::string& name, const NameWidthFn& width, float maxW) { if (width(name) <= maxW) return name; static const std::string kEllipsis = "..."; @@ -315,6 +353,12 @@ Placement layeredPlacement(const std::vector& nodes, const std::vecto }; renumber(); auto frac = [&](int node, float dy) { return nodes[node].h > 0.f ? dy / nodes[node].h : 0.5f; }; + std::vector isSink(n, 0); + for (int v = 0; v < n; ++v) { + bool drives = nodes[v].drivesOutput; + for (int e : outEdges[v]) if (!isBack[e]) drives = true; + isSink[v] = !drives; + } for (int sweep = 0; sweep < 4; ++sweep) { const bool down = sweep % 2 == 0; for (int li = 0; li <= maxLevel; ++li) { @@ -331,15 +375,27 @@ Placement layeredPlacement(const std::vector& nodes, const std::vecto for (int e : outEdges[v]) visit(edges[e].v, edges[e].dv); keyed.push_back({ cnt ? sum / float(cnt) : order[v] + 0.5f, v }); } - std::stable_sort(keyed.begin(), keyed.end(), - [](const auto& a, const auto& b) { return a.first < b.first; }); + // Ties between sinks (the loads of one pin): by rank. + std::stable_sort(keyed.begin(), keyed.end(), [&](const auto& a, const auto& b) { + if (a.first != b.first) return a.first < b.first; + return isSink[a.second] && isSink[b.second] && nodes[a.second].rank < nodes[b.second].rank; + }); for (size_t i = 0; i < keyed.size(); ++i) layer[i] = keyed[i].second; renumber(); } } // 6 (before the columns are measured). Sink grid: a column with too - // many sinks is dealt into several, each a level of its own. + // many sinks is dealt into several, each a level of its own. Its + // sinks are banded by driver: each driver's sinks get rows of their + // own (a band, placed level with the driver in step 5) and are dealt + // into columns from the grid's first one, so every driver's grid + // starts in the same column and no net's wire has to cross another + // net's sinks to reach its own. + struct Band { std::vector> cols; }; + struct SinkGrid { int first = 0, count = 0; std::vector bands; }; + std::vector grids; + std::vector gridOfLevel(maxLevel + 1, -1); if (maxSinkRows > 0) { std::vector> wrapped; for (const auto& layer : layers) { @@ -350,19 +406,59 @@ Placement layeredPlacement(const std::vector& nodes, const std::vecto (drives ? others : sinks).push_back(v); } if (int(sinks.size()) <= maxSinkRows) { wrapped.push_back(layer); continue; } - const size_t cols = (sinks.size() + size_t(maxSinkRows) - 1) / size_t(maxSinkRows); - const size_t per = (sinks.size() + cols - 1) / cols; - for (size_t c = 0; c * per < sinks.size(); ++c) - wrapped.emplace_back(sinks.begin() + long(c * per), - sinks.begin() + long(std::min(sinks.size(), (c + 1) * per))); + // A sink's band: its nearest driver (the highest level among its + // forward in-edges, then the first in column order). Bands keep + // the order their first sink has in the column. + std::vector bandKeys; + std::vector> bandSinks; + for (int v : sinks) { + int key = -1, keyLevel = INT_MIN; + for (int e : inEdges[v]) { + if (isBack[e]) continue; + const int u = edges[e].u; + if (key < 0 || out.level[u] > keyLevel || (out.level[u] == keyLevel && order[u] < order[key])) { + key = u; + keyLevel = out.level[u]; + } + } + auto it = std::find(bandKeys.begin(), bandKeys.end(), key); + if (it == bandKeys.end()) { + bandKeys.push_back(key); + bandSinks.emplace_back(); + it = bandKeys.end() - 1; + } + bandSinks[size_t(it - bandKeys.begin())].push_back(v); + } + SinkGrid grid; + grid.first = int(wrapped.size()); + for (const auto& bs : bandSinks) { + const size_t cols = (bs.size() + size_t(maxSinkRows) - 1) / size_t(maxSinkRows); + const size_t per = (bs.size() + cols - 1) / cols; + Band band; + for (size_t c = 0; c * per < bs.size(); ++c) + band.cols.emplace_back(bs.begin() + long(c * per), + bs.begin() + long(std::min(bs.size(), (c + 1) * per))); + grid.count = std::max(grid.count, int(band.cols.size())); + grid.bands.push_back(std::move(band)); + } + for (int c = 0; c < grid.count; ++c) { + std::vector col; + for (const auto& band : grid.bands) + if (c < int(band.cols.size())) col.insert(col.end(), band.cols[c].begin(), band.cols[c].end()); + wrapped.push_back(std::move(col)); + } + grids.push_back(std::move(grid)); if (!others.empty()) wrapped.push_back(others); } - if (wrapped.size() != layers.size()) { + if (!grids.empty()) { layers = std::move(wrapped); maxLevel = int(layers.size()) - 1; for (int l = 0; l <= maxLevel; ++l) for (int v : layers[l]) out.level[v] = l; renumber(); + gridOfLevel.assign(maxLevel + 1, -1); + for (int g = 0; g < int(grids.size()); ++g) + for (int c = 0; c < grids[g].count; ++c) gridOfLevel[grids[g].first + c] = g; } } @@ -393,10 +489,48 @@ Placement layeredPlacement(const std::vector& nodes, const std::vecto float cy = 0.f; for (int v : layer) { y[v] = cy; cy += nodes[v].h + kRowSpacing; } } + // A sink grid is placed as a whole: its bands top to bottom, each one's + // rows level with its driver's pin as far as the bands above allow, the + // rows of a band aligned across its columns. + auto placeGrid = [&](const SinkGrid& grid) { + float prevBottom = 0.f; + bool first = true; + for (const auto& band : grid.bands) { + size_t rows = 0; + for (const auto& col : band.cols) rows = std::max(rows, col.size()); + std::vector rowOff(rows, 0.f); + float rowY = 0.f; + for (size_t r = 0; r < rows; ++r) { + float h = 0.f; + for (const auto& col : band.cols) if (r < col.size()) h = std::max(h, nodes[col[r]].h); + rowOff[r] = rowY; + rowY += h + kRowSpacing; + } + const float height = rowY - kRowSpacing; + std::vector want; + for (const auto& col : band.cols) + for (size_t r = 0; r < col.size(); ++r) + for (int e : inEdges[col[r]]) + if (!isBack[e] && out.level[edges[e].u] < grid.first) + want.push_back(y[edges[e].u] + edges[e].du - edges[e].dv - rowOff[r]); + float top = want.empty() ? (first ? 0.f : prevBottom + kBandGap) : lowerMedian(want); + if (!first) top = std::max(top, prevBottom + kBandGap); + top = std::round(top / kGrid) * kGrid; + for (const auto& col : band.cols) + for (size_t r = 0; r < col.size(); ++r) y[col[r]] = top + rowOff[r]; + prevBottom = top + height; + first = false; + } + }; const int rounds[] = { +1, -1, +1 }; for (int dir : rounds) { for (int li = 0; li <= maxLevel; ++li) { int l = dir > 0 ? li : maxLevel - li; + if (gridOfLevel[l] >= 0) { + const SinkGrid& grid = grids[size_t(gridOfLevel[l])]; + if (l == (dir > 0 ? grid.first : grid.first + grid.count - 1)) placeGrid(grid); + continue; + } auto& layer = layers[l]; std::vector target, weight, h; for (int v : layer) { @@ -735,6 +869,17 @@ std::string baseName(const std::string& label) { } } // namespace +std::string fanoutRoleGroup(const Item& r) { + const std::string& role = r.role; + if (role == "clock" || (role.empty() && r.clock)) return "clock"; + if (role == "async_reset" || role == "sync_reset") return "reset"; + if (role == "async_set" || role == "sync_set") return "set"; + if (role == "enable" || role == "memory_write_enable") return "enable"; + if (role == "scan_input" || role == "scan_enable") return "scan"; + if (role == "memory_read_address" || role == "memory_write_address") return "address"; + return "data"; +} + FanoutPlan planFanout(const std::vector& nets, int maxSinks, FanoutGroupBy groupBy, const std::set& pinned, const FanoutExpandedFn& expanded) { FanoutPlan plan; @@ -780,6 +925,9 @@ FanoutPlan planFanout(const std::vector& nets, int maxSinks, FanoutGr k.module.assign(r.path.begin(), r.path.end() - (r.path.empty() ? 0 : 1)); break; case FanoutGroupBy::Role: + k.text = fanoutRoleGroup(r); + break; + case FanoutGroupBy::Pin: k.clock = r.clock; if (!r.clock) k.text = baseName(r.label); break; @@ -834,7 +982,8 @@ FanoutPlan planFanout(const std::vector& nets, int maxSinks, FanoutGr while (k < common && k + 1 < r.path.size() && r.path[k] == first.path[k]) ++k; common = k; } - if (groupBy == FanoutGroupBy::Role && g.clock && g.pin.empty()) g.pin = "clock"; + if (g.pin.empty() && groupBy == FanoutGroupBy::Pin && g.clock) g.pin = "clock"; + if (g.pin.empty() && groupBy == FanoutGroupBy::Role) g.pin = key.text; g.module.assign(first.path.begin(), first.path.begin() + long(common)); g.moduleModels.assign(first.pathModels.begin(), first.pathModels.begin() + long(std::min(common, first.pathModels.size()))); @@ -842,7 +991,8 @@ FanoutPlan planFanout(const std::vector& nets, int maxSinks, FanoutGr switch (groupBy) { case FanoutGroupBy::Model: what = key.text.empty() ? "cells" : key.text; break; case FanoutGroupBy::Hierarchy: what = key.module.empty() ? "(top)" : displayPath(key.module); break; - case FanoutGroupBy::Role: what = key.clock ? "clock" : key.text; break; + case FanoutGroupBy::Role: what = key.text; break; + case FanoutGroupBy::Pin: what = key.clock ? "clock" : key.text; break; } g.label = what + " \xC3\x97" + std::to_string(g.count); // U+00D7 multiplication sign const int gi = int(plan.groups.size()); diff --git a/src/SchematicLayout.h b/src/SchematicLayout.h index a0b8bdb..d8ed859 100644 --- a/src/SchematicLayout.h +++ b/src/SchematicLayout.h @@ -34,6 +34,7 @@ inline constexpr float kLeftMargin = 20.0f; inline constexpr float kChannelMin = 50.0f; // narrowest routing channel between columns inline constexpr float kTrackPitch = 10.0f; // extra channel width per vertical wire track inline constexpr float kPortGap = 50.0f; // top-level ports -> nearest box +inline constexpr float kBandGap = kRowSpacing + 2.0f * kPinPitch; // between two drivers' sink bands // Hierarchy grouping (module frames around traced leaves). // Grid multiples, so leaves inside frames keep their pins on the grid. @@ -62,6 +63,13 @@ using NameWidthFn = std::function; // "...". Empty when not even the ellipsis fits. std::string shortenMiddle(const std::string& name, const NameWidthFn& width, float maxW); +// Natural order: runs of digits compare by value, so "i_lut_111" comes +// before "i_lut_1037" (and "u2" before "u10"); otherwise byte order. Equal +// values with different spellings ("07", "7") fall back to byte order. +bool naturalLess(const std::string& a, const std::string& b); +// naturalLess() on instance names, level by level; ids break ties. +bool naturalPathLess(const InstancePath& a, const InstancePath& b); + // The name drawn above `s` (its label, else its name, shortened to // kNameMaxW), or "" for shapes drawn without one (frames, top-level ports, // a box showing its model only). @@ -132,16 +140,25 @@ inline constexpr float kOperatorGlyphW = 2.f * kPinPitch; // to (straight wires), keeping the column order and spacing. // 6. a column with more than `maxSinkRows` sinks -- nodes nothing placed // is driven by (a net's loads: flops, a summary box) -- is wrapped into -// a grid: the sinks, in their order, are dealt into as few columns of -// at most that many as needed (balanced), placed before the column's -// other nodes, which keep the last column next to what they drive. -// Each grid column is a level of its own (Placement::level), with a -// channel before it like any other. 0: no limit. +// a grid, placed before the column's other nodes, which keep the last +// column next to what they drive. The grid has a band of rows per +// driver (a sink's nearest one), in column order: each band's sinks, +// in their order, are dealt into as few columns of at most that many +// as needed (balanced), starting from the grid's first column, and the +// band is placed level with its driver, below the band above it +// (kBandGap apart), rows aligned across its columns. So no driver's +// wires cross another driver's sinks. Each grid column is a level of +// its own (Placement::level), with a channel before it like any +// other. 0: no limit. // Pure geometry: the result depends only on the inputs, in their order. // --------------------------------------------------------------------------- struct PlaceNode { float w = 0.f, h = 0.f; bool drivesOutput = false; // drives a net that reaches a top-level output + // Order among sinks the crossing reduction can't tell apart (same + // barycenter: e.g. the loads of one driver pin): lower first. The + // caller's, e.g. the natural order of the names (naturalLess). + int rank = 0; }; struct PlacePin { int node = 0; @@ -222,6 +239,7 @@ struct Item { unsigned termChildId = 0; std::optional termBit; bool clock = false; // a sequential cell's clock pin + std::string role; // naja's term role, "" = data (BitTerm::role) std::vector pathIds; // Only meaningful for instance occurrences (isTerm == false): whether // this instance's model has sub-instances worth expanding into a nested @@ -251,13 +269,19 @@ void buildItems(const Equipotential* eq, std::vector& drivers, std::vector // as itself on every net. Top-level ports are never gathered. // // A group is keyed by what it gathers: the model (Model), the module -// holding the sinks (Hierarchy), or the receiving pin -- every clock pin -// together, else by base name (Role). +// holding the sinks (Hierarchy), the receiving pin's naja role, by +// fanoutRoleGroup() (Role), or the receiving pin -- every clock pin +// together, else by base name (Pin). // --------------------------------------------------------------------------- +// The group a receiving pin falls in with group_by "role", by its naja +// term role: "clock" (also a pin naja models as a clock with no role set), +// "reset", "set", "enable", "scan", "address", else "data". +std::string fanoutRoleGroup(const Item& receiver); + struct FanoutGroupKey { - std::string text; // Model: the model; Role: the pin's base name + std::string text; // Model: the model; Role: fanoutRoleGroup(); Pin: the pin's base name InstancePath module; // Hierarchy: the module containing the sinks - bool clock = false; // Role: the clock pins + bool clock = false; // Pin: the clock pins auto tie() const { return std::tie(text, module, clock); } bool operator<(const FanoutGroupKey& o) const { return tie() < o.tie(); } bool operator==(const FanoutGroupKey& o) const { return tie() == o.tie(); } diff --git a/src/SchematicPainter.h b/src/SchematicPainter.h index 5c9dc86..efa4949 100644 --- a/src/SchematicPainter.h +++ b/src/SchematicPainter.h @@ -2,6 +2,8 @@ #include #include +#include +#include #include // What SchematicView draws with: the subset of ImDrawList it uses, with the @@ -31,6 +33,14 @@ class SchematicPainter { const char* text) = 0; virtual void PushClipRect(const ImVec2& rmin, const ImVec2& rmax) = 0; virtual void PopClipRect() = 0; + + // Structure around what's drawn between them -- a net, an instance, a + // port flag -- as (name, value) attributes, e.g. {"class", "net"}, + // {"data-net", "q"}. Draws nothing: only SvgPainter keeps it (a ); + // nested calls nest. + using GroupAttrs = std::vector>; + virtual void BeginGroup(const GroupAttrs& /*attrs*/) {} + virtual void EndGroup() {} }; class ImDrawListPainter : public SchematicPainter { @@ -96,6 +106,10 @@ class SvgPainter : public SchematicPainter { void AddText(ImFont* font, float fontSize, const ImVec2& pos, ImU32 col, const char* text) override; void PushClipRect(const ImVec2&, const ImVec2&) override {} void PopClipRect() override {} + // A with the attributes (values XML-escaped), on a line of its own; + // EndGroup() its line. + void BeginGroup(const GroupAttrs& attrs) override; + void EndGroup() override; // The complete document (call once, after drawing). std::string finish(); diff --git a/src/SchematicView.cpp b/src/SchematicView.cpp index d048807..0cbf95f 100644 --- a/src/SchematicView.cpp +++ b/src/SchematicView.cpp @@ -1,6 +1,7 @@ #include "SchematicView.h" #include "RasterPainter.h" +#include "ViewOptions.h" #include #include @@ -331,7 +332,7 @@ static void drawPorts(SchematicPainter* dl, const InstanceShape& inst, // An open pin (net not in the view yet) ends in a hollow circle, a // loading one in a filled circle: "click here to see more" without // needing color for the resting state. - if (p.open) { + if (p.open && !sv.hideUiGlyphs) { float r = std::max(kMinOpenPinR, kOpenPinBaseR * sv.transform.scale); ImVec2 c(tickEnd.x + (isLeft ? -r : r), tickEnd.y); dl->AddCircleFilled(c, r, pending ? portColor : kCanvasBgColor); @@ -544,7 +545,7 @@ static void drawGenericInstance(SchematicPainter* dl, const InstanceShape& inst, drawInstanceName(dl, inst, sv, rmin); - if (inst.partialInterface) { + if (inst.partialInterface && !sv.hideUiGlyphs) { float boxH = rmax.y - rmin.y; if (boxH > 28.0f) { const float dotR = 2.5f; @@ -1361,6 +1362,73 @@ void SchematicView::handleInteraction(const ImVec2& canvasPos, const ImVec2& can } } +// --------------------------------------------------------------------------- +// Export structure: the data-* attributes of each drawn object's +// (SchematicPainter::BeginGroup; only the SVG keeps them). +// --------------------------------------------------------------------------- +namespace { + +std::string idPathText(const InstancePath& path) { + std::string out; + for (size_t i = 0; i < path.size(); ++i) out += (i ? "," : "") + std::to_string(path[i].id); + return out; +} + +// True when the "u1/u2" (or "u1/u2:Q") text can't be read back: a name +// that is empty (anonymous) or holds a separator, as escaped Verilog names +// can. The group then also carries the path as JSON. +bool ambiguous(const InstancePath& path, const std::string& term = "") { + for (const auto& ref : path) + if (ref.name.empty() || ref.name.find_first_of("/:") != std::string::npos) return true; + return term.find_first_of("/:") != std::string::npos; +} + +std::string jsonText(const nlohmann::json& j) { + return j.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace); +} + +nlohmann::json namesJson(const InstancePath& path) { + nlohmann::json names = nlohmann::json::array(); + for (const auto& ref : path) names.push_back(ref.name); + return names; +} + +} // namespace + +SchematicPainter::GroupAttrs SchematicView::instanceGroup(const InstanceShape& inst) { + if (inst.modelName == "port") { + const Port* p = inst.ports.empty() ? nullptr : &inst.ports[0]; + const char* dir = !p ? "" : p->direction == Direction::Input ? "input" + : p->direction == Direction::Output ? "output" : "inout"; + return { { "class", "port" }, { "data-name", p ? p->name : inst.name }, { "data-direction", dir } }; + } + if (inst.isSummary) + return { { "class", "summary" }, { "data-group", inst.summaryGroup }, + { "data-count", std::to_string(inst.summaryCount) } }; + SchematicPainter::GroupAttrs attrs{ { "class", inst.isHierGroup ? "module" : "instance" }, + { "data-path", displayPath(inst.path) }, + { "data-id-path", idPathText(inst.path) } }; + if (ambiguous(inst.path)) attrs.push_back({ "data-path-json", jsonText(namesJson(inst.path)) }); + if (!inst.model.empty()) attrs.push_back({ "data-model", inst.model }); + return attrs; +} + +SchematicPainter::GroupAttrs SchematicView::netGroup(const std::string& netName, const SchematicNetRef& driver, + const std::string& label) { + SchematicPainter::GroupAttrs attrs{ { "class", "net" }, { "data-net", netName } }; + if (driver.port) { + attrs.push_back({ "data-driver", driver.pin }); + } else { + attrs.push_back({ "data-driver", displayPath(driver.path) + ":" + driver.pin }); + attrs.push_back({ "data-driver-id-path", idPathText(driver.path) }); + if (ambiguous(driver.path, driver.pin)) + attrs.push_back({ "data-driver-json", + jsonText({ { "path", namesJson(driver.path) }, { "terminal", driver.pin } }) }); + } + if (!label.empty()) attrs.push_back({ "data-label", label }); + return attrs; +} + void SchematicView::render(ImDrawList* drawList, const ImVec2& canvasPos, const ImVec2& canvasSize) { ImDrawListPainter painter(drawList); render(painter, canvasPos, canvasSize); @@ -1378,8 +1446,10 @@ void SchematicView::render(SchematicPainter& painter, const ImVec2& canvasPos, c // so nested frames paint over their enclosing one. for (const auto& inst : instances) { if (inst.isHierGroup) { + dl->BeginGroup(instanceGroup(inst)); drawInstance(dl, inst, canvasPos, canvasSize); drawReviewBadge(dl, inst, *this, canvasPos, canvasSize); + dl->EndGroup(); } } @@ -1387,19 +1457,46 @@ void SchematicView::render(SchematicPainter& painter, const ImVec2& canvasPos, c // before. A net nested inside an expanded instance (containerShapeId set) // is drawn later instead -- see drawSubtree below -- so that instance's // opaque box fill doesn't get painted over it afterward. - for (const auto& route : routes) drawRoute(dl, route, canvasPos, canvasSize); - for (const auto& net : nets) { - if (net.containerShapeId < 0 && !net.routed) drawNet(dl, net, canvasPos, canvasSize); + for (const auto& route : routes) { + dl->BeginGroup(netGroup(route.netName, route.ref, route.label)); + drawRoute(dl, route, canvasPos, canvasSize); + dl->EndGroup(); } + // Unrouted wires, one group per run of wires from the same driver pin. + auto drawNets = [&](int containerShapeId) { + std::optional> open; + for (const auto& net : nets) { + if (net.containerShapeId != containerShapeId || net.routed) continue; + InstanceShape* src = findInstanceById(net.srcInstance); + const Port* srcPort = src ? findPortById(*src, net.srcPortId) : nullptr; + const std::pair key{ net.srcInstance, net.srcPortId }; + if (open != key) { + if (open) dl->EndGroup(); + open.reset(); + if (src && srcPort) { + dl->BeginGroup(netGroup(net.netName, + src->modelName == "port" + ? SchematicNetRef{ {}, srcPort->name, true } + : SchematicNetRef{ src->path, srcPort->name, false }, + net.label)); + open = key; + } + } + drawNet(dl, net, canvasPos, canvasSize); + } + if (open) dl->EndGroup(); + }; + drawNets(-1); // Recursive draw: a box, then the nets internal to it, then its nested // children on top of those nets -- so hierarchy embedding never hides a // wire under a box's fill or a child under its own internal wiring. std::function drawSubtree = [&](const InstanceShape& inst) { + dl->BeginGroup(instanceGroup(inst)); drawInstance(dl, inst, canvasPos, canvasSize); drawReviewBadge(dl, inst, *this, canvasPos, canvasSize); - for (const auto& net : nets) - if (net.containerShapeId == inst.id) drawNet(dl, net, canvasPos, canvasSize); + dl->EndGroup(); + drawNets(inst.id); for (const auto& child : instances) if (child.parentShapeId == inst.id) drawSubtree(child); }; @@ -1410,41 +1507,186 @@ void SchematicView::render(SchematicPainter& painter, const ImVec2& canvasPos, c dl->PopClipRect(); } -std::string SchematicView::exportSvg(float margin) const { +// --------------------------------------------------------------------------- +// Export page: the drawing, plus ViewOptions' decorations around it -- a +// title band above, the legend and a caption below. With none of them the +// page is the drawing alone, drawn exactly as before they existed. +// --------------------------------------------------------------------------- +namespace { + +constexpr float kTitleFontSize = 18.0f; +constexpr float kCaptionFontSize = 12.0f; +constexpr float kLegendFontSize = 12.0f; +constexpr float kLegendSwatchW = 24.0f; +constexpr float kLegendGap = 6.0f; // swatch to label +constexpr float kLegendSpacing = 18.0f; // between entries +constexpr ImU32 kTitleColor = IM_COL32(20, 20, 25, 255); +constexpr ImU32 kCaptionColor = IM_COL32(70, 70, 80, 255); + +struct TextBlock { + std::vector lines; + float size = 0.0f, lineH = 0.0f, w = 0.0f, h = 0.0f; +}; + +TextBlock measureText(const std::string& text, float size) { + TextBlock b; + if (text.empty()) return b; + ImFont* font = ImGui::GetFont(); + b.size = size; + b.lineH = font->CalcTextSizeA(size, FLT_MAX, 0.0f, "Xg").y; + size_t from = 0; + for (;;) { + const size_t nl = text.find('\n', from); + b.lines.push_back(text.substr(from, nl == std::string::npos ? std::string::npos : nl - from)); + if (nl == std::string::npos) break; + from = nl + 1; + } + for (const auto& line : b.lines) + b.w = std::max(b.w, font->CalcTextSizeA(size, FLT_MAX, 0.0f, line.c_str()).x); + b.h = b.lineH * float(b.lines.size()); + return b; +} + +struct ExportPage { + ImVec2 size, drawingAt, drawing; + bool decorated = false; + TextBlock title, caption; + ImVec2 titleAt, captionAt; + struct LegendItem { ImVec2 at; float textW = 0.0f; const SchematicView::LegendEntry* entry = nullptr; }; + std::vector legend; + float legendLineH = 0.0f; +}; + +ExportPage layoutPage(ImVec2 drawing, float margin, const ViewOptions& options, + const std::vector& legend) { + ExportPage page; + page.drawing = drawing; + page.title = measureText(options.title, kTitleFontSize); + page.caption = measureText(options.caption, kCaptionFontSize); + const bool withLegend = options.legend && !legend.empty(); + page.decorated = !page.title.lines.empty() || !page.caption.lines.empty() || withLegend; + if (!page.decorated) { + page.size = drawing; + return page; + } + ImFont* font = ImGui::GetFont(); + // Width: the drawing's, or more for a long title, caption or legend entry. + float width = std::max({ drawing.x, page.title.w + 2.0f * margin, page.caption.w + 2.0f * margin }); + std::vector textW; + if (withLegend) { + page.legendLineH = font->CalcTextSizeA(kLegendFontSize, FLT_MAX, 0.0f, "Xg").y; + for (const auto& e : legend) { + textW.push_back(font->CalcTextSizeA(kLegendFontSize, FLT_MAX, 0.0f, e.label.c_str()).x); + width = std::max(width, kLegendSwatchW + kLegendGap + textW.back() + 2.0f * margin); + } + } + float y = 0.0f; + if (!page.title.lines.empty()) { + page.titleAt = ImVec2(margin, margin); + y = margin + page.title.h; // the drawing's own margin follows + } + page.drawingAt = ImVec2(std::floor((width - drawing.x) * 0.5f), y); + y += drawing.y; + if (withLegend) { + // Entries left to right, wrapped at the page's inner width. + const float rowH = page.legendLineH + 6.0f; + float x = margin; + for (size_t i = 0; i < legend.size(); ++i) { + const float w = kLegendSwatchW + kLegendGap + textW[i]; + if (x > margin && x + w > width - margin) { x = margin; y += rowH; } + page.legend.push_back({ ImVec2(x, y), textW[i], &legend[i] }); + x += w + kLegendSpacing; + } + y += rowH; + } + if (!page.caption.lines.empty()) { + page.captionAt = ImVec2(margin, y + (withLegend ? 6.0f : 0.0f)); + y = page.captionAt.y + page.caption.h; + } + page.size = ImVec2(width, y + margin); + return page; +} + +void paintText(SchematicPainter& p, const TextBlock& b, ImVec2 at, ImU32 color) { + for (size_t i = 0; i < b.lines.size(); ++i) + p.AddText(ImGui::GetFont(), b.size, ImVec2(at.x, at.y + b.lineH * float(i)), color, b.lines[i].c_str()); +} + +void paintPage(SchematicPainter& p, SchematicView& sheet, const ExportPage& page) { + if (!page.decorated) { + sheet.render(p, ImVec2(0.0f, 0.0f), page.drawing); + return; + } + p.AddRectFilled(ImVec2(0.0f, 0.0f), page.size, IM_COL32(255, 255, 255, 255)); + sheet.render(p, page.drawingAt, page.drawing); + if (!page.title.lines.empty()) { + p.BeginGroup({ { "class", "title" } }); + paintText(p, page.title, page.titleAt, kTitleColor); + p.EndGroup(); + } + if (!page.legend.empty()) { + p.BeginGroup({ { "class", "legend" } }); + for (const auto& item : page.legend) { + p.BeginGroup({ { "class", "legend-entry" }, { "data-label", item.entry->label } }); + const float midY = item.at.y + page.legendLineH * 0.5f; + p.AddLine(ImVec2(item.at.x, midY), ImVec2(item.at.x + kLegendSwatchW, midY), item.entry->color, 3.0f); + p.AddText(ImGui::GetFont(), kLegendFontSize, ImVec2(item.at.x + kLegendSwatchW + kLegendGap, item.at.y), + kCaptionColor, item.entry->label.c_str()); + p.EndGroup(); + } + p.EndGroup(); + } + if (!page.caption.lines.empty()) { + p.BeginGroup({ { "class", "caption" } }); + paintText(p, page.caption, page.captionAt, kCaptionColor); + p.EndGroup(); + } +} + +} // namespace + +// The sheet an export draws: this view at 1x over the whole drawing, with +// `margin` around it, with no hover or pending feedback -- but the +// selection is kept, so an export can point at something. False if empty. +bool SchematicView::exportSheet(float margin, SchematicView& sheet, ImVec2& size) const { ImVec2 lo, hi; - if (!computeWorldBounds(lo, hi)) return ""; - // The whole sheet at 1x: nothing is small enough to fade out (see the - // label legibility helpers above), and no hover or pending feedback -- - // but the selection is kept, so an export can point at something. - SchematicView sheet = *this; + if (!computeWorldBounds(lo, hi)) return false; + sheet = *this; sheet.exporting = true; + sheet.hideUiGlyphs = ViewOptions::current().hideUiGlyphs; sheet.hoveredPortId = -1; sheet.transform = Transform{}; sheet.transform.offset = ImVec2(lo.x - margin, lo.y - margin); - const ImVec2 size(hi.x - lo.x + 2.0f * margin, hi.y - lo.y + 2.0f * margin); - SvgPainter svg(size); - sheet.render(svg, ImVec2(0.0f, 0.0f), size); + size = ImVec2(hi.x - lo.x + 2.0f * margin, hi.y - lo.y + 2.0f * margin); + return true; +} + +std::string SchematicView::exportSvg(float margin) const { + // At 1x nothing is small enough to fade out (see the label legibility + // helpers above). + SchematicView sheet; + ImVec2 drawing; + if (!exportSheet(margin, sheet, drawing)) return ""; + const ExportPage page = layoutPage(drawing, margin, ViewOptions::current(), sheet.legend); + SvgPainter svg(page.size); + paintPage(svg, sheet, page); return svg.finish(); } std::string SchematicView::exportPng(float scale, float margin) const { - ImVec2 lo, hi; - if (!(scale > 0.0f) || !computeWorldBounds(lo, hi)) return ""; - SchematicView sheet = *this; - sheet.exporting = true; - sheet.hoveredPortId = -1; - sheet.transform = Transform{}; - sheet.transform.offset = ImVec2(lo.x - margin, lo.y - margin); - const ImVec2 size(hi.x - lo.x + 2.0f * margin, hi.y - lo.y + 2.0f * margin); - if (double(size.x) * scale * double(size.y) * scale > kMaxPngPixels) return ""; + SchematicView sheet; + ImVec2 drawing; + if (!(scale > 0.0f) || !exportSheet(margin, sheet, drawing)) return ""; + const ExportPage page = layoutPage(drawing, margin, ViewOptions::current(), sheet.legend); + if (double(page.size.x) * scale * double(page.size.y) * scale > kMaxPngPixels) return ""; // Twice: the first drawing bakes the font sizes it needs into the atlas, // which may grow it and so move glyphs drawn before; the second finds // every glyph in place. { - RasterPainter warmup(size, scale); - sheet.render(warmup, ImVec2(0.0f, 0.0f), size); + RasterPainter warmup(page.size, scale); + paintPage(warmup, sheet, page); } - RasterPainter raster(size, scale); - sheet.render(raster, ImVec2(0.0f, 0.0f), size); + RasterPainter raster(page.size, scale); + paintPage(raster, sheet, page); return raster.png(); } diff --git a/src/SchematicView.h b/src/SchematicView.h index 7254534..0861456 100644 --- a/src/SchematicView.h +++ b/src/SchematicView.h @@ -97,6 +97,10 @@ class SchematicView { // The whole schematic as an SVG document, at 1x with `margin` world // units around it, without transient interaction feedback (hover, // pending pins); the selection is kept. "" when there is nothing to draw. + // Each net, instance, port flag, summary and module frame is a with + // data-* attributes naming it (the drawing itself is unchanged). The + // export decorations of ViewOptions::current() apply (title band above, + // legend and caption below, hide_ui_glyphs); exportPng() draws the same. std::string exportSvg(float margin = 24.0f) const; // The same drawing as a PNG file's bytes, `scale` pixels per SVG pixel // (RasterPainter: every stroke, radius and font size scaled with it, @@ -106,6 +110,19 @@ class SchematicView { static constexpr double kMaxPngPixels = 120e6; // Set on the copy exportSvg() draws: skips transient interaction feedback. bool exporting = false; + // Set on the export copy by ViewOptions' hide_ui_glyphs: leaves out the + // "more pins" dots of a partial box and the hollow stubs of open pins, + // which only mean something to a viewer's user (clicks). + bool hideUiGlyphs = false; + + // One row of an export's legend (ViewOptions' legend): a net color and + // what it stands for -- a visible trace's label, or a host style's + // label on a net. Filled by EquipotentialView with the shapes. + struct LegendEntry { + ImU32 color = 0; + std::string label; + }; + std::vector legend; bool computeWorldBounds(ImVec2& outMin, ImVec2& outMax) const; @@ -121,7 +138,15 @@ class SchematicView { // Every badge shown at the current zoom (hidden with the labels). std::vector reviewBadges(const ImVec2& canvasPos, const ImVec2& canvasSize) const; + // The attributes the export gives an instance box, port flag, + // fanout summary or module frame, and a net (named by its driver pin). + static SchematicPainter::GroupAttrs instanceGroup(const InstanceShape& inst); + static SchematicPainter::GroupAttrs netGroup(const std::string& netName, const SchematicNetRef& driver, + const std::string& label); + private: + bool exportSheet(float margin, SchematicView& sheet, ImVec2& size) const; + bool needsFit_ = true; bool hasUserInteraction_ = false; bool hasFitRect_ = false; diff --git a/src/StyleStore.cpp b/src/StyleStore.cpp index 4b20b28..702930c 100644 --- a/src/StyleStore.cpp +++ b/src/StyleStore.cpp @@ -131,6 +131,14 @@ std::vector StyleStore::parse(const nlohmann::json& j, std::vector" << escapeXml(text) << "\n"; } +void SvgPainter::BeginGroup(const GroupAttrs& attrs) { + out_ << "\n"; +} + +void SvgPainter::EndGroup() { out_ << "\n"; } + std::string SvgPainter::finish() { out_ << "\n"; return out_.str(); diff --git a/src/Types.cpp b/src/Types.cpp index 549a140..f562745 100644 --- a/src/Types.cpp +++ b/src/Types.cpp @@ -201,6 +201,8 @@ void from_json(const json& j, Equipotential& e) { term.direction = intToDirection(occJson["direction"].get()); } term.clock = occJson.value("clock", false); + if (occJson.contains("role") && occJson["role"].is_string()) + term.role = occJson["role"].get(); if (occJson.contains("bit") && !occJson["bit"].is_null()) { term.bit = occJson["bit"].get(); } else { diff --git a/src/Types.h b/src/Types.h index 8b679f7..dcf5b8a 100644 --- a/src/Types.h +++ b/src/Types.h @@ -192,6 +192,9 @@ struct BitTerm { Direction direction = Direction::Inout; std::optional bit; bool clock = false; // a sequential cell's clock pin (naja's isClock) + // naja's term role ("clock", "async_reset", "enable", ...; SNLTermRole), + // "" for a data pin (DataInput/DataOutput, or none set). + std::string role; // The pin's label: displayTermName() plus "[bit]" for a bus bit. std::string getString() const { @@ -490,6 +493,9 @@ struct InstanceShape { // made-up one (EquipotentialView), never sent to the host. bool isSummary = false; int summaryCount = 0; + // What its sinks have in common (the group_by key): the model, the + // module's path, the role or pin name. Named in the SVG export. + std::string summaryGroup; float x = 0.0f; float y = 0.0f; // world coords (top-left) float w = 100.0f; diff --git a/src/ViewOptions.cpp b/src/ViewOptions.cpp index 06ef89f..babed35 100644 --- a/src/ViewOptions.cpp +++ b/src/ViewOptions.cpp @@ -19,6 +19,7 @@ const char* ViewOptions::name(FanoutGroupBy v) { switch (v) { case FanoutGroupBy::Hierarchy: return "hierarchy"; case FanoutGroupBy::Role: return "role"; + case FanoutGroupBy::Pin: return "pin"; default: return "model"; } } @@ -49,7 +50,22 @@ bool ViewOptions::apply(const json& message, std::string& error) { if (s == "model") next.groupBy = FanoutGroupBy::Model; else if (s == "hierarchy") next.groupBy = FanoutGroupBy::Hierarchy; else if (s == "role") next.groupBy = FanoutGroupBy::Role; - else { error = "group_by: expected \"model\", \"hierarchy\" or \"role\", got " + v.dump(); return false; } + else if (s == "pin") next.groupBy = FanoutGroupBy::Pin; + else { error = "group_by: expected \"model\", \"hierarchy\", \"role\" or \"pin\", got " + v.dump(); return false; } + } + for (auto [key, field] : { std::pair{ "hide_ui_glyphs", &next.hideUiGlyphs }, + std::pair{ "legend", &next.legend }, + std::pair{ "convergence_outline", &next.convergenceOutline } }) { + if (!message.contains(key)) continue; + const json& v = message[key]; + if (!v.is_boolean()) { error = std::string(key) + ": expected true or false, got " + v.dump(); return false; } + *field = v.get(); + } + for (auto [key, field] : { std::pair{ "title", &next.title }, std::pair{ "caption", &next.caption } }) { + if (!message.contains(key)) continue; + const json& v = message[key]; + if (!v.is_string()) { error = std::string(key) + ": expected a string, got " + v.dump(); return false; } + *field = v.get(); } *this = next; return true; @@ -59,5 +75,17 @@ json ViewOptions::toJson() const { return { { "instance_label", name(instanceLabel) }, { "sink_rows", sinkRows }, { "max_sinks", maxSinks }, - { "group_by", name(groupBy) } }; + { "group_by", name(groupBy) }, + { "convergence_outline", convergenceOutline }, + { "hide_ui_glyphs", hideUiGlyphs }, + { "title", title }, + { "caption", caption }, + { "legend", legend } }; +} + +json ViewOptions::layoutJson() const { + json j = toJson(); + for (const char* key : { "convergence_outline", "hide_ui_glyphs", "title", "caption", "legend" }) + j.erase(key); + return j; } diff --git a/src/ViewOptions.h b/src/ViewOptions.h index 3e84385..af7e6bc 100644 --- a/src/ViewOptions.h +++ b/src/ViewOptions.h @@ -22,7 +22,8 @@ enum class InstanceLabel { enum class FanoutGroupBy { Model, // by cell model ("DFF x812") Hierarchy, // by the module containing the sink ("u_core/u_regs x812") - Role, // by the receiving pin: "clock" for a clock pin, else its name + Role, // by the receiving pin's naja role: "clock", "reset", "enable", ..., "data" + Pin, // by the receiving pin: "clock" for a clock pin, else its name }; struct ViewOptions { @@ -37,14 +38,34 @@ struct ViewOptions { // drawn. 0: never. int maxSinks = 32; FanoutGroupBy groupBy = FanoutGroupBy::Model; + // A box two or more visible traces go through is outlined in the + // near-black convergence color (never one the host styles). false: no + // such outline (shared wires still show the traces' stripes). + bool convergenceOutline = true; + + // Export decorations: they change only exported drawings (SVG and PNG, + // SchematicView::exportSvg()/exportPng()), never the canvas. + // No "more pins" dots on a partial box, no hollow open-pin stubs. + bool hideUiGlyphs = false; + // Text in a band above / below the drawing ("" = none; '\n' breaks lines). + std::string title; + std::string caption; + // A swatch and label below the drawing for each visible trace, and each + // net a host style labels. + bool legend = false; static ViewOptions& current(); // Applies the keys a view_options message (or a native flag) sets -- - // "instance_label", "sink_rows", "max_sinks", "group_by" -- leaving the - // others as they are. False, changing nothing, if one is malformed. + // "instance_label", "sink_rows", "max_sinks", "group_by", + // "convergence_outline", "hide_ui_glyphs", "title", "caption", "legend" + // -- leaving the others + // as they are. False, changing nothing, if one is malformed. bool apply(const nlohmann::json& message, std::string& error); nlohmann::json toJson() const; + // toJson() without the keys that don't move anything (export + // decorations, convergence_outline): what the layout depends on. + nlohmann::json layoutJson() const; static const char* name(InstanceLabel v); static const char* name(FanoutGroupBy v); diff --git a/src/main_native.cpp b/src/main_native.cpp index 693c5e9..7983a57 100644 --- a/src/main_native.cpp +++ b/src/main_native.cpp @@ -26,7 +26,8 @@ int main(int argc, char* argv[]) { // [--yosys-src] [--top ] // [--instance-label name|model|both] // [--sink-rows N] [--max-sinks N] - // [--group-by model|hierarchy|role] + // [--group-by model|hierarchy|role|pin] [--no-convergence-outline] + // [--title TEXT] [--caption TEXT] [--legend] [--hide-ui-glyphs] // [--export ] [--png [--scale S]] // [--focus ] [--trace ]... [--equipotential ]... // is loaded by extension (.sv/.v/.vhd/.vhdl/otherwise-assumed-SNL-directory); @@ -48,8 +49,13 @@ int main(int argc, char* argv[]) { // --source-root adds a directory relative source file references (Show // Sources) are looked up in (repeatable, tried in order, then the current // directory); - // --instance-label, --sink-rows, --max-sinks and --group-by set how the - // schematic is drawn (ViewOptions.h; also in the View menu); + // --instance-label, --sink-rows, --max-sinks (default 32, applied when + // not given; 0 turns summaries off), --group-by and + // --no-convergence-outline set how the schematic is drawn (ViewOptions.h; + // also in the View menu); + // --title, --caption, --legend and --hide-ui-glyphs decorate exports only + // (File > Export too): a text band above / below the drawing, a swatch + // per labeled trace or styled net, no open-pin stubs or "more pins" dots; // --export draws the schematic to an SVG file and exits, with no window, // --png to a PNG file, --scale pixels per SVG pixel (default 1); both // can be given (see HeadlessExport.h for what --focus/--trace/ @@ -98,6 +104,14 @@ int main(int argc, char* argv[]) { std::cerr << arg << ": " << error << "\n"; return 1; } + } else if ((arg == "--title" || arg == "--caption") && i + 1 < argc) { + ViewOptions::current().apply({ { arg.substr(2), std::string(argv[++i]) } }, error); + } else if (arg == "--legend") { + ViewOptions::current().legend = true; + } else if (arg == "--no-convergence-outline") { + ViewOptions::current().convergenceOutline = false; + } else if (arg == "--hide-ui-glyphs") { + ViewOptions::current().hideUiGlyphs = true; } else if (arg == "--focus" && i + 1 < argc) { exportOptions.focus = parseFocusArg(argv[++i], error); if (!exportOptions.focus) { std::cerr << error << "\n"; return 1; } diff --git a/tests/FanoutTest.cpp b/tests/FanoutTest.cpp index d3779b5..28a3ca7 100644 --- a/tests/FanoutTest.cpp +++ b/tests/FanoutTest.cpp @@ -6,8 +6,15 @@ #include "SchematicLayout.h" #include "SchematicView.h" #include "SelectionStore.h" +#include "StyleStore.h" +#include "TraceStore.h" #include "ViewOptions.h" +#include +#include +#include +#include + #include #include @@ -20,11 +27,12 @@ namespace { float charWidth(const std::string& s) { return 7.f * float(s.size()); } Item sinkItem(std::vector> path, const std::string& model, - const std::string& pin, bool clock = false) { + const std::string& pin, bool clock = false, const std::string& role = "") { Item it; it.label = pin; it.direction = Direction::Input; it.clock = clock; + it.role = role; for (const auto& [id, name] : path) { it.path.push_back({ id, name }); it.pathModels.push_back("M"); @@ -67,6 +75,98 @@ TEST(ViewOptions, AppliesKnownKeysAndRejectsBadValues) { EXPECT_FALSE(o.apply({ { "instance_label", "cell" } }, error)); EXPECT_TRUE(o.apply({ { "group_by", "hierarchy" } }, error)); EXPECT_EQ(o.toJson()["group_by"], "hierarchy"); + EXPECT_TRUE(o.apply({ { "group_by", "role" } }, error)); + EXPECT_EQ(o.groupBy, FanoutGroupBy::Role); + EXPECT_TRUE(o.apply({ { "group_by", "pin" } }, error)); + EXPECT_EQ(o.toJson()["group_by"], "pin"); +} + +TEST(ViewOptions, ExportDecorationsAreKeysButNotLayout) { + ViewOptions o; + std::string error; + EXPECT_TRUE(o.apply({ { "title", "T" }, { "caption", "C" }, { "legend", true }, { "hide_ui_glyphs", true } }, + error)); + EXPECT_EQ(o.title, "T"); + EXPECT_EQ(o.caption, "C"); + EXPECT_TRUE(o.legend); + EXPECT_TRUE(o.hideUiGlyphs); + EXPECT_EQ(o.toJson()["title"], "T"); + EXPECT_FALSE(o.layoutJson().contains("title")); + EXPECT_EQ(o.layoutJson(), ViewOptions{}.layoutJson()); + EXPECT_FALSE(o.apply({ { "legend", "yes" } }, error)); + EXPECT_NE(error.find("legend"), std::string::npos); + EXPECT_FALSE(o.apply({ { "title", 3 } }, error)); + EXPECT_EQ(o.title, "T"); +} + +// --------------------------------------------------------------------------- +// group_by "role": naja's term role of the receiving pin, not its name +// --------------------------------------------------------------------------- +TEST(PlanFanout, GroupsByTheReceivingPinsRole) { + // Flops whose pins are named nothing like their role, on clock, reset + // (async and sync), enable and data pins; LUT inputs with no role. + FanoutNet n; + n.drivers.push_back(driverItem(1, "drv")); + unsigned id = 100; + auto add = [&](int count, const std::string& model, const std::string& pin, bool clock, + const std::string& role) { + for (int i = 0; i < count; ++i, ++id) + n.receivers.push_back(sinkItem({ { id, "s" + std::to_string(id) } }, model, pin, clock, role)); + }; + add(6, "FF", "CK", true, "clock"); + add(2, "FF", "XC", true, ""); // modeled as a clock, no role set: still a clock + add(3, "FF", "R", false, "async_reset"); + add(2, "FF", "SR", false, "sync_reset"); + add(4, "FF", "L", false, "enable"); + add(3, "FF", "D", false, ""); // DataInput: no role sent + add(5, "LUT", "I1", false, ""); + add(2, "LUT", "I2", false, ""); + const std::vector nets{ n }; + + FanoutPlan plan = planFanout(nets, 1, FanoutGroupBy::Role, {}, nullptr); + std::map byLabel; + for (const auto& g : plan.groups) byLabel[g.label] = &g; + // The first sink (a CK pin) is drawn; the 26 others gathered in 4 groups. + ASSERT_EQ(plan.groups.size(), 4u); + ASSERT_TRUE(byLabel.count("clock \xC3\x97" "7")); + ASSERT_TRUE(byLabel.count("reset \xC3\x97" "5")); + ASSERT_TRUE(byLabel.count("enable \xC3\x97" "4")); + ASSERT_TRUE(byLabel.count("data \xC3\x97" "10")); + EXPECT_TRUE(byLabel["clock \xC3\x97" "7"]->clock); + EXPECT_EQ(byLabel["clock \xC3\x97" "7"]->pin, "clock"); // CK and XC + EXPECT_EQ(byLabel["reset \xC3\x97" "5"]->pin, "reset"); // R and SR + EXPECT_EQ(byLabel["enable \xC3\x97" "4"]->pin, "L"); // they all share it + EXPECT_FALSE(byLabel["data \xC3\x97" "10"]->clock); + + // "pin": the same sinks by name, the clock pins together. + plan = planFanout(nets, 1, FanoutGroupBy::Pin, {}, nullptr); + std::set labels; + for (const auto& g : plan.groups) labels.insert(g.label); + EXPECT_EQ(labels, (std::set{ "clock \xC3\x97" "7", "R \xC3\x97" "3", + "SR \xC3\x97" "2", "L \xC3\x97" "4", + "D \xC3\x97" "3", "I1 \xC3\x97" "5", + "I2 \xC3\x97" "2" })); +} + +TEST(PlanFanout, RoleGroupOfEveryNajaRole) { + auto group = [](const std::string& role, bool clock = false) { + return fanoutRoleGroup(sinkItem({ { 1, "u" } }, "M", "P", clock, role)); + }; + EXPECT_EQ(group("clock"), "clock"); + EXPECT_EQ(group("", true), "clock"); + EXPECT_EQ(group("async_reset"), "reset"); + EXPECT_EQ(group("sync_reset"), "reset"); + EXPECT_EQ(group("async_set"), "set"); + EXPECT_EQ(group("sync_set"), "set"); + EXPECT_EQ(group("enable"), "enable"); + EXPECT_EQ(group("memory_write_enable"), "enable"); + EXPECT_EQ(group("scan_input"), "scan"); + EXPECT_EQ(group("scan_enable"), "scan"); + EXPECT_EQ(group("memory_read_address"), "address"); + EXPECT_EQ(group("memory_write_address"), "address"); + EXPECT_EQ(group("memory_write_data"), "data"); + EXPECT_EQ(group(""), "data"); + EXPECT_EQ(group("something_new"), "data"); } // --------------------------------------------------------------------------- @@ -202,7 +302,7 @@ TEST(PlanFanout, ByHierarchyAndByRole) { EXPECT_EQ(plan.groups[0].label, "u_a \xC3\x97" "5"); EXPECT_EQ(displayPath(plan.groups[1].key.module), "u_b"); - plan = planFanout(nets, 1, FanoutGroupBy::Role, {}, nullptr); + plan = planFanout(nets, 1, FanoutGroupBy::Pin, {}, nullptr); ASSERT_EQ(plan.groups.size(), 2u); // in key order: the clock pins first EXPECT_TRUE(plan.groups[0].key.clock); EXPECT_TRUE(plan.groups[0].clock); @@ -351,3 +451,260 @@ TEST_F(FanoutView, SinkGridKeepsTheDrawingCompact) { EXPECT_LT(hi.y - lo.y, tall * 0.3f); EXPECT_EQ(boxes(), 31); } + +// --------------------------------------------------------------------------- +// Natural order +// --------------------------------------------------------------------------- +TEST(NaturalOrder, DigitRunsCompareByValue) { + EXPECT_TRUE(naturalLess("i_b1_lut_111", "i_b1_lut_1037")); + EXPECT_FALSE(naturalLess("i_b1_lut_1037", "i_b1_lut_111")); + EXPECT_TRUE(naturalLess("u2", "u10")); + EXPECT_TRUE(naturalLess("a9b", "a10a")); + EXPECT_TRUE(naturalLess("x", "x1")); + EXPECT_FALSE(naturalLess("same_7", "same_7")); + EXPECT_TRUE(naturalLess("r07", "r7") != naturalLess("r7", "r07")); // a strict order + EXPECT_TRUE(naturalLess("r99999999999999999999", "r100000000000000000000")); // no overflow + EXPECT_TRUE(naturalPathLess({ { 9, "u2" }, { 1, "x" } }, { { 3, "u10" }, { 0, "a" } })); +} + +// --------------------------------------------------------------------------- +// Several drivers' fanouts: bands, no crossings, natural order, and the +// convergence outline (the shape of a fanout-fix before/after figure). +// --------------------------------------------------------------------------- +namespace { + +class MultiDriverFanout : public ::testing::Test { + protected: + // Top-level `en` drives three registers; each register's O drives + // `sinks` LUTs, listed in a shuffled, non-natural order. + void SetUp() override { + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); + io.DisplaySize = ImVec2(1200.f, 800.f); + io.DeltaTime = 1.f / 60.f; + io.IniFilename = nullptr; + unsigned char* px; int w, h; + io.Fonts->GetTexDataAsRGBA32(&px, &w, &h); + EquipotentialView::setProvider(&provider); + EquipotentialView::resetLayout(); + SelectionStore::clear(); + TraceStore::clear(); + StyleStore::clear(); + saved = ViewOptions::current(); + ViewOptions::current() = ViewOptions{}; + } + void TearDown() override { + ViewOptions::current() = saved; + EquipotentialView::setProvider(nullptr); + EquipotentialView::resetLayout(); + SelectionStore::clear(); + TraceStore::clear(); + StyleStore::clear(); + for (auto* e : eqs) delete e; + ImGui::DestroyContext(); + } + static InstTermOccurrence pin(unsigned id, const std::string& name, const std::string& model, + const std::string& term, unsigned termId, Direction dir) { + InstTermOccurrence o; + o.path = { { id, name } }; + o.pathIds = { id }; + o.pathModels = { model }; + o.term = BitTerm{ term, termId, dir, std::nullopt }; + o.bit_term_count = 2; + return o; + } + void build(unsigned sinks, bool traced = false) { + const char* names[] = { "en_reg", "en_reg_fo1", "en_reg_fo2" }; + const int enTrace = traced ? TraceStore::begin("en") : -1; + Equipotential en{ true, {}, {} }; + en.terms.push_back(BitTerm{ "en", 0, Direction::Input, std::nullopt }); + for (unsigned d = 0; d < 3; ++d) en.occurrences.push_back(pin(1 + d, names[d], "REG", "D", 0, Direction::Input)); + if (traced) en.traceIds = { enTrace }; + eqs.push_back(new Equipotential(en)); + for (unsigned d = 0; d < 3; ++d) { + Equipotential o{ true, {}, {} }; + o.occurrences.push_back(pin(1 + d, names[d], "REG", "O", 1, Direction::Output)); + // Ids in a scrambled order, names with numbers of mixed widths. + for (unsigned i = 0; i < sinks; ++i) { + const unsigned k = (i * 7 + d) % sinks; + const unsigned num = (k % 2 ? 1000 : 100) + k * 3 + d; + o.occurrences.push_back(pin(100 + d * 1000 + (sinks - i), "i_b1_lut_" + std::to_string(num), "LUT1", "I0", 0, + Direction::Input)); + } + if (traced) o.traceIds = { TraceStore::begin(std::string(names[d]) + "/O") }; + eqs.push_back(new Equipotential(o)); + } + } + void frame(int n = 3) { + for (int i = 0; i < n; ++i) { + unsigned char* px; int w, h; + ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&px, &w, &h); + ImGui::NewFrame(); + ImGui::SetNextWindowPos(ImVec2(0.f, 0.f)); + ImGui::SetNextWindowSize(ImGui::GetIO().DisplaySize); + ImGui::Begin("Schematic", nullptr, + ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings); + EquipotentialView::renderSchematic(eqs); + ImGui::End(); + ImGui::Render(); + } + } + const SchematicView& sv() const { return EquipotentialView::schematicForTesting(); } + const InstanceShape* shape(const std::string& name) const { + for (const auto& s : sv().instances) + if (!s.isHierGroup && !s.path.empty() && s.path.back().name == name) return &s; + return nullptr; + } + // The boxes each driver's net reaches (its sinks), by driver shape id. + std::map> sinksByDriver() const { + std::map> out; + for (const auto& n : sv().nets) { + const InstanceShape* src = sv().findInstanceById(n.srcInstance); + const InstanceShape* dst = sv().findInstanceById(n.dstInstance); + if (src && dst && src->modelName != "port") out[src->id].push_back(dst); + } + return out; + } + // A net's sink columns: per column (box x), the rect from its first to + // its last sink box. + static std::vector sinkColumns(const std::vector& sinks) { + std::map byX; + for (const auto* s : sinks) { + auto [it, fresh] = byX.try_emplace(int(std::lround(s->x)), RouteRect{ s->x, s->y, s->x + s->w, s->y + s->h }); + if (!fresh) { + it->second.x1 = std::max(it->second.x1, s->x + s->w); + it->second.y0 = std::min(it->second.y0, s->y); + it->second.y1 = std::max(it->second.y1, s->y + s->h); + } + } + std::vector out; + for (const auto& [x, r] : byX) out.push_back(r); + return out; + } + static bool crosses(const RouteSegment& seg, const RouteRect& r) { + constexpr float eps = 0.5f; + const float x0 = std::min(seg.a.x, seg.b.x), x1 = std::max(seg.a.x, seg.b.x); + const float y0 = std::min(seg.a.y, seg.b.y), y1 = std::max(seg.a.y, seg.b.y); + return x1 > r.x0 + eps && x0 < r.x1 - eps && y1 > r.y0 + eps && y0 < r.y1 - eps; + } + + FakeNetlistProvider provider; + std::vector eqs; + ViewOptions saved; +}; + +} // namespace + +// The figure's case: no wire of one net runs through another net's sink +// columns -- the area from its first column to its last, top sink to +// bottom one, channels between the columns included -- with the default +// grid (8 rows) and summaries (32 sinks). +TEST_F(MultiDriverFanout, NoNetCrossesAnotherNetsSinkColumns) { + for (unsigned sinks : { 20u, 40u }) { + SCOPED_TRACE(sinks); + TearDown(); + eqs.clear(); + SetUp(); + build(sinks); + frame(); + const auto sinks3 = sinksByDriver(); + ASSERT_EQ(sinks3.size(), 3u); + int checked = 0; + for (const auto& route : sv().routes) { + if (route.ref.port) continue; // en: drives the three registers only + const InstanceShape* drv = nullptr; + for (const auto& [id, list] : sinks3) + if (sv().findInstanceById(id)->path == route.ref.path) drv = sv().findInstanceById(id); + ASSERT_NE(drv, nullptr) << route.ref.pin; + ASSERT_FALSE(route.segments.empty()); + for (const auto& [otherId, otherSinks] : sinks3) { + if (otherId == drv->id) continue; + const auto cols = sinkColumns(otherSinks); + ASSERT_GE(cols.size(), 2u); + RouteRect area = cols.front(); + for (const auto& c : cols) { + area.x0 = std::min(area.x0, c.x0); area.x1 = std::max(area.x1, c.x1); + area.y0 = std::min(area.y0, c.y0); area.y1 = std::max(area.y1, c.y1); + } + for (const auto& seg : route.segments) { + ++checked; + EXPECT_FALSE(crosses(seg, area)) + << drv->name << " crosses " << sv().findInstanceById(otherId)->name << "'s sink columns (" + << area.x0 << "," << area.y0 << " - " << area.x1 << "," << area.y1 << ") with segment " + << seg.a.x << "," << seg.a.y << " - " << seg.b.x << "," << seg.b.y; + } + } + } + EXPECT_GT(checked, 0); + } +} + +// Each driver's sinks sit in a band level with it, starting in the same +// column as every other driver's (no staircase), bands one under another. +TEST_F(MultiDriverFanout, EachDriversSinksAreABandLevelWithIt) { + build(40); + frame(); + const auto sinks3 = sinksByDriver(); + ASSERT_EQ(sinks3.size(), 3u); + float firstX = -1.f, prevBottom = -1e9f; + std::vector> byY; + for (const auto& [id, list] : sinks3) byY.push_back({ sv().findInstanceById(id)->y, id }); + std::sort(byY.begin(), byY.end()); + for (const auto& [y, id] : byY) { + const InstanceShape* drv = sv().findInstanceById(id); + const auto cols = sinkColumns(sinks3.at(id)); + ASSERT_GE(cols.size(), 2u) << drv->name; // a grid + if (firstX < 0.f) firstX = cols.front().x0; + EXPECT_FLOAT_EQ(cols.front().x0, firstX) << drv->name; // aligned columns + float top = 1e9f, bottom = -1e9f; + for (const auto& c : cols) { top = std::min(top, c.y0); bottom = std::max(bottom, c.y1); } + const float pinY = drv->y + drv->h * 0.5f; + EXPECT_GT(pinY, top) << drv->name; + EXPECT_LT(pinY, bottom) << drv->name; + EXPECT_GT(top, prevBottom) << drv->name; // bands don't overlap + prevBottom = bottom; + } +} + +// The first sinks drawn, and their order down a column, are natural +// (i_b1_lut_111 before i_b1_lut_1037), whatever order the host sent. +TEST_F(MultiDriverFanout, SinksAreInNaturalOrder) { + build(40); + frame(); + for (const auto& [id, list] : sinksByDriver()) { + std::vector drawn; + for (const auto* s : list) if (!s->isSummary) drawn.push_back(s); + ASSERT_EQ(drawn.size(), 32u); // max_sinks + // Reading order: columns left to right, each top to bottom. + std::sort(drawn.begin(), drawn.end(), [](const InstanceShape* a, const InstanceShape* b) { + return std::lround(a->x) != std::lround(b->x) ? a->x < b->x : a->y < b->y; + }); + for (size_t i = 1; i < drawn.size(); ++i) + EXPECT_TRUE(naturalLess(drawn[i - 1]->path.back().name, drawn[i]->path.back().name)) + << drawn[i - 1]->path.back().name << " before " << drawn[i]->path.back().name; + // The summarized ones all come after the drawn ones. + const auto summary = std::find_if(list.begin(), list.end(), [](auto* s) { return s->isSummary; }); + ASSERT_NE(summary, list.end()); + EXPECT_EQ((*summary)->summaryCount, 8); + } +} + +// A register on two visible traces (en and its own O) converges: outlined +// in near-black -- unless it's styled, or convergence_outline is off. +TEST_F(MultiDriverFanout, ConvergenceOutlineSkipsStyledBoxesAndCanBeTurnedOff) { + build(4, /*traced=*/true); + frame(); + ASSERT_NE(shape("en_reg"), nullptr); + EXPECT_EQ(shape("en_reg")->diagOutline, TraceStore::convergenceColor()); + StyleStore::setStyles(StyleStore::parse(nlohmann::json::parse( + R"({"items": [{"kind": "instance", "id_path": [1], "fill": "#1f77b455"}]})"))); + frame(); + EXPECT_EQ(shape("en_reg")->diagOutline, 0u); // styled + EXPECT_EQ(shape("en_reg_fo1")->diagOutline, TraceStore::convergenceColor()); // not styled + ViewOptions::current().convergenceOutline = false; + frame(); + EXPECT_EQ(shape("en_reg_fo1")->diagOutline, 0u); + std::string error; + EXPECT_TRUE(ViewOptions::current().apply({ { "convergence_outline", true } }, error)); + EXPECT_FALSE(ViewOptions::current().layoutJson().contains("convergence_outline")); +} diff --git a/tests/StyleStoreTest.cpp b/tests/StyleStoreTest.cpp index c4fe47d..46e7778 100644 --- a/tests/StyleStoreTest.cpp +++ b/tests/StyleStoreTest.cpp @@ -58,9 +58,13 @@ TEST_F(StyleStoreTest, MalformedItemsAreSkippedAndReported) { {{"kind", "wire"}, {"path", {"u1"}}}, // unknown kind {{"kind", "instance"}, {"path", {""}}}, // anonymous by name {{"kind", "instance"}, {"id_path", {1}}, {"fill", "#00ff0080"}}, // fine + {{"kind", "instance"}, {"target", "u1/u2"}, {"fill", "#00ff0080"}}, // the host resolves it + {{"kind", "net"}, {"target", {json::array(), "en"}}}, // same }), &errors); EXPECT_EQ(items.size(), 1u); - EXPECT_EQ(errors.size(), 4u); + ASSERT_EQ(errors.size(), 6u); + EXPECT_NE(errors[4].find("\"target\" is resolved by the naja-schematic Python host"), + std::string::npos) << errors[4]; } TEST_F(StyleStoreTest, InstancesMatchByIdPathElseByNamesAndMergeInOrder) { diff --git a/tests/SvgExportTest.cpp b/tests/SvgExportTest.cpp new file mode 100644 index 0000000..41c47fb --- /dev/null +++ b/tests/SvgExportTest.cpp @@ -0,0 +1,376 @@ +// The schematic export's structure (SVG groups with data-* attributes) and +// decorations (title, caption, legend, hide_ui_glyphs), on the real +// EquipotentialView in a headless ImGui context -- and a golden file holding +// the drawing as it was before the groups existed: an export with no +// decoration must still draw exactly that, group tags aside. +#include "EquipotentialView.h" +#include "SchematicView.h" +#include "SelectionStore.h" +#include "StyleStore.h" +#include "TraceStore.h" +#include "ViewOptions.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FakeNetlistProvider.h" + +namespace { + +InstTermOccurrence occ(std::vector> path, const std::string& model, + const std::string& term, unsigned termId, Direction dir, size_t bitTermCount) { + InstTermOccurrence o; + for (const auto& [id, name] : path) { + o.path.push_back({ id, name }); + o.pathIds.push_back(id); + o.pathModels.push_back("M"); + } + o.pathModels.back() = model; + o.term = BitTerm{ term, termId, dir, std::nullopt }; + o.bit_term_count = bitTermCount; + return o; +} + +class SvgExport : public ::testing::Test { + protected: + void SetUp() override { + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); + io.DisplaySize = ImVec2(1200.f, 800.f); + io.DeltaTime = 1.f / 60.f; + io.IniFilename = nullptr; + unsigned char* px; int w, h; + io.Fonts->GetTexDataAsRGBA32(&px, &w, &h); + EquipotentialView::setProvider(&provider); + EquipotentialView::resetLayout(); + SelectionStore::clear(); + TraceStore::clear(); + StyleStore::clear(); + ViewOptions::current() = ViewOptions{}; + } + + void TearDown() override { + EquipotentialView::setProvider(nullptr); + EquipotentialView::resetLayout(); + SelectionStore::clear(); + TraceStore::clear(); + StyleStore::clear(); + ViewOptions::current() = ViewOptions{}; + for (auto* eq : eqs) delete eq; + ImGui::DestroyContext(); + } + + void add(Equipotential eq) { eqs.push_back(new Equipotential(std::move(eq))); } + + void frame(int n = 1) { + for (int i = 0; i < n; ++i) { + unsigned char* px; int w, h; + ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&px, &w, &h); + ImGui::NewFrame(); + ImGui::SetNextWindowPos(ImVec2(0.f, 0.f)); + ImGui::SetNextWindowSize(ImGui::GetIO().DisplaySize); + ImGui::Begin("Schematic", nullptr, + ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings); + EquipotentialView::renderSchematic(eqs); + ImGui::End(); + ImGui::Render(); + } + } + + // The scene: top-level input `en` into u1.A; u1.Q (traced, labeled) to + // u2.A, u2 drawn with a partial interface, then expanded (open pins); an + // escaped name holding '/' and a space; u1.Q also fans out to five flops, + // gathered past max_sinks=4 (natural name order) into a summary. + int scene() { + const int trace = TraceStore::begin("u1/Q (net)"); + Equipotential in{ true, {}, {} }; + in.terms.push_back(BitTerm{ "en", 0, Direction::Input, std::nullopt }); + in.occurrences.push_back(occ({ { 1, "u1" } }, "AND2", "A", 10, Direction::Input, 3)); + add(in); + Equipotential q{ true, {}, {} }; + q.occurrences.push_back(occ({ { 1, "u1" } }, "AND2", "Q", 12, Direction::Output, 3)); + q.occurrences.push_back(occ({ { 4, "top" }, { 2, "u2" } }, "BOX3", "A", 20, Direction::Input, 3)); + q.occurrences.push_back(occ({ { 3, "\\a/b c " } }, "BUF", "I", 30, Direction::Input, 2)); + for (unsigned i = 0; i < 5; ++i) + q.occurrences.push_back(occ({ { 100 + i, "r" + std::to_string(i) } }, "DFF", "D", 40, Direction::Input, 3)); + q.traceIds = { trace }; + add(q); + ViewOptions::current().maxSinks = 4; + frame(3); + return trace; + } + + std::string svg() const { return EquipotentialView::exportSvg(); } + const SchematicView& sv() const { return EquipotentialView::schematicForTesting(); } + + FakeNetlistProvider provider; + std::vector eqs; +}; + +// The export with every and line taken out: what was drawn. +std::string withoutGroups(const std::string& svg) { + std::istringstream in(svg); + std::string out, line; + while (std::getline(in, line)) + if (line.rfind("> groups(const std::string& svg, const std::string& cls) { + std::vector> out; + std::regex tag("]*)>"); + std::regex attr(" ([a-z-]+)=\"([^\"]*)\""); + for (auto it = std::sregex_iterator(svg.begin(), svg.end(), tag); it != std::sregex_iterator(); ++it) { + std::map attrs; + const std::string body = (*it)[1]; + for (auto a = std::sregex_iterator(body.begin(), body.end(), attr); a != std::sregex_iterator(); ++a) + attrs[(*a)[1]] = (*a)[2]; + if (attrs["class"] == cls) out.push_back(attrs); + } + return out; +} + +const std::map* find(const std::vector>& gs, + const std::string& key, const std::string& value) { + for (const auto& g : gs) + if (auto it = g.find(key); it != g.end() && it->second == value) return &g; + return nullptr; +} + +} // namespace + +#ifdef NAJA_SCHEMATIC_TEST_DATA +// The drawing is the same, byte for byte, as before the groups existed. +// NAJA_SCHEMATIC_UPDATE_GOLDEN=1 rewrites the file (only for a deliberate +// drawing change). +TEST_F(SvgExport, DrawingWithoutDecorationsMatchesTheGolden) { + scene(); + const std::string drawn = withoutGroups(svg()); + ASSERT_FALSE(drawn.empty()); + const std::string path = std::string(NAJA_SCHEMATIC_TEST_DATA) + "/export_golden.svg"; + if (std::getenv("NAJA_SCHEMATIC_UPDATE_GOLDEN")) { + std::ofstream(path, std::ios::binary) << drawn; + GTEST_SKIP() << "wrote " << path; + } + const std::string golden = readFile(path); + ASSERT_FALSE(golden.empty()) << path; + EXPECT_EQ(drawn, golden); +} +#endif + +// The text between a group's opening tag (found by `marker`) and its . +std::string groupBody(const std::string& svg, const std::string& marker) { + const size_t at = svg.find(marker); + if (at == std::string::npos) return ""; + const size_t from = svg.find('\n', at) + 1; + return svg.substr(from, svg.find("", from) - from); +} + +TEST_F(SvgExport, EveryNetInstancePortAndSummaryIsAGroup) { + scene(); + const std::string out = svg(); + // Balanced: every group closed. + size_t opened = 0, closed = 0; + for (size_t p = out.find(""); p != std::string::npos; p = out.find("", p + 1)) ++closed; + EXPECT_EQ(opened, closed); + + const auto nets = groups(out, "net"); + ASSERT_EQ(nets.size(), sv().routes.size()); + const auto* en = find(nets, "data-driver", "en"); + ASSERT_NE(en, nullptr); + EXPECT_EQ(en->at("data-net"), "en"); + EXPECT_EQ(en->count("data-driver-id-path"), 0u); // a top-level port + const auto* q = find(nets, "data-driver", "u1:Q"); + ASSERT_NE(q, nullptr); + EXPECT_EQ(q->at("data-driver-id-path"), "1"); + // Its wires and junction dots are inside it. + const std::string qBody = groupBody(out, "data-driver=\"u1:Q\""); + EXPECT_NE(qBody.find("at("data-id-path"), "1"); + EXPECT_EQ(u1->at("data-model"), "AND2"); + EXPECT_EQ(u1->count("data-path-json"), 0u); + const std::string u1Body = groupBody(out, "data-path=\"u1\""); + EXPECT_NE(u1Body.find(">u1"), std::string::npos); // its name + EXPECT_NE(u1Body.find(">Q"), std::string::npos); // its pins + const auto* u2 = find(insts, "data-id-path", "4,2"); + ASSERT_NE(u2, nullptr); + EXPECT_EQ(u2->at("data-path"), "top/u2"); + // An escaped name with '/' and a space: the text form is ambiguous, so + // the path is also JSON (XML-escaped in the file). + const auto* esc = find(insts, "data-id-path", "3"); + ASSERT_NE(esc, nullptr); + EXPECT_EQ(esc->at("data-path"), "\\a/b c "); + EXPECT_EQ(esc->at("data-path-json"), "["\\\\a/b c "]"); + + const auto ports = groups(out, "port"); + ASSERT_EQ(ports.size(), 1u); + EXPECT_EQ(ports[0].at("data-name"), "en"); + EXPECT_EQ(ports[0].at("data-direction"), "input"); + EXPECT_NE(groupBody(out, "class=\"port\"").find(">en"), std::string::npos); + + const auto sums = groups(out, "summary"); + ASSERT_EQ(sums.size(), 1u); + EXPECT_EQ(sums[0].at("data-group"), "DFF"); + EXPECT_EQ(sums[0].at("data-count"), "2"); // r3, r4 + + const auto mods = groups(out, "module"); + ASSERT_EQ(mods.size(), 1u); + EXPECT_EQ(mods[0].at("data-path"), "top"); +} + +TEST_F(SvgExport, AStyleLabelIsOnItsNetGroup) { + scene(); + std::vector errors; + StyleStore::setStyles(StyleStore::parse(nlohmann::json::parse(R"({"items": [ + {"kind": "net", "id_path": [1], "terminal": "Q", "color": "#1f77b4", "label": "copy 0"}]})"), &errors)); + ASSERT_TRUE(errors.empty()) << errors[0]; + frame(2); + const auto nets = groups(svg(), "net"); + const auto* q = find(nets, "data-driver", "u1:Q"); + ASSERT_NE(q, nullptr); + EXPECT_EQ(q->at("data-label"), "copy 0"); +} + +TEST_F(SvgExport, TitleCaptionAndLegendFrameTheDrawing) { + const int trace = scene(); + const std::string plain = svg(); + ViewOptions::current().title = "Fan-out of u1/Q"; + ViewOptions::current().caption = "line one\nline "; + ViewOptions::current().legend = true; + const std::string out = svg(); + // The same drawing, moved down by the title band. + EXPECT_NE(out.find(""), std::string::npos); + EXPECT_NE(groupBody(out, "class=\"title\"").find(">Fan-out of u1/Q"), std::string::npos); + const std::string caption = groupBody(out, "class=\"caption\""); + EXPECT_NE(caption.find(">line one"), std::string::npos); + EXPECT_NE(caption.find(">line <two>"), std::string::npos); + // One legend entry: the trace, in its color. + const auto entries = groups(out, "legend-entry"); + ASSERT_EQ(entries.size(), 1u); + EXPECT_EQ(entries[0].at("data-label"), "u1/Q (net)"); + const ImU32 c = TraceStore::color(trace); + char rgb[48]; + std::snprintf(rgb, sizeof(rgb), "stroke=\"rgb(%u,%u,%u)\"", c & 0xFF, (c >> 8) & 0xFF, (c >> 16) & 0xFF); + EXPECT_NE(groupBody(out, "class=\"legend-entry\"").find(rgb), std::string::npos) << rgb; + // A taller page; the groups of the drawing are all still there. + auto height = [](const std::string& s) { + const size_t at = s.find(" height=\"") + 9; + return std::stof(s.substr(at, s.find('"', at) - at)); + }; + EXPECT_GT(height(out), height(plain) + 30.f); + EXPECT_EQ(groups(out, "net").size(), groups(plain, "net").size()); + EXPECT_EQ(groups(out, "instance").size(), groups(plain, "instance").size()); + + // A hidden trace isn't in the legend; legend with nothing to list adds nothing. + ViewOptions::current().title.clear(); + ViewOptions::current().caption.clear(); + TraceStore::setVisible(trace, false); + frame(2); + EXPECT_TRUE(groups(svg(), "legend-entry").empty()); + EXPECT_EQ(withoutGroups(svg()).find("class=\"legend\""), std::string::npos); +} + +TEST_F(SvgExport, DecorationsNeverReachTheCanvasLayout) { + scene(); + const auto before = sv().transform.scale; + ViewOptions::current().title = "t"; + frame(2); + EXPECT_EQ(sv().transform.scale, before); +} + +TEST_F(SvgExport, HideUiGlyphsDropsMorePinsDotsAndOpenStubs) { + scene(); + EquipotentialView::applyInstanceExpansion(InstancePath{ { 4, "top" }, { 2, "u2" } }, { + { "A", Direction::Input, 20, std::nullopt }, + { "B", Direction::Input, 21, std::nullopt }, + { "Y", Direction::Output, 22, std::nullopt }, + }); + frame(2); + auto circles = [](const std::string& s) { + size_t n = 0; + for (size_t p = s.find("