Coverage for app / documents / visuals / mermaid / canvas.py: 93%
90 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""A diagram's shapes, placed as the layout places them (y down) and drawn
2as reportlab shapes (y up).
4Edges are d3's ``curveBasis`` through their points, as Mermaid draws them:
5a B-spline that starts and ends on the end points and runs smoothly past the
6bends between. Every ``String`` is given its font, and its text is drawn as
7text: no markup is read.
8"""
10from __future__ import annotations
12from collections.abc import Sequence
14from reportlab.graphics.shapes import (
15 Circle,
16 Drawing,
17 Ellipse,
18 Group,
19 Line,
20 Path,
21 PolyLine,
22 Polygon,
23 Rect,
24 String,
25)
26from reportlab.lib.colors import Color
28from ..text import measure
29from .look import LINE_HEIGHT
31Point = tuple[float, float]
32#: A quarter circle's control length, as a fraction of its radius.
33KAPPA = 0.5523
36def basis(points: Sequence[Point]) -> list[tuple[str, tuple[float, ...]]]:
37 """d3's ``curveBasis`` through ``points``: move, lines and cubic curves."""
38 out: list[tuple[str, tuple[float, ...]]] = []
39 if not points:
40 return out
41 if len(points) == 1:
42 return [("move", points[0])]
43 out.append(("move", points[0]))
44 if len(points) == 2:
45 out.append(("line", points[1]))
46 return out
47 (x0, y0), (x1, y1) = points[0], points[1]
48 out.append(("line", ((5 * x0 + x1) / 6, (5 * y0 + y1) / 6)))
49 for x, y in points[2:]:
50 out.append(
51 (
52 "curve",
53 (
54 (2 * x0 + x1) / 3,
55 (2 * y0 + y1) / 3,
56 (x0 + 2 * x1) / 3,
57 (y0 + 2 * y1) / 3,
58 (x0 + 4 * x1 + x) / 6,
59 (y0 + 4 * y1 + y) / 6,
60 ),
61 )
62 )
63 x0, y0, x1, y1 = x1, y1, x, y
64 out.append(
65 (
66 "curve",
67 (
68 (2 * x0 + x1) / 3,
69 (2 * y0 + y1) / 3,
70 (x0 + 2 * x1) / 3,
71 (y0 + 2 * y1) / 3,
72 (x0 + 5 * x1) / 6,
73 (y0 + 5 * y1) / 6,
74 ),
75 )
76 )
77 out.append(("line", (x1, y1)))
78 return out
81class Canvas:
82 def __init__(self, width: float, height: float) -> None:
83 self.width = width
84 self.height = height
85 self.shapes: list[object] = []
87 def _y(self, y: float) -> float:
88 return self.height - y
90 def _style(
91 self,
92 shape: object,
93 fill: Color | None,
94 stroke: Color | None,
95 width: float,
96 dash: Sequence[float] | None,
97 fill_opacity: float | None = None,
98 ) -> object:
99 if not isinstance(shape, (Line, PolyLine)): # neither takes a fill
100 shape.fillColor = fill # type: ignore[attr-defined]
101 shape.strokeColor = stroke # type: ignore[attr-defined]
102 shape.strokeWidth = width # type: ignore[attr-defined]
103 if dash:
104 shape.strokeDashArray = list(dash) # type: ignore[attr-defined]
105 if fill_opacity is not None and fill is not None:
106 shape.fillOpacity = fill_opacity # type: ignore[attr-defined]
107 self.shapes.append(shape)
108 return shape
110 def polygon(
111 self,
112 points: Sequence[Point],
113 *,
114 fill: Color | None,
115 stroke: Color | None,
116 width: float = 1.0,
117 dash: Sequence[float] | None = None,
118 fill_opacity: float | None = None,
119 ) -> None:
120 flat = [c for x, y in points for c in (x, self._y(y))]
121 shape = Polygon(flat, strokeLineJoin=1)
122 self._style(shape, fill, stroke, width, dash, fill_opacity)
124 def rect(
125 self,
126 x: float,
127 y: float,
128 w: float,
129 h: float,
130 *,
131 fill: Color | None,
132 stroke: Color | None,
133 width: float = 1.0,
134 radius: float = 0.0,
135 dash: Sequence[float] | None = None,
136 fill_opacity: float | None = None,
137 ) -> None:
138 shape = Rect(x, self._y(y + h), w, h, rx=radius, ry=radius)
139 self._style(shape, fill, stroke, width, dash, fill_opacity)
141 def circle(
142 self,
143 cx: float,
144 cy: float,
145 r: float,
146 *,
147 fill: Color | None,
148 stroke: Color | None,
149 width: float = 1.0,
150 dash: Sequence[float] | None = None,
151 ) -> None:
152 self._style(Circle(cx, self._y(cy), r), fill, stroke, width, dash)
154 def ellipse(
155 self,
156 cx: float,
157 cy: float,
158 rx: float,
159 ry: float,
160 *,
161 fill: Color | None,
162 stroke: Color | None,
163 width: float = 1.0,
164 ) -> None:
165 self._style(Ellipse(cx, self._y(cy), rx, ry), fill, stroke, width, None)
167 def line(
168 self,
169 x0: float,
170 y0: float,
171 x1: float,
172 y1: float,
173 *,
174 color: Color,
175 width: float = 1.0,
176 dash: Sequence[float] | None = None,
177 ) -> None:
178 self._style(Line(x0, self._y(y0), x1, self._y(y1)), None, color, width, dash)
180 def polyline(
181 self,
182 points: Sequence[Point],
183 *,
184 color: Color,
185 width: float = 1.0,
186 dash: Sequence[float] | None = None,
187 ) -> None:
188 flat = [c for x, y in points for c in (x, self._y(y))]
189 shape = PolyLine(flat, strokeLineJoin=1, strokeLineCap=1)
190 self._style(shape, None, color, width, dash)
192 def path(
193 self,
194 commands: Sequence[tuple[str, tuple[float, ...]]],
195 *,
196 fill: Color | None = None,
197 stroke: Color | None,
198 width: float = 1.0,
199 dash: Sequence[float] | None = None,
200 close: bool = False,
201 ) -> None:
202 path = Path(strokeLineJoin=1, strokeLineCap=1)
203 for kind, values in commands:
204 ys = [v if i % 2 == 0 else self._y(v) for i, v in enumerate(values)]
205 if kind == "move":
206 path.moveTo(*ys)
207 elif kind == "line":
208 path.lineTo(*ys)
209 else:
210 path.curveTo(*ys)
211 if close:
212 path.closePath()
213 self._style(path, fill, stroke, width, dash)
215 def curve(
216 self,
217 points: Sequence[Point],
218 *,
219 color: Color,
220 width: float = 1.0,
221 dash: Sequence[float] | None = None,
222 ) -> None:
223 self.path(basis(points), stroke=color, width=width, dash=dash)
225 def text(
226 self,
227 x: float,
228 baseline: float,
229 text: str,
230 *,
231 font: str,
232 size: float,
233 color: Color,
234 anchor: str = "middle",
235 ) -> None:
236 self.shapes.append(
237 String(
238 x,
239 self._y(baseline),
240 text,
241 fontName=font,
242 fontSize=size,
243 fillColor=color,
244 textAnchor=anchor,
245 )
246 )
248 def lines(
249 self,
250 x: float,
251 cy: float,
252 lines: Sequence[str],
253 *,
254 font: str,
255 size: float,
256 color: Color,
257 anchor: str = "middle",
258 ) -> None:
259 """``lines`` as a block centred on ``cy``."""
260 step = size * LINE_HEIGHT
261 top = cy - step * len(lines) / 2
262 for i, line in enumerate(lines):
263 if line:
264 self.text(
265 x,
266 top + step * i + step / 2 + size * 0.35,
267 line,
268 font=font,
269 size=size,
270 color=color,
271 anchor=anchor,
272 )
274 def drawing(self) -> Drawing:
275 drawing = Drawing(self.width, self.height)
276 drawing.add(Group(*self.shapes))
277 return drawing
280def block_size(lines: Sequence[str], font: str, size: float) -> tuple[float, float]:
281 """What ``Canvas.lines`` takes: the widest line, and the lines' height."""
282 width = max((measure(line, font, size) for line in lines), default=0.0)
283 return width, size * LINE_HEIGHT * len(lines)