Skip to content

Latest commit

 

History

History
217 lines (187 loc) · 17.3 KB

schematic-editor.md

File metadata and controls

217 lines (187 loc) · 17.3 KB

Schematic editor

Status: section 1 describes the legacy GTK editor (retired in M15, ADR 0030); sections 2–6 are the Phase 1 design notes, realised by the M7 proof of concept and the M10 editor; sections 7 (M7 proof of concept) and 8 (M10 editor) are current. Library choice: custom SVG, accepted 2026-11-29 (ADR 0005); the maxGraph prototype was removed after the decision. Navigation: index · frontend · backend · project format · ADR 0004 · ADR 0005.

1. Legacy implementation (GTK, retired in M15)

  • view/drawing.py (DrawingView) draws onto a Gtk.DrawingArea with Cairo: background grid, template border, title block, elements, selection, floating insert model and wire preview. A cached background surface speeds redraws.
  • Interaction modes: default, box selection, insert (floating model with rotate R and port cycling C), add wire (click points, finish on double/middle click or on a port, cancel with right click or Escape).
  • Each element draws itself from schem_model (primitives in grid units) and text_model (${...} label templates over field values, evaluated by the safe expression evaluator since M3; Mako before). Orientation is a 90° rotation; there is no mirroring or free rotation.
  • Connectivity is computed later by NetworkModel from coincident port coordinates; the editor does not maintain connection records.
  • The same Cairo code produces drawing PDFs and prints.

2. Principles for the new editor

  1. Canonical data stays in Python. Elements, wires, positions, orientation, fields, sheets and connectivity rules live in the backend document. The frontend library holds a disposable view model rebuilt from backend state.
  2. Connectivity semantics do not change. Ports connect when coordinates coincide on a sheet; references connect across sheets by ref. The frontend may display derived connections (junction dots, highlighted nets) computed by the backend; it never decides them.
  3. Edits are commands. Pointer interactions produce commands (drawing.insert, drawing.move, drawing.add_wire, drawing.edit_wire, drawing.rotate, ...). The backend snaps, validates, applies, records undo and returns authoritative geometry plus connectivity changes.
  4. No library undo. The library's own undo manager is disabled; undo/redo goes through the backend history.
  5. Exact coordinates. Committed coordinates are integers in drawing units; the adapter rounds library floats before sending and never writes back rounded-off values without a command.
  6. Labels are computed in Python. The backend sends rendered label lines for each element; the frontend only lays them out. This retires Mako on the rendering path without duplicating formatting rules in TypeScript.

3. Symbol pipeline

Step Output Notes
Convert schem_model → SVG (one-off tool, then maintained) gelectrical/symbols/svg/<code>.svg Primitive mapping: LINE→<line>, CURVE→cubic <path>, ARC→arc <path>, CIRCLE→<circle>, RECT→<rect>, PATH→<path>; dash arrays and the four stroke widths become classes
Port and anchor metadata <circle class="eui-port" data-port="0" cx cy r="0"/> + data-anchor Ports in drawing units relative to the element origin; editable in Inkscape (object properties/XML editor)
Parameterised symbols gelectrical/symbols/definitions/<code>.json For busbar width, reference box width, transformer variants, display text box: parameters → primitive list generated by Python
Text slots data-label-slot positions Label lines come from the backend
Sprite for the frontend generated symbols.svg sprite or per-symbol strings Built from the same files; no hand-copied paths in TypeScript
PDF output Cairo renderer in gelectrical/symbols/render_cairo.py Consumes the same definitions; replaces per-element render_element

Static symbols are edited in Inkscape (plain SVG, no Inkscape-only features required). A validation script checks that each symbol's ports match the element class ports exactly; mismatches fail the build. During migration, a parity test renders each element with the legacy render_element and the new renderer to PNG and compares within a pixel tolerance.

Automatic conversion is expected to cover all current primitives, because schem_model is already declarative data. Elements that build schem_model dynamically in render_element (for example busbar, reference box, switches with state, display text) become parameterised definitions.

4. Requirements and evaluation

Both candidates render SVG in the webview. "maxGraph" means @maxgraph/core (Apache-2.0, TypeScript successor of mxGraph). "Custom SVG" means Vue-rendered SVG with EngineeringUI drawing/ utilities (viewport, grid, snapping, selection), optionally using SVG.js (MIT) for DOM manipulation.

Requirement GElectrical need maxGraph (to verify) Custom SVG
Custom electrical symbols ~35 element types Stencils or SVG image shapes; custom Shape classes Direct <use>/inline SVG
SVG symbol definitions Inkscape-editable SVG as image shape loses per-element styling; stencil XML is a separate format Native
Dynamic/parameterised symbols Busbar width, ref box, switch state Custom shape classes Re-render from backend primitives
Connection ports Port metadata per symbol Connection constraints or port child cells Port markers + hit areas
Adjustable busbars Width changes ports Custom resize handler + recompute ports Custom handle
Orthogonal and manual wires Polylines with grid points; free routing Edge styles (OrthConnector, segment edges), waypoints Polyline editing handles
Junctions and branches Coordinate coincidence, T-junctions Edges terminate on cells; dangling terminal points possible; junctions need extra vertices Junction dots from backend net data
Grid snapping 16-unit grid, 8-unit ports Built-in grid Utility in drawing/
Precise coordinates Integer drawing units Float geometry; adapter rounding Full control
Rotation 90° orientation today Style rotation Transform attribute
Selection, box select, toggle Required Built in (rubberband) Utility
Grouping and assemblies Assembly boxes Groups (cells with children) Overlay rectangles
Copy/paste Backend payload Backend payload either way Backend payload
Undo/redo Backend history Disable library undo Backend history
Multiple sheets One canvas per sheet One graph model per sheet One component per sheet
Border and title block Must match PDF Background image/layer Backend-generated SVG layer
Dynamic labels Backend label lines Cell labels / HTML labels <text> elements
Analysis overlays Node results, loading colours, markers Overlays or extra cells Overlay layer
Zoom and pan Required Built in Utility
Large schematic performance Target below Proven at scale in diagram apps Must be measured
Vector PDF Cairo backend (unchanged) Not used for PDF Not used for PDF
High-DPI / fractional scaling Required SVG SVG

Selection criteria (decision gate for M7)

# Criterion Weight Pass condition
1 Connectivity fidelity must Backend connectivity after PoC edits equals the legacy engine for all sample projects
2 Coordinate fidelity must Load → display → save without edits is byte-identical in canonical JSON
3 Symbol fidelity must All element types render; PNG diff with legacy within tolerance
4 Interaction completeness high Insert, rotate, port cycle, wire draw/edit, junctions, select/box/toggle, move, delete, assemblies, zoom/pan, keyboard shortcuts
5 Performance high 1,000 elements + 2,000 wire segments on one sheet: pan/zoom frame under 16 ms median, selection update under 100 ms, initial load under 1 s on a mid-range laptop
6 Code size and clarity medium Adapter code that a contributor can follow; no fighting the library's model
7 Accessibility medium Keyboard selection and movement; screen-reader names for elements
8 Maintenance and licence must Active releases, Apache-2.0/MIT, no proprietary add-ons
9 Bundle size low Measured and recorded

Choose maxGraph if it passes all must criteria and is not worse on criteria 4–6. Otherwise choose custom SVG. Record the measurements and the decision in ADR 0005. Main known risk for maxGraph: its edge-to-terminal connection model differs from coordinate-coincidence connectivity, so the adapter may need to suppress most of maxGraph's connection logic.

5. Editing behaviour notes

  • Moving elements: today a drag moves a single element by deleting it and re-inserting it at the end of the element list (its positional identity changes); wires are not dragged along, so connections break if wire endpoints no longer coincide. Parity keeps the connectivity behaviour; stable uids remove the identity change. Parity comes first (owner decision Q6); moving multiple selected elements is an enhancement after M15 or behind an option. A "keep connections" option (backend adjusts attached wire endpoints in the same command, with preview) is an enhancement and must be listed as Changed.
  • Automatic routing and snapping must never create or break connections silently. The backend returns connectivity deltas (joined, split node sets); the editor shows them, and MCP responses report them.
  • Display nodes: analysis node markers become an overlay, not document elements (backend).

6. Proof of concept scope (M7)

  1. Symbol converter: generate SVG for every registered element from schem_model; port metadata; validation script.
  2. Load sample.gepro through a fixture JSON export (no live backend required initially), render both sheets with border and title block.
  3. Implement insert, move, rotate, wire drawing with junctions, box selection and zoom/pan in both candidates on the same fixture.
  4. Send edits to a stub command recorder; replay them through the Python engine in a test and compare connectivity with the legacy result.
  5. Generate a 1,000-element synthetic sheet; measure criteria 5.
  6. Write ADR 0005 with results.

7. M7 proof of concept (current)

Implemented on feat/m7-schematic-editor-poc; results and the decision record in ADR 0005, evidence in the validation log.

Part Location Notes
Vector scenes gelectrical/symbols/scene.py Headless. schem_model primitives → SVG path items (d, fill, dash, width code) in element-local drawing units; labels formatted and laid out in Python (baseline positions, size in drawing units, text backend metrics); element transform, global ports, extents, wire points, assembly children; junction points (three or more coincident ports, display only); title block and border as frame
Symbol files gelectrical/symbols/svg/<code>.svg Generated for every registered element (default instance) with <circle class="eui-port" data-port> markers; tools/schematic/export.py symbols [--check]. Not used at run time yet (no packaging entry needed until M9)
Fixtures modern/src/schematic/fixtures/{sample,catalog}.json tools/schematic/export.py fixture / catalog; stand-ins for a drawing.scene query (M9). Fixture ids are s<sheet>e<index>
Drawing utilities packages/engineering-ui/src/drawing/ (@kavilgroup/engineering-ui/drawing, MIT) Viewport (world/screen, zoom about a point, fit), grid snapping and exact integer points, nearest port, box and toggle selection. No components yet
Candidate A: maxGraph (removed) was modern/src/schematic/maxgraph/ @maxgraph/core 0.25.1. Elements as vertices with a custom shape painting scene paths through the canvas API, wires as terminal-less edges, frame as a locked cell. Removed with its path parser and dependency after ADR 0005 was accepted; findings in the ADR
Chosen: custom SVG modern/src/schematic/svg/ Vue SVG: scene paths inserted as-is, theme tokens through CSS classes, one viewport transform; selection, box selection, move, insert and wire handling with the EngineeringUI utilities
Shared modern/src/schematic/{types,editing,stubBackend,synthetic}.ts Scene types; key bindings (legacy R/C/Escape plus Delete, Enter, Backspace, F, +/-, Tab, arrows, Ctrl+A); PoC-only stub that records the M4 commands and applies provisional geometry; 1,000-element synthetic sheet
PoC page modern/schematic-poc.html (npm run dev, then /schematic-poc.html) Data set, sheet, tools, theme; command log; window.__schematicPoc automation and measurement hooks
Scenario and measurements tools/schematic_poc_bench.mjs, tests/schematic/poc_scenario.json Scripted pointer/keyboard actions (Playwright, Chromium): commands and resulting geometry must equal the committed scenario; coordinate fidelity; timings; bundle size
Replay tests/services/test_schematic_replay.py Recorded commands through the real services vs the legacy engine driven like the GTK view; displayed geometry vs backend

Interaction notes from the PoC:

  • Edits are sent with the snapped point the user saw (port under the pointer, else the grid point), so backend snapping is idempotent and the displayed result equals the committed one (checked by the replay test).
  • Moves send a grid-multiple delta (drawing.move), never absolute positions; ports stay on the grid whatever the element's extents.
  • Box selection selects elements whose extents touch the box, like DrawingModel.update_select.
  • New interactions without a GTK equivalent (rotating a placed element, keyboard moves, Tab to the next element) use the existing M4 commands.
  • Not prototyped: wire point editing (drawing.edit_wire), assembly creation, copy/paste, busbar resizing, analysis overlays.

8. M10 editor (current)

Implemented on feat/m10-schematic-editing; decisions in ADR 0022, evidence in the validation log M10 entry.

Part Location Notes
Editor view modern/src/components/SchematicView.vue Backend scene plus transient state: tool, drag ghost, floating model, wire preview, port highlight, rubber band. Emits intents (place, wire, move, delete, rotate); publishes its viewport in data-view for automation
Tools and snapping modern/src/schematic/tools.ts Tool state (select, place from the palette or the clipboard, wire), legacy zoom steps, display snapping with the engine's rules (first port in the 16-unit pick box, else grid point), drawing keys
Commands modern/src/composables/useEditor.ts One backend command per intent with if_revision; insert preview through drawing.floating_scene; palette catalogue and icons; clipboard; sheets; references; inspector edits; view memory per sheet
Palette, sheets, inspector, dialogs modern/src/components/ PalettePanel (B01, A14), SheetList (B18), InspectorPanel (B03, B19, element fields), RenumberDialog (B16), LinkReferencesDialog (B15), ShortcutsDialog (A16, modern/src/shortcuts.ts)
Backend additions modern/backend/services/drawing.py, catalog.py Query drawing.floating_scene; drawing.paste orientation; insert-time fields update the symbol before anchoring; runtime method catalog.icons
Workflows and replay modern/e2e/editing.spec.ts, tests/schematic/m10_scenario.json, tests/services/test_schematic_replay.py Every row through the shell; recorded commands replayed against the legacy engine

Interaction (legacy gtk/view/drawing.py unless marked changed):

Input Select tool Placing Wire
Left click Port under the pointer: start a wire; element: select (Shift/Ctrl toggles; changed: topmost element only, assemblies by their frame); empty space: deselect, or with nothing selected start the two-click box Place (Shift: place another) Add the snapped point; on a port after the first point: finish
Left drag Element: move it by grid steps (changed: in place); empty space: box selection (changed: drag as well as two clicks) – –
Double or middle click – – Finish
Right click Deselect Cancel Cancel
Middle, right or Space+left drag Pan Pan Pan
Wheel Scroll (Shift: horizontal); Ctrl: zoom in 0.2 steps (0.4–2.6) about the pointer same same
Keys Escape deselects; Delete; R rotates one selected element (changed); Shift+arrows move (changed); arrows scroll; the bracket keys step through elements R rotates, C cycles the attachment port, Escape cancels Enter finishes, Backspace removes the last point, Escape cancels

Shell shortcuts: Ctrl+X/C/V, Ctrl+A, Ctrl+W (wire), Ctrl+G (group), Ctrl+Shift+N (new sheet; legacy Ctrl+N, changed), Ctrl+Z/Ctrl+Shift+Z, Ctrl++/Ctrl+-/Ctrl+0, Ctrl+? (shortcuts window). Clipboard, select-all and undo shortcuts are left to text fields when one has the focus.