vibe-sketcherDocumentation

Source code for vibesketcher.render.diagram

"""Workflow and taxonomy diagrams: boxes with text and attached connectors (#247).

A diagram is stated as a small spec (:class:`DiagramSpec`, schema
``vibesketcher.diagram/1``, written as JSON or TOML): nodes (boxes with
``$...$`` math labels, optionally in a named group), directed edges with
optional labels, and a layout. Nothing is drawn from a picture: every
connector is computed from the boxes it joins, so it stays attached when a
box moves, and the same spec always gives the same bytes.

Layouts:

- ``layered`` (workflows): the layered drawing of K. Sugiyama, S. Tagawa and
  M. Toda, "Methods for visual understanding of hierarchical system
  structures", IEEE Trans. Syst. Man Cybern. SMC-11, 109-125 (1981),
  doi:10.1109/TSMC.1981.4308636. Cycles are broken by reversing the back
  edges of a depth-first search in input order (they are drawn in their
  stated direction). Layers are the longest path from a source. An edge that
  spans several layers gets a dummy vertex per inner layer, so it is drawn as
  a polyline through the gaps between boxes. Crossings are reduced by the
  barycentre method (section IV of the paper) in alternating down and up
  sweeps, a fixed number of them (:data:`SWEEPS`); the order with the fewest
  crossings is kept, so the result does not depend on timing. Positions
  along a layer follow the barycentres of the neighbours (the priority idea
  of section V, simplified to the average of a left-to-right and a
  right-to-left sweep, which keeps the stated separation).
- ``tree`` (taxonomies): each node has at most one parent; children are
  placed side by side in the order their edges are stated and the parent is
  centred over them, the aesthetic rules of E. M. Reingold and J. S. Tilford,
  "Tidier drawings of trees", IEEE Trans. Softw. Eng. SE-7, 223-228 (1981),
  doi:10.1109/TSE.1981.234519. Subtrees are packed by their bounding widths,
  not by their contours, so a tree may be wider than Reingold-Tilford's.
- ``manual``: every node states its centre ``position`` (pt, y down).

In the other layouts a node's ``position`` pins it there. The direction is
``down`` (layers are rows) or ``right`` (layers are columns).

The drawing fails closed: more than :data:`MAX_NODES` nodes or
:data:`MAX_EDGES` edges, an unknown node or group, a self-loop, a duplicate
edge, a second parent in a tree, unsupported math, two boxes that overlap and
a group box that covers a node outside the group are refused with
:class:`DiagramRefused`. The bounds include every box, connector, arrowhead
and label: text is measured with the publication font's advance widths
(:func:`vibesketcher.render.mathtext.measure`), so nothing is clipped in SVG,
PDF or PNG. One SVG unit is one point; PDF and PNG go through the
publication extra.
"""

from __future__ import annotations

import html
import json
import math
import tomllib
from collections.abc import Sequence
from typing import Any, Final, Literal

from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator

from vibesketcher.render import RenderRefused, mathtext

__all__ = [
    "MAX_EDGES",
    "MAX_GROUPS",
    "MAX_NODES",
    "SCHEMA",
    "SWEEPS",
    "DiagramEdge",
    "DiagramGroup",
    "DiagramNode",
    "DiagramRefused",
    "DiagramSpec",
    "diagram",
    "diagram_layout",
    "diagram_svg",
    "load_spec",
]

SCHEMA: Final = "vibesketcher.diagram/1"
#: The most nodes, edges and groups a diagram may have.
MAX_NODES = 120
MAX_EDGES = 360
MAX_GROUPS = 24
#: Barycentre sweeps (each a down and an up pass) of the crossing reduction.
SWEEPS = 12
#: Rounds of the barycentre placement along the layers.
_PLACEMENT_ROUNDS = 8
_MAX_LINES = 4
_COLOUR = r"^#[0-9a-fA-F]{6}$"
_ID = r"^[A-Za-z0-9_.:-]{1,64}$"
_MAX_SPEC_BYTES = 256 * 1024
_BOLD_SLACK = 1.08


[docs] class DiagramRefused(RenderRefused): """The spec cannot be drawn as stated."""
[docs] class DiagramNode(BaseModel): """One box. ``label`` holds up to four lines separated by newlines; math is allowed.""" model_config = ConfigDict(extra="forbid") id: str = Field(pattern=_ID) label: str = Field(min_length=1, max_length=600) group: str | None = Field(default=None, pattern=_ID) #: The box's centre in points (y down); required by the manual layout, a pin otherwise. position: tuple[float, float] | None = None shape: Literal["box", "rounded", "plain"] = "rounded" fill: str = Field(default="#ffffff", pattern=_COLOUR) stroke: str = Field(default="#000000", pattern=_COLOUR) #: The smallest box width in points; the label widens it as needed. min_width: float = Field(default=0.0, ge=0.0, le=1000.0) bold: bool = False @model_validator(mode="after") def _finite(self) -> DiagramNode: if self.position is not None and not all( math.isfinite(v) and abs(v) <= 10000 for v in self.position ): raise ValueError(f"node {self.id}: position must be finite, within 10000 pt") return self
[docs] class DiagramEdge(BaseModel): """A directed connector from ``source`` to ``target``, with an optional label.""" model_config = ConfigDict(extra="forbid") source: str = Field(pattern=_ID) target: str = Field(pattern=_ID) label: str | None = Field(default=None, max_length=300) style: Literal["solid", "dashed"] = "solid" arrow: bool = True colour: str = Field(default="#000000", pattern=_COLOUR)
[docs] class DiagramGroup(BaseModel): """A labelled frame around the nodes that name it.""" model_config = ConfigDict(extra="forbid") id: str = Field(pattern=_ID) label: str | None = Field(default=None, max_length=300) stroke: str = Field(default="#666666", pattern=_COLOUR) fill: str = Field(default="#f4f4f4", pattern=_COLOUR)
[docs] class DiagramSpec(BaseModel): """A workflow or taxonomy diagram; every choice is stated.""" model_config = ConfigDict(extra="forbid", populate_by_name=True) schema_: Literal["vibesketcher.diagram/1"] = Field(default=SCHEMA, alias="schema") layout: Literal["layered", "tree", "manual"] = "layered" direction: Literal["down", "right"] = "down" nodes: list[DiagramNode] = Field(min_length=1, max_length=MAX_NODES) edges: list[DiagramEdge] = Field(default_factory=list, max_length=MAX_EDGES) groups: list[DiagramGroup] = Field(default_factory=list, max_length=MAX_GROUPS) font_size: float = Field(default=8.0, ge=4.0, le=36.0) #: Space between layers and between neighbouring boxes in a layer, in points. layer_gap: float = Field(default=28.0, ge=4.0, le=400.0) node_gap: float = Field(default=14.0, ge=2.0, le=400.0) #: Inner padding of a box, in points. padding: float = Field(default=4.0, ge=0.0, le=40.0) #: Draw the figure this wide (pt), scaling the drawing; by default 1 unit = 1 pt. width_pt: float | None = Field(default=None, ge=20.0, le=14400.0) title: str | None = Field(default=None, max_length=300)
[docs] def load_spec( data: str | bytes | dict[str, Any], fmt: Literal["json", "toml"] = "json" ) -> DiagramSpec: """A validated spec from JSON or TOML text (or a parsed mapping); errors are refusals.""" if isinstance(data, dict): raw: Any = data else: text = data.decode("utf-8") if isinstance(data, bytes) else data if len(text.encode("utf-8")) > _MAX_SPEC_BYTES: raise DiagramRefused(f"a diagram spec is at most {_MAX_SPEC_BYTES // 1024} KiB") try: raw = json.loads(text) if fmt == "json" else tomllib.loads(text) except (json.JSONDecodeError, tomllib.TOMLDecodeError) as error: raise DiagramRefused(f"the diagram spec is not valid {fmt.upper()}: {error}") from None if not isinstance(raw, dict): raise DiagramRefused("a diagram spec is a mapping with nodes and edges") try: return DiagramSpec.model_validate(raw) except ValidationError as error: problems = "; ".join( f"{'.'.join(str(p) for p in e['loc'])}: {e['msg']}" for e in error.errors() ) raise DiagramRefused(f"invalid diagram spec: {problems}") from None
# ── measurement ───────────────────────────────────────────────────────── class _Box: """A node's box: centre (x, y), size (w, h), its label lines.""" def __init__(self, node: DiagramNode, lines: list[str], w: float, h: float) -> None: self.node, self.lines, self.w, self.h = node, lines, w, h self.x = 0.0 self.y = 0.0 def rect(self) -> tuple[float, float, float, float]: return self.x - self.w / 2, self.y - self.h / 2, self.x + self.w / 2, self.y + self.h / 2 def _line_height(size: float) -> float: return 1.25 * size def _measure_box(node: DiagramNode, spec: DiagramSpec) -> _Box: lines = node.label.split("\n") if len(lines) > _MAX_LINES: raise DiagramRefused(f"node {node.id}: at most {_MAX_LINES} label lines") widths = [] for line in lines: if not line.strip(): raise DiagramRefused(f"node {node.id}: a label line is empty") try: width = mathtext.measure(line, spec.font_size)[0] except mathtext.MathRefused as error: raise DiagramRefused(f"node {node.id}: {error}") from None # The advances are the regular face's; a bold face is up to 8 per cent wider. widths.append(width * (_BOLD_SLACK if node.bold else 1.0)) w = max(max(widths) + 2 * spec.padding + 0.6 * spec.font_size, node.min_width) h = len(lines) * _line_height(spec.font_size) + 2 * spec.padding return _Box(node, lines, w, h) # ── validation of the graph ───────────────────────────────────────────── def _check_graph(spec: DiagramSpec) -> None: ids = [n.id for n in spec.nodes] seen: set[str] = set() for identifier in ids: if identifier in seen: raise DiagramRefused(f"node id {identifier!r} is used twice") seen.add(identifier) groups = [g.id for g in spec.groups] if len(set(groups)) != len(groups): raise DiagramRefused("a group id is used twice") for node in spec.nodes: if node.group is not None and node.group not in groups: raise DiagramRefused(f"node {node.id}: unknown group {node.group!r}") pairs: set[tuple[str, str]] = set() for edge in spec.edges: for end in (edge.source, edge.target): if end not in seen: raise DiagramRefused(f"edge {edge.source} -> {edge.target}: unknown node {end!r}") if edge.source == edge.target: raise DiagramRefused(f"edge {edge.source} -> {edge.target}: self-loops are refused") if (edge.source, edge.target) in pairs: raise DiagramRefused(f"edge {edge.source} -> {edge.target} is stated twice") pairs.add((edge.source, edge.target)) if spec.layout == "manual": missing = [n.id for n in spec.nodes if n.position is None] if missing: raise DiagramRefused( "the manual layout needs every position; missing: " + ", ".join(missing) ) # ── layered layout (Sugiyama, Tagawa and Toda 1981) ───────────────────── def _back_edges(n: int, out: list[list[int]]) -> set[tuple[int, int]]: """Back edges of a depth-first search in input order (iterative, deterministic).""" state = [0] * n # 0 new, 1 on the stack, 2 done back: set[tuple[int, int]] = set() for root in range(n): if state[root]: continue state[root] = 1 stack: list[tuple[int, int]] = [(root, 0)] while stack: v, k = stack[-1] if k < len(out[v]): stack[-1] = (v, k + 1) w = out[v][k] if state[w] == 1: back.add((v, w)) elif state[w] == 0: state[w] = 1 stack.append((w, 0)) else: state[v] = 2 stack.pop() return back def _barycentre( v: int, nbrs: list[list[int]], pos: dict[int, int], current: dict[int, int] ) -> tuple[float, int]: """The mean position of ``v``'s neighbours in the reference layer; ties keep the order.""" near = [pos[w] for w in nbrs[v] if w in pos] value = sum(near) / len(near) if near else float(current[v]) return value, current[v] def _crossings(upper: list[int], lower: list[int], links: list[tuple[int, int]]) -> int: """Crossings between two adjacent layers (the links join upper to lower vertices).""" pos_u = {v: i for i, v in enumerate(upper)} pos_l = {v: i for i, v in enumerate(lower)} pairs = sorted((pos_u[a], pos_l[b]) for a, b in links if a in pos_u and b in pos_l) count = 0 for i in range(len(pairs)): for j in range(i + 1, len(pairs)): if pairs[i][0] < pairs[j][0] and pairs[i][1] > pairs[j][1]: count += 1 return count class _Layered: """Layers, the vertex order in each, and the dummy chains of long edges.""" def __init__(self, spec: DiagramSpec) -> None: index = {n.id: i for i, n in enumerate(spec.nodes)} n = len(spec.nodes) out: list[list[int]] = [[] for _ in range(n)] for edge in spec.edges: out[index[edge.source]].append(index[edge.target]) back = _back_edges(n, out) #: Every stated edge as (upper, lower) in the acyclic orientation, and whether reversed. self.oriented: list[tuple[int, int, bool]] = [] for edge in spec.edges: s, t = index[edge.source], index[edge.target] self.oriented.append((t, s, True) if (s, t) in back else (s, t, False)) preds: list[list[int]] = [[] for _ in range(n)] for a, b, _r in self.oriented: preds[b].append(a) layer = [-1] * n def depth(v: int) -> int: # Longest path from a source; the graph is acyclic after the reversal. stack = [v] while stack: top = stack[-1] pending = [p for p in preds[top] if layer[p] < 0] if pending: stack.extend(pending) continue stack.pop() if layer[top] < 0: layer[top] = max((layer[p] + 1 for p in preds[top]), default=0) return layer[v] for v in range(n): depth(v) self.n_real = n self.layer = list(layer) #: For each stated edge, the vertex chain from its upper to its lower end. self.chains: list[list[int]] = [] groups = {g.id: k for k, g in enumerate(spec.groups)} self.key: list[tuple[int, int]] = [ (groups.get(node.group, -1) if node.group else -1, i) for i, node in enumerate(spec.nodes) ] for k, (a, b, _r) in enumerate(self.oriented): chain = [a] for depth_ in range(self.layer[a] + 1, self.layer[b]): self.layer.append(depth_) self.key.append((-1, n + k)) chain.append(len(self.layer) - 1) chain.append(b) self.chains.append(chain) self.links = [(c[i], c[i + 1]) for c in self.chains for i in range(len(c) - 1)] count = max(self.layer) + 1 self.layers: list[list[int]] = [[] for _ in range(count)] for v in sorted(range(len(self.layer)), key=lambda v: self.key[v]): self.layers[self.layer[v]].append(v) self.up: list[list[int]] = [[] for _ in self.layer] self.down: list[list[int]] = [[] for _ in self.layer] for a, b in self.links: self.down[a].append(b) self.up[b].append(a) self._reduce_crossings() def total_crossings(self, layers: list[list[int]]) -> int: return sum(_crossings(layers[i], layers[i + 1], self.links) for i in range(len(layers) - 1)) def _reduce_crossings(self) -> None: """The barycentre method: alternate down and up sweeps; keep the best order.""" layers = [list(row) for row in self.layers] best, best_count = [list(row) for row in layers], self.total_crossings(layers) for _sweep in range(SWEEPS): for direction in ("down", "up"): order = ( range(1, len(layers)) if direction == "down" else range(len(layers) - 2, -1, -1) ) for i in order: ref = layers[i - 1] if direction == "down" else layers[i + 1] pos = {v: k for k, v in enumerate(ref)} nbrs = self.up if direction == "down" else self.down current = {v: k for k, v in enumerate(layers[i])} layers[i] = sorted(layers[i], key=lambda v: _barycentre(v, nbrs, pos, current)) count = self.total_crossings(layers) if count < best_count: best, best_count = [list(row) for row in layers], count self.layers = best self.crossings = best_count def _separate(desired: list[float], sizes: list[float], gap: float) -> list[float]: """Positions in order, closest to ``desired``, with at least ``gap`` between boxes. The average of a left-to-right and a right-to-left sweep; both keep the separation, so their average does too. """ k = len(desired) left = list(desired) for i in range(1, k): left[i] = max(left[i], left[i - 1] + (sizes[i - 1] + sizes[i]) / 2 + gap) right = list(desired) for i in range(k - 2, -1, -1): right[i] = min(right[i], right[i + 1] - (sizes[i] + sizes[i + 1]) / 2 - gap) return [(a + b) / 2 for a, b in zip(left, right, strict=True)] def _layered_positions( spec: DiagramSpec, boxes: list[_Box] ) -> tuple[list[tuple[float, float]], list[list[int]], int]: """Vertex centres (real and dummy) and the chain of every edge.""" graph = _Layered(spec) down = spec.direction == "down" breadth = [(b.w if down else b.h) for b in boxes] + [0.0] * (len(graph.layer) - len(boxes)) depth_size = [(b.h if down else b.w) for b in boxes] + [0.0] * (len(graph.layer) - len(boxes)) along: list[float] = [0.0] * len(graph.layer) for row in graph.layers: sizes = [breadth[v] for v in row] total = sum(sizes) + spec.node_gap * (len(row) - 1) x = -total / 2 for v, s in zip(row, sizes, strict=True): along[v] = x + s / 2 x += s + spec.node_gap for round_ in range(_PLACEMENT_ROUNDS): rows = graph.layers if round_ % 2 == 0 else graph.layers[::-1] nbrs = graph.up if round_ % 2 == 0 else graph.down for row in rows: desired = [] for v in row: near = [along[w] for w in nbrs[v]] desired.append(sum(near) / len(near) if near else along[v]) placed = _separate(desired, [breadth[v] for v in row], spec.node_gap) for v, p in zip(row, placed, strict=True): along[v] = p level = _levels( spec, [max((depth_size[v] for v in row), default=0.0) for row in graph.layers], [[v for v in row if v < len(boxes)] for row in graph.layers], ) centres = [ (along[v], level[graph.layer[v]]) if down else (level[graph.layer[v]], along[v]) for v in range(len(graph.layer)) ] chains = [] for chain, (_a, _b, reversed_) in zip(graph.chains, graph.oriented, strict=True): chains.append(chain[::-1] if reversed_ else chain) return centres, chains, graph.crossings def _levels(spec: DiagramSpec, thick: list[float], members: list[list[int]]) -> list[float]: """Centre of every layer along the depth axis. A layer that holds grouped nodes gets room for the group frame (and, going down, its label) before and after it, so the frame stays in the gap. """ labelled = {g.id for g in spec.groups if g.label} pad = _frame_pad(spec) level: list[float] = [] cursor = 0.0 for size, row in zip(thick, members, strict=True): names = {spec.nodes[v].group for v in row} - {None} before = after = pad if names else 0.0 if spec.direction == "down" and names & labelled: before += _line_height(spec.font_size) level.append(cursor + before + size / 2) cursor += before + size + after + spec.layer_gap return level def _frame_pad(spec: DiagramSpec) -> float: return 0.6 * spec.font_size # ── tree layout (Reingold and Tilford 1981, by bounding widths) ───────── def _tree_positions(spec: DiagramSpec, boxes: list[_Box]) -> list[tuple[float, float]]: index = {n.id: i for i, n in enumerate(spec.nodes)} n = len(spec.nodes) parent = [-1] * n children: list[list[int]] = [[] for _ in range(n)] for edge in spec.edges: s, t = index[edge.source], index[edge.target] if parent[t] >= 0: raise DiagramRefused( f"node {edge.target} has two parents; a tree layout needs one (use layered)" ) parent[t] = s children[s].append(t) roots = [v for v in range(n) if parent[v] < 0] reached: set[int] = set() stack = list(roots) while stack: v = stack.pop() reached.add(v) stack.extend(children[v]) if len(reached) != n: raise DiagramRefused("the tree edges form a cycle; a tree layout needs a forest") down = spec.direction == "down" breadth = [b.w if down else b.h for b in boxes] thick = [b.h if down else b.w for b in boxes] span = [0.0] * n order: list[int] = [] stack = list(reversed(roots)) while stack: v = stack.pop() order.append(v) stack.extend(reversed(children[v])) depth = [0] * n for v in order: for c in children[v]: depth[c] = depth[v] + 1 for v in reversed(order): inner = sum(span[c] for c in children[v]) + spec.node_gap * max(len(children[v]) - 1, 0) span[v] = max(breadth[v], inner) along = [0.0] * n def place(v: int, left: float) -> None: # Children side by side under the parent, the parent centred over them. work = [(v, left)] while work: node, start = work.pop() inner = sum(span[c] for c in children[node]) + spec.node_gap * max( len(children[node]) - 1, 0 ) along[node] = start + span[node] / 2 x = start + (span[node] - inner) / 2 for c in children[node]: work.append((c, x)) x += span[c] + spec.node_gap left = 0.0 for root in roots: place(root, left) left += span[root] + spec.node_gap levels = max(depth) + 1 level_thick = [ max((thick[v] for v in range(n) if depth[v] == d), default=0.0) for d in range(levels) ] level = _levels( spec, level_thick, [[v for v in range(n) if depth[v] == d] for d in range(levels)] ) return [(along[v], level[depth[v]]) if down else (level[depth[v]], along[v]) for v in range(n)] # ── geometry ──────────────────────────────────────────────────────────── def _clip( box: _Box, start: tuple[float, float], toward: tuple[float, float] ) -> tuple[float, float]: """Where the segment from ``start`` (inside the box) toward ``toward`` leaves the box.""" dx, dy = toward[0] - start[0], toward[1] - start[1] x0, y0, x1, y1 = box.rect() t = 1.0 if dx > 1e-12: t = min(t, (x1 - start[0]) / dx) elif dx < -1e-12: t = min(t, (x0 - start[0]) / dx) if dy > 1e-12: t = min(t, (y1 - start[1]) / dy) elif dy < -1e-12: t = min(t, (y0 - start[1]) / dy) t = max(t, 0.0) return start[0] + dx * t, start[1] + dy * t def _shifted(points: list[tuple[float, float]], offset: float) -> list[tuple[float, float]]: """The polyline moved sideways by ``offset`` (to the left of its direction).""" a, b = points[0], points[-1] length = math.dist(a, b) if length < 1e-9: return points nx, ny = (b[1] - a[1]) / length, -(b[0] - a[0]) / length return [(x + offset * nx, y + offset * ny) for x, y in points] def _overlap(a: tuple[float, float, float, float], b: tuple[float, float, float, float]) -> bool: return a[0] < b[2] - 1e-6 and b[0] < a[2] - 1e-6 and a[1] < b[3] - 1e-6 and b[1] < a[3] - 1e-6 def _n(value: float) -> str: text = f"{value:.3f}".rstrip("0").rstrip(".") return "0" if text in ("-0", "") else text class _Layout: """Everything drawn, in diagram points (y down), before the final translation.""" def __init__(self) -> None: self.boxes: list[_Box] = [] #: (edge, polyline points) self.paths: list[tuple[DiagramEdge, list[tuple[float, float]]]] = [] #: (group, rect) self.frames: list[tuple[DiagramGroup, tuple[float, float, float, float]]] = [] #: (group, label baseline start) of a labelled group frame. self.group_labels: list[tuple[DiagramGroup, tuple[float, float]]] = [] #: (edge, label centre, label rect) self.labels: list[ tuple[DiagramEdge, tuple[float, float], tuple[float, float, float, float]] ] = [] self.crossings: int | None = None
[docs] def diagram_layout(spec: DiagramSpec) -> _Layout: """Measure, lay out and check the diagram; the geometry before drawing.""" _check_graph(spec) for text in [spec.title or "", *(e.label or "" for e in spec.edges)] + [ g.label or "" for g in spec.groups ]: if text: try: mathtext.validate(text) except mathtext.MathRefused as error: raise DiagramRefused(str(error)) from None boxes = [_measure_box(node, spec) for node in spec.nodes] out = _Layout() chains: list[list[int]] if spec.layout == "layered": centres, chains, out.crossings = _layered_positions(spec, boxes) elif spec.layout == "tree": centres = _tree_positions(spec, boxes) index = {n.id: i for i, n in enumerate(spec.nodes)} chains = [[index[e.source], index[e.target]] for e in spec.edges] else: centres = [(0.0, 0.0)] * len(boxes) index = {n.id: i for i, n in enumerate(spec.nodes)} chains = [[index[e.source], index[e.target]] for e in spec.edges] centres = list(centres) for i, (box, node) in enumerate(zip(boxes, spec.nodes, strict=True)): if node.position is not None: centres[i] = node.position box.x, box.y = centres[i] for i in range(len(boxes)): for j in range(i + 1, len(boxes)): if _overlap(boxes[i].rect(), boxes[j].rect()): raise DiagramRefused( f"boxes {boxes[i].node.id} and {boxes[j].node.id} overlap; move one" ) pairs = {(e.source, e.target) for e in spec.edges} for edge, chain in zip(spec.edges, chains, strict=True): points = [centres[v] for v in chain] first, last = boxes[chain[0]], boxes[chain[-1]] if (edge.target, edge.source) in pairs: # A pair of opposite edges: each runs on its own side of the centre line. side = 0.35 * min(first.h, last.h, first.w, last.w, 1.4 * spec.font_size) points = _shifted(points, side) points[0] = _clip(first, points[0], points[1]) points[-1] = _clip(last, points[-1], points[-2]) out.paths.append((edge, points)) pad = _frame_pad(spec) label_h = _line_height(spec.font_size) if spec.groups else 0.0 for group in spec.groups: members = [b for b in boxes if b.node.group == group.id] if not members: raise DiagramRefused(f"group {group.id} has no nodes") rects = [b.rect() for b in members] head = label_h if group.label else 0.0 frame = ( min(r[0] for r in rects) - pad, min(r[1] for r in rects) - pad - head, max(r[2] for r in rects) + pad, max(r[3] for r in rects) + pad, ) for other in boxes: if other.node.group != group.id and _overlap(frame, other.rect()): raise DiagramRefused( f"group {group.id}'s frame covers node {other.node.id}, which is not in it; " "reorder the nodes or give positions" ) out.frames.append((group, frame)) for k, (g1, f1) in enumerate(out.frames): for g2, f2 in out.frames[k + 1 :]: if _overlap(f1, f2): raise DiagramRefused(f"the frames of groups {g1.id} and {g2.id} overlap") out.boxes = boxes _place_labels(spec, out) return out
#: Where along a connector (fraction of its length) its label may sit, in order of preference. _LABEL_STOPS = (0.5, 0.4, 0.6, 0.3, 0.7, 0.2, 0.8) def _place_labels(spec: DiagramSpec, out: _Layout) -> None: """Group and edge labels; an edge label slides along its connector off other text.""" size = spec.font_size taken = [b.rect() for b in out.boxes] for group, frame in out.frames: if group.label: width, ascent, descent = mathtext.measure(group.label, 0.9 * size) x, y = frame[0] + 0.4 * size, frame[1] + 0.25 * size + ascent out.group_labels.append((group, (x, y))) taken.append((x, y - ascent, x + width, y + descent)) lsize = 0.85 * size for edge, points in out.paths: if not edge.label: continue width, ascent, descent = mathtext.measure(edge.label, lsize) pad = 0.2 * lsize half_w, half_h = width / 2 + pad, (ascent + descent) / 2 + pad for stop in _LABEL_STOPS: cx, cy = _point_at(points, stop) rect = (cx - half_w, cy - half_h, cx + half_w, cy + half_h) if not any(_overlap(rect, other) for other in taken): break else: raise DiagramRefused( f"the label of edge {edge.source} -> {edge.target} has no free place on its " "connector; widen layer_gap or give positions" ) taken.append(rect) out.labels.append((edge, (cx, cy), rect)) def _arrowhead(a: tuple[float, float], b: tuple[float, float], size: float, colour: str) -> str: angle = math.atan2(b[1] - a[1], b[0] - a[0]) left = (b[0] - size * math.cos(angle - 0.38), b[1] - size * math.sin(angle - 0.38)) right = (b[0] - size * math.cos(angle + 0.38), b[1] - size * math.sin(angle + 0.38)) return ( f'<polygon class="arrowhead" points="{_n(b[0])},{_n(b[1])} {_n(left[0])},{_n(left[1])} ' f'{_n(right[0])},{_n(right[1])}" fill="{colour}"/>' ) def _point_at(points: Sequence[tuple[float, float]], fraction: float) -> tuple[float, float]: """The point ``fraction`` of the way along the polyline.""" lengths = [math.dist(points[i], points[i + 1]) for i in range(len(points) - 1)] half = sum(lengths) * fraction for i, length in enumerate(lengths): if half <= length or i == len(lengths) - 1: t = half / length if length > 0 else 0.0 a, b = points[i], points[i + 1] return a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t half -= length return points[0]
[docs] def diagram_svg(spec: DiagramSpec) -> bytes: """The diagram as standalone SVG (UTF-8), one unit per point unless ``width_pt``.""" layout = diagram_layout(spec) size = spec.font_size stroke = max(0.5, 0.09 * size) head = 0.55 * size xs: list[float] = [] ys: list[float] = [] frames: list[str] = [] for group, (x0, y0, x1, y1) in layout.frames: xs.extend([x0, x1]) ys.extend([y0, y1]) frames.append( f'<rect class="group" data-group="{html.escape(group.id)}" x="{_n(x0)}" y="{_n(y0)}" ' f'width="{_n(x1 - x0)}" height="{_n(y1 - y0)}" rx="{_n(0.4 * size)}" ' f'fill="{group.fill}" stroke="{group.stroke}" stroke-width="{_n(stroke)}" ' f'stroke-dasharray="{_n(3 * stroke)} {_n(2 * stroke)}"/>' ) edges: list[str] = [] labels: list[str] = [] for group, (x, y) in layout.group_labels: # Drawn over the connectors, on the frame's own fill, so it stays legible. assert group.label is not None width, ascent, descent = mathtext.measure(group.label, 0.9 * size) pad = 0.15 * size xs.append(x + width + pad) labels.append( f'<rect class="group-label" x="{_n(x - pad)}" y="{_n(y - ascent - pad)}" ' f'width="{_n(width + 2 * pad)}" height="{_n(ascent + descent + 2 * pad)}" ' f'fill="{group.fill}"/>' + mathtext.svg_text(group.label, x, y, 0.9 * size, fill=group.stroke) ) for edge, points in layout.paths: for x, y in points: xs.append(x) ys.append(y) end = points[-1] prev = points[-2] # The line stops at the arrowhead's base so the tip is sharp. drawn = list(points) if edge.arrow: length = math.dist(prev, end) if length > head: t = (length - 0.7 * head) / length drawn[-1] = (prev[0] + (end[0] - prev[0]) * t, prev[1] + (end[1] - prev[1]) * t) dash = ( f' stroke-dasharray="{_n(3 * stroke)} {_n(2 * stroke)}"' if edge.style == "dashed" else "" ) edges.append( f'<polyline class="edge" data-source="{html.escape(edge.source)}" ' f'data-target="{html.escape(edge.target)}" points="' + " ".join(f"{_n(x)},{_n(y)}" for x, y in drawn) + f'" fill="none" stroke="{edge.colour}" stroke-width="{_n(stroke)}"{dash}/>' ) if edge.arrow: edges.append(_arrowhead(prev, end, head, edge.colour)) for edge, (cx, cy), (x0, y0, x1, y1) in layout.labels: assert edge.label is not None lsize = 0.85 * size _width, ascent, descent = mathtext.measure(edge.label, lsize) xs.extend([x0, x1]) ys.extend([y0, y1]) labels.append( f'<rect class="edge-label" x="{_n(x0)}" y="{_n(y0)}" width="{_n(x1 - x0)}" ' f'height="{_n(y1 - y0)}" fill="#ffffff"/>' + mathtext.svg_text(edge.label, cx, cy + (ascent - descent) / 2, lsize, anchor="middle") ) nodes: list[str] = [] for box in layout.boxes: x0, y0, x1, y1 = box.rect() xs.extend([x0 - stroke, x1 + stroke]) ys.extend([y0 - stroke, y1 + stroke]) node = box.node if node.shape != "plain": rx = f' rx="{_n(0.45 * size)}"' if node.shape == "rounded" else "" nodes.append( f'<rect class="node" data-node="{html.escape(node.id)}" x="{_n(x0)}" ' f'y="{_n(y0)}" width="{_n(box.w)}" height="{_n(box.h)}"{rx} fill="{node.fill}" ' f'stroke="{node.stroke}" stroke-width="{_n(stroke)}"/>' ) else: nodes.append( f'<rect class="node" data-node="{html.escape(node.id)}" x="{_n(x0)}" ' f'y="{_n(y0)}" width="{_n(box.w)}" height="{_n(box.h)}" fill="none"/>' ) lh = _line_height(size) top = box.y - len(box.lines) * lh / 2 for k, line in enumerate(box.lines): # The baseline sits so the line's em box is centred in its slot. baseline = top + k * lh + lh / 2 + 0.35 * size nodes.append( mathtext.svg_text( line, box.x, baseline, size, anchor="middle", weight="bold" if node.bold else "normal", ) ) # fmt: skip margin = 0.6 * size title_h = 0.0 parts: list[str] = [] minx, maxx = min(xs), max(xs) miny, maxy = min(ys), max(ys) if spec.title: tsize = 1.1 * size width, ascent, descent = mathtext.measure(spec.title, tsize) maxx = max(maxx, minx + width) title_h = ascent + descent + 0.6 * size parts.append(mathtext.svg_text(spec.title, margin, margin + ascent, tsize)) width = maxx - minx + 2 * margin height = maxy - miny + 2 * margin + title_h dx, dy = margin - minx, margin + title_h - miny parts.append( f'<g transform="translate({_n(dx)} {_n(dy)})">' + "".join(frames + edges + labels + nodes) + "</g>" ) shown_w = spec.width_pt or width shown_h = height * shown_w / width if shown_w > 14400 or shown_h > 14400: raise DiagramRefused("the diagram is larger than 14400 pt; lower font_size or the gaps") title = mathtext.plain_text(spec.title) if spec.title else f"{spec.layout} diagram" crossings = f' data-vibe-crossings="{layout.crossings}"' if layout.crossings is not None else "" svg = ( '<?xml version="1.0" encoding="UTF-8"?>\n' f'<svg xmlns="http://www.w3.org/2000/svg" width="{_n(shown_w)}pt" ' f'height="{_n(shown_h)}pt" viewBox="0 0 {_n(width)} {_n(height)}" ' f'font-family="Roboto, Arial, sans-serif" data-vibe-diagram="{spec.layout}"' f"{crossings}><title>{html.escape(title)}</title>" f'<rect width="100%" height="100%" fill="#fff"/>{"".join(parts)}</svg>' ) return svg.encode("utf-8")
[docs] def diagram(spec: DiagramSpec, fmt: str = "svg", *, dpi: int = 300) -> bytes: """The diagram as SVG, or PDF/PNG through the publication extra.""" svg = diagram_svg(spec) if fmt == "svg": return svg if fmt not in ("pdf", "png"): raise DiagramRefused(f"cannot write {fmt!r}; formats: svg, pdf, png") from vibesketcher.render.publication import convert return bytes(convert(svg, fmt, dpi=dpi))