Coverage for app / documents / visuals / mermaid / sequence.py: 96%
546 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"""``sequenceDiagram``.
3Read: ``participant`` and ``actor`` (``as`` an alias, v11's ``@{ "type" }``
4shapes read as participants), ``create`` and ``destroy``, ``box`` groups,
5every message arrow (``->``, ``-->``, ``->>``, ``-->>``, ``<<->>``,
6``<<-->>``, ``-x``, ``--x``, ``-)``, ``--)``) with ``+`` / ``-``
7activation, ``activate`` / ``deactivate``, notes left of, right of and over
8one or two participants, the blocks ``loop``, ``alt`` / ``else``, ``opt``,
9``par`` / ``and``, ``critical`` / ``option``, ``break`` and ``rect``,
10``autonumber`` and ``title``. Links, properties and the accessibility lines
11are left out.
13Laid out as Mermaid lays it out: a column per participant, spaced so every
14message's label fits between its two lifelines, one row per message, note
15or block line, participants repeated at the foot. Every row boundary is a
16place a tall diagram may be cut across pages, and each part after the first
17starts with the participants again (``Layout.header``).
18"""
20from __future__ import annotations
22import re
23from dataclasses import dataclass, field
24from typing import Literal
26from reportlab.lib.colors import Color, HexColor
28from ..colors import parse_color
29from ..registry import Layout
30from ..text import measure
31from ..theme import Theme
32from . import look
33from .base import Diagram, MermaidSyntaxError, Statement, register_diagram
34from .canvas import Canvas, block_size
35from .compound import MAX_EDGES, MAX_NODES
36from .labels import fit
37from .markers import draw_edge
39Stroke = Literal["solid", "dotted"]
41#: Each arrow: its line, and the markers at its start and end.
42_ARROWS: dict[str, tuple[Stroke, str | None, str | None]] = {
43 "->": ("solid", None, None),
44 "-->": ("dotted", None, None),
45 "->>": ("solid", None, "arrow"),
46 "-->>": ("dotted", None, "arrow"),
47 "<<->>": ("solid", "arrow", "arrow"),
48 "<<-->>": ("dotted", "arrow", "arrow"),
49 "-x": ("solid", None, "cross"),
50 "--x": ("dotted", None, "cross"),
51 "-)": ("solid", None, "open_arrow"),
52 "--)": ("dotted", None, "open_arrow"),
53}
54_ARROW = "|".join(re.escape(a) for a in sorted(_ARROWS, key=len, reverse=True))
55_MESSAGE = re.compile(
56 rf"^(?P<a>[^:]+?)\s*(?P<arrow>{_ARROW})\s*(?P<sign>[+-])?\s*"
57 r"(?P<b>[^:+\-\s][^:]*?)\s*(?::(?P<text>.*))?$"
58)
59_ACTOR = re.compile(
60 r"^(?:(?P<create>create)\s+)?(?P<kind>participant|actor)\s+(?P<id>[^\s@]+)"
61 r"(?:@\{(?P<props>[^}]*)\})?(?:\s+as\s+(?P<alias>.+))?$"
62)
63_NOTE = re.compile(
64 r"^note\s+(?P<place>left of|right of|over)\s+(?P<who>[^:]+?)\s*:\s*(?P<text>.*)$",
65 re.IGNORECASE,
66)
67#: Blocks, and the lines that divide each into sections.
68_BLOCKS = ("loop", "alt", "opt", "par", "par_over", "critical", "break", "rect")
69_SECTIONS = {"else": "alt", "and": "par", "option": "critical"}
70_SKIPPED = ("link", "links", "properties", "details", "accTitle", "accDescr")
72#: Sizes, in points.
73PAD_X = 10.0
74PAD_Y = 7.0
75ACTOR_MIN_W = 64.0
76ACTOR_MIN_H = 28.0
77ACTOR_GAP = 28.0
78STICK = 26.0
79MARGIN = 8.0
80LOOP = 24.0
81NOTE_PAD = 6.0
82NOTE_MAX = 160.0
83FRAME_PAD = 10.0
84BAR = 9.0
85LABEL_MAX = 220.0
86LIFELINE = HexColor("#999999")
87FRAME = HexColor("#9370DB")
88BAR_FILL = HexColor("#f4f4f4")
89BAR_STROKE = HexColor("#666666")
92@dataclass
93class Actor:
94 id: str
95 label: str
96 kind: str = "participant"
97 box: int | None = None
98 #: Drawn where it is created, not in the header.
99 created: bool = False
102@dataclass
103class Message:
104 source: int
105 target: int
106 stroke: Stroke
107 start: str | None
108 end: str | None
109 text: str
110 activate: bool = False
111 deactivate: bool = False
112 number: int | None = None
115@dataclass
116class Note:
117 place: str
118 actors: tuple[int, ...]
119 text: str
122@dataclass
123class Open:
124 kind: str
125 text: str
126 color: Color | None = None
129@dataclass
130class Section:
131 kind: str
132 text: str
135@dataclass
136class Close:
137 pass
140@dataclass
141class Activation:
142 actor: int
143 on: bool
146@dataclass
147class Create:
148 actor: int
151@dataclass
152class Destroy:
153 actor: int
156Event = Message | Note | Open | Section | Close | Activation | Create | Destroy
159@dataclass
160class Box:
161 title: str
162 color: Color | None
163 actors: list[int] = field(default_factory=list)
166@register_diagram
167class SequenceDiagram(Diagram):
168 keywords = ("sequenceDiagram",)
169 noun = "a sequence diagram"
171 def __init__(self) -> None:
172 self.actors: list[Actor] = []
173 self.index: dict[str, int] = {}
174 self.events: list[Event] = []
175 self.boxes: list[Box] = []
176 self.title = None
177 self._stack: list[str] = []
178 self._box: int | None = None
179 self._number: int | None = None
180 self._step = 1
182 @classmethod
183 def parse(cls, header: Statement, statements: list[Statement]) -> SequenceDiagram:
184 diagram = cls()
185 lines = iter(statements)
186 for statement in lines:
187 first = statement.text.split(maxsplit=1)[0]
188 if (
189 first.startswith("accDescr")
190 and "{" in statement.text
191 and "}" not in statement.text
192 ):
193 for later in lines:
194 if "}" in later.text:
195 break
196 continue
197 diagram._statement(statement)
198 if diagram._stack:
199 raise MermaidSyntaxError(None, f"a '{diagram._stack[-1]}' has no 'end'")
200 if not diagram.actors:
201 raise MermaidSyntaxError(None, "it has no participants")
202 return diagram
204 def _actor(
205 self, aid: str, line: int, *, label: str | None = None, kind: str | None = None
206 ) -> int:
207 aid = aid.strip()
208 if not aid:
209 raise MermaidSyntaxError(line, "a participant's name is missing")
210 if aid not in self.index:
211 if len(self.actors) >= MAX_NODES:
212 raise MermaidSyntaxError(
213 None, f"it has more than {MAX_NODES} participants"
214 )
215 self.index[aid] = len(self.actors)
216 self.actors.append(Actor(aid, aid, box=self._box))
217 if self._box is not None:
218 self.boxes[self._box].actors.append(self.index[aid])
219 actor = self.actors[self.index[aid]]
220 if label:
221 actor.label = label
222 if kind:
223 actor.kind = kind
224 return self.index[aid]
226 def _event(self, event: Event) -> None:
227 self.events.append(event)
228 if len(self.events) > 2 * MAX_EDGES:
229 raise MermaidSyntaxError(None, f"it has more than {2 * MAX_EDGES} lines")
231 def _statement(self, statement: Statement) -> None:
232 text, line = statement.text, statement.line
233 first, _, rest = text.partition(" ")
234 rest = rest.strip()
235 lowered = first.lower()
236 if lowered in _BLOCKS:
237 if lowered == "rect":
238 color = parse_color(rest, HexColor("#e8e8e8"))
239 self._event(Open("rect", "", color))
240 else:
241 self._event(Open("par" if lowered == "par_over" else lowered, rest))
242 self._stack.append(lowered)
243 return
244 if lowered in _SECTIONS:
245 owner = _SECTIONS[lowered]
246 if not self._stack or self._stack[-1].replace("par_over", "par") != owner:
247 raise MermaidSyntaxError(line, f"'{lowered}' belongs inside '{owner}'")
248 self._event(Section(lowered, rest))
249 return
250 if lowered == "box":
251 if self._box is not None:
252 raise MermaidSyntaxError(line, "a box cannot hold another box")
253 color, title = self._box_heading(rest)
254 self.boxes.append(Box(title, color))
255 self._box = len(self.boxes) - 1
256 self._stack.append("box")
257 return
258 if lowered == "end":
259 if not self._stack:
260 raise MermaidSyntaxError(line, "'end' closes nothing")
261 if self._stack.pop() == "box":
262 self._box = None
263 else:
264 self._event(Close())
265 return
266 if lowered == "autonumber":
267 if rest == "off":
268 self._number = None
269 return
270 numbers = rest.split()
271 try:
272 self._number = int(numbers[0]) if numbers else 1
273 self._step = int(numbers[1]) if len(numbers) > 1 else 1
274 except ValueError:
275 raise MermaidSyntaxError(
276 line, "autonumber takes a start and a step"
277 ) from None
278 return
279 if lowered in ("activate", "deactivate"):
280 self._event(Activation(self._actor(rest, line), lowered == "activate"))
281 return
282 if lowered == "destroy":
283 self._event(Destroy(self._actor(rest, line)))
284 return
285 titled = re.match(r"^title\b\s*:?\s*(.*)$", text)
286 if titled:
287 self.title = titled.group(1).strip() or None
288 return
289 if first.startswith(_SKIPPED):
290 return
291 m = _ACTOR.match(text)
292 if m:
293 kind = m.group("kind")
294 props = m.group("props") or ""
295 typed = re.search(r'"type"\s*:\s*"(\w+)"', props)
296 if typed and typed.group(1) == "actor":
297 kind = "actor"
298 index = self._actor(m.group("id"), line, label=m.group("alias"), kind=kind)
299 if m.group("create"):
300 self.actors[index].created = True
301 self._event(Create(index))
302 return
303 m = _NOTE.match(text)
304 if m:
305 who = tuple(self._actor(name, line) for name in m.group("who").split(","))
306 place = m.group("place").lower()
307 if len(who) > 2 or (len(who) == 2 and place != "over"):
308 raise MermaidSyntaxError(
309 line, "a note is over one or two participants, or beside one"
310 )
311 self._event(Note(place, who, m.group("text")))
312 return
313 m = _MESSAGE.match(text)
314 if m:
315 stroke, start, end = _ARROWS[m.group("arrow")]
316 source = self._actor(m.group("a"), line)
317 target = self._actor(m.group("b"), line)
318 message = Message(
319 source, target, stroke, start, end, (m.group("text") or "").strip(),
320 activate=m.group("sign") == "+", deactivate=m.group("sign") == "-",
321 ) # fmt: skip
322 if self._number is not None:
323 message.number = self._number
324 self._number += self._step
325 self._event(message)
326 return
327 raise MermaidSyntaxError(
328 line, "this line is not a participant, a message, a note or a block"
329 )
331 @staticmethod
332 def _box_heading(rest: str) -> tuple[Color | None, str]:
333 """``box Aqua Title``, ``box rgb(1,2,3) Title``, ``box Title``."""
334 m = re.match(
335 r"^(rgba?\([^)]*\)|hsla?\([^)]*\)|#[0-9a-fA-F]{3,8}|transparent)\s*(.*)$",
336 rest,
337 )
338 if m:
339 color = (
340 None
341 if m.group(1) == "transparent"
342 else parse_color(m.group(1), HexColor("#f2f2f2"))
343 )
344 return color, m.group(2)
345 word, _, title = rest.partition(" ")
346 unknown = Color(0, 0, 0, 0)
347 named = parse_color(word, unknown)
348 if named is not unknown:
349 return named, title
350 return None, rest
352 # ── layout ────────────────────────────────────────────────────────────
354 def layout(self, theme: Theme) -> Layout:
355 return _Drawer(self, theme).draw()
358@dataclass
359class _Frame:
360 kind: str
361 text: str
362 color: Color | None
363 top: float
364 lo: float = float("inf")
365 hi: float = float("-inf")
366 sections: list[tuple[float, str]] = field(default_factory=list)
367 bottom: float = 0.0
370class _Drawer:
371 """Two passes: geometry first (so the drawing's extent is known), then
372 the shapes, moved right by what reaches left of the first column."""
374 def __init__(self, diagram: SequenceDiagram, theme: Theme) -> None:
375 self.d = diagram
376 self.theme = theme
377 self.font = theme.regular
378 self.size = look.FONT_SIZE
379 self.lh = self.size * look.LINE_HEIGHT
381 def _lines(self, text: str, width: float, most: int = 6) -> list[str]:
382 return fit(text, self.font, self.size, width, most) if text.strip() else []
384 def draw(self) -> Layout:
385 d, font, size, lh = self.d, self.font, self.size, self.lh
386 n = len(d.actors)
387 names = [self._lines(a.label, 150.0, 3) or [""] for a in d.actors]
388 sizes: list[tuple[float, float]] = []
389 for actor, lines in zip(d.actors, names):
390 tw, th = block_size(lines, font, size)
391 if actor.kind == "actor":
392 sizes.append((max(tw, STICK) + 8, STICK + 4 + th))
393 else:
394 sizes.append(
395 (max(tw + 2 * PAD_X, ACTOR_MIN_W), max(th + 2 * PAD_Y, ACTOR_MIN_H))
396 )
397 head = max(h for _, h in sizes)
399 # Columns: each message's label between its lifelines, each note and
400 # self-message in the gap beside it.
401 need: dict[tuple[int, int], float] = {}
403 def require(a: int, b: int, gap: float) -> None:
404 if a == b:
405 return
406 a, b = min(a, b), max(a, b)
407 need[(a, b)] = max(need.get((a, b), 0.0), gap)
409 for i in range(n - 1):
410 require(i, i + 1, sizes[i][0] / 2 + sizes[i + 1][0] / 2 + ACTOR_GAP)
411 texts: list[list[str]] = []
412 for event in d.events:
413 lines: list[str] = []
414 if isinstance(event, Message):
415 lines = self._lines(event.text, LABEL_MAX)
416 width = block_size(lines, font, size)[0] if lines else 0.0
417 if event.number is not None:
418 width += 16
419 if event.source == event.target:
420 if event.source + 1 < n:
421 require(event.source, event.source + 1, LOOP + 6 + width + 10)
422 else:
423 require(event.source, event.target, width + 24)
424 elif isinstance(event, Note):
425 lines = self._lines(event.text, NOTE_MAX, 10)
426 width = block_size(lines, font, size)[0] + 2 * NOTE_PAD
427 i = event.actors[0]
428 if event.place == "right of" and i + 1 < n:
429 require(i, i + 1, width + 20)
430 elif event.place == "left of" and i > 0:
431 require(i - 1, i, width + 20)
432 elif event.place == "over" and len(event.actors) == 2:
433 require(event.actors[0], event.actors[1], width - 2 * FRAME_PAD)
434 elif event.place == "over":
435 if i > 0:
436 require(i - 1, i, width / 2 + 12)
437 if i + 1 < n:
438 require(i, i + 1, width / 2 + 12)
439 elif isinstance(event, (Open, Section)) and event.text:
440 lines = self._lines(f"[{event.text}]", 300.0, 2)
441 texts.append(lines)
442 # Every constraint runs left to right, so by target each column's
443 # sources are already placed.
444 xs = [0.0] * n
445 for (a, b), gap in sorted(need.items(), key=lambda item: item[0][1]):
446 xs[b] = max(xs[b], xs[a] + gap)
448 # Rows.
449 top = (lh + 8.0) if d.boxes else 0.0
450 y = top + head + 12.0
451 breaks: list[float] = []
452 spans: list[tuple[float, float]] = [] # what reaches left and right
453 for x, (w, _) in zip(xs, sizes):
454 spans.append((x - w / 2, x + w / 2))
455 frames: list[_Frame] = []
456 closed: list[_Frame] = []
457 active: dict[int, list[float]] = {}
458 bars: list[tuple[int, float, float, int]] = []
459 drawn: list[tuple[str, object]] = []
460 created_at: dict[int, float] = {}
461 destroyed_at: dict[int, float] = {}
463 def reach(lo: float, hi: float) -> None:
464 spans.append((lo, hi))
465 for frame in frames:
466 frame.lo = min(frame.lo, lo)
467 frame.hi = max(frame.hi, hi)
469 def level(actor: int) -> int:
470 return len(active.get(actor, []))
472 def edge_x(actor: int, toward: float) -> float:
473 depth = level(actor)
474 if not depth:
475 return xs[actor]
476 offset = BAR / 2 + 4.0 * (depth - 1)
477 return xs[actor] + (offset if toward > xs[actor] else -offset)
479 def start_bar(actor: int, at: float) -> None:
480 active.setdefault(actor, []).append(at)
482 def end_bar(actor: int, at: float) -> None:
483 stack = active.get(actor)
484 if stack:
485 started = stack.pop()
486 bars.append((actor, started, at, len(stack)))
488 for event, lines in zip(d.events, texts):
489 if isinstance(event, Message):
490 label_h = block_size(lines, font, size)[1] if lines else 0.0
491 if event.source == event.target:
492 x = edge_x(event.source, xs[event.source] + 1)
493 y1 = y + 8.0
494 y2 = y1 + max(16.0, label_h)
495 drawn.append(("self", (event, x, y1, y2, lines)))
496 width = block_size(lines, font, size)[0] if lines else 0.0
497 reach(
498 x,
499 x + LOOP + 6 + width + (16 if event.number is not None else 0),
500 )
501 y = y2 + 10.0
502 else:
503 arrow = y + 8.0 + label_h
504 if event.activate:
505 start_bar(event.target, arrow)
506 x1 = edge_x(event.source, xs[event.target])
507 x2 = edge_x(event.target, xs[event.source])
508 drawn.append(("message", (event, x1, x2, arrow, y + 4.0, lines)))
509 reach(min(x1, x2), max(x1, x2))
510 if event.deactivate:
511 end_bar(event.source, arrow)
512 y = arrow + 10.0
513 elif isinstance(event, Note):
514 note_w = block_size(lines, font, size)[0] + 2 * NOTE_PAD
515 note_h = block_size(lines, font, size)[1] + 2 * NOTE_PAD
516 i = event.actors[0]
517 if event.place == "right of":
518 left = edge_x(i, xs[i] + 1) + 10.0
519 elif event.place == "left of":
520 left = edge_x(i, xs[i] - 1) - 10.0 - note_w
521 elif len(event.actors) == 2:
522 lo, hi = sorted(xs[a] for a in event.actors)
523 note_w = max(note_w, hi - lo + 2 * FRAME_PAD)
524 left = (lo + hi) / 2 - note_w / 2
525 else:
526 note_w = max(note_w, 60.0)
527 left = xs[i] - note_w / 2
528 drawn.append(("note", (left, y + 6.0, note_w, note_h, lines)))
529 reach(left, left + note_w)
530 y += 6.0 + note_h + 8.0
531 elif isinstance(event, Open):
532 frames.append(_Frame(event.kind, event.text, event.color, y + 4.0))
533 y += 4.0 + (self.lh + 4.0 if event.kind != "rect" else 0.0) + 8.0
534 elif isinstance(event, Section):
535 frames[-1].sections.append((y + 2.0, event.text))
536 y += 2.0 + self.lh + 8.0
537 elif isinstance(event, Close):
538 frame = frames.pop()
539 frame.bottom = y + 4.0
540 if frame.lo == float("inf"):
541 frame.lo, frame.hi = xs[0] - 30.0, xs[0] + 30.0
542 frame.lo -= FRAME_PAD
543 frame.hi += FRAME_PAD
544 # Wide enough for its tab and every condition beside it.
545 tab = measure(frame.kind, self.theme.bold, self.size) + 14.0
546 said = [frame.text, *(text for _, text in frame.sections)]
547 widest = max(
548 (measure(f"[{t}]", font, size) for t in said if t), default=0.0
549 )
550 frame.hi = max(frame.hi, frame.lo + tab + 16.0 + widest)
551 closed.append(frame)
552 reach(frame.lo, frame.hi)
553 y += 10.0
554 elif isinstance(event, Activation):
555 if event.on:
556 start_bar(event.actor, y)
557 else:
558 end_bar(event.actor, y)
559 continue
560 elif isinstance(event, Create):
561 created_at[event.actor] = y + 4.0
562 y += 4.0 + sizes[event.actor][1] + 8.0
563 elif isinstance(event, Destroy):
564 destroyed_at[event.actor] = y + 6.0
565 y += 16.0
566 breaks.append(y)
567 for actor, stack in active.items():
568 while stack:
569 bars.append((actor, stack.pop(), y, len(stack)))
570 foot = y + 10.0
571 height = foot + head + MARGIN
572 for box in d.boxes:
573 members = [i for i in box.actors]
574 if members:
575 lo = min(xs[i] - sizes[i][0] / 2 for i in members) - 8.0
576 hi = max(xs[i] + sizes[i][0] / 2 for i in members) + 8.0
577 title_w = measure(box.title, self.theme.bold, self.size) + 16.0
578 spans.append((lo, max(hi, lo + title_w)))
579 left = min(lo for lo, _ in spans) - MARGIN
580 right = max(hi for _, hi in spans) + MARGIN
581 width = right - left
582 dx = -left
584 canvas = Canvas(width, height)
585 header = Canvas(width, head + 6.0)
586 X = [x + dx for x in xs]
588 # Box groups, then rect backgrounds.
589 for box in d.boxes:
590 if not box.actors:
591 continue
592 lo = min(X[i] - sizes[i][0] / 2 for i in box.actors) - 8.0
593 hi = max(X[i] + sizes[i][0] / 2 for i in box.actors) + 8.0
594 title_w = measure(box.title, self.theme.bold, self.size) + 16.0
595 hi = max(hi, lo + title_w)
596 if box.color is not None:
597 canvas.rect(
598 lo,
599 2.0,
600 hi - lo,
601 height - 4.0,
602 fill=box.color,
603 stroke=None,
604 width=0,
605 fill_opacity=0.35,
606 )
607 canvas.rect(
608 lo, 2.0, hi - lo, height - 4.0, fill=None, stroke=LIFELINE, width=0.5
609 )
610 if box.title:
611 canvas.text(
612 (lo + hi) / 2,
613 2.0 + lh * 0.8 + 2,
614 box.title,
615 font=self.theme.bold,
616 size=size,
617 color=look.TEXT,
618 )
619 for frame in closed:
620 if frame.kind == "rect":
621 canvas.rect(
622 frame.lo + dx, frame.top, frame.hi - frame.lo, frame.bottom - frame.top,
623 fill=frame.color, stroke=None, width=0, fill_opacity=0.5,
624 ) # fmt: skip
626 # Lifelines, then activation bars.
627 for i, x in enumerate(X):
628 start = created_at[i] + sizes[i][1] if i in created_at else top + head
629 end = destroyed_at.get(i, foot)
630 canvas.line(x, start, x, end, color=LIFELINE, width=0.6)
631 for actor, y0, y1, depth in bars:
632 x = X[actor] - BAR / 2 + 4.0 * depth
633 canvas.rect(
634 x,
635 y0,
636 BAR,
637 max(y1 - y0, 4.0),
638 fill=BAR_FILL,
639 stroke=BAR_STROKE,
640 width=0.6,
641 )
643 # Frames.
644 for frame in closed:
645 if frame.kind != "rect":
646 self._frame(canvas, frame, dx)
648 # Participants: the header, the foot, those created on the way.
649 for i, actor in enumerate(d.actors):
650 if i in created_at:
651 self._actor(canvas, X[i], created_at[i], sizes[i], actor, names[i])
652 else:
653 self._actor(canvas, X[i], top, sizes[i], actor, names[i])
654 if i not in destroyed_at:
655 self._actor(canvas, X[i], foot, sizes[i], actor, names[i])
656 self._actor(header, X[i], 0.0, sizes[i], actor, names[i])
657 header.line(X[i], sizes[i][1], X[i], head + 6.0, color=LIFELINE, width=0.6)
659 # Messages and notes.
660 for kind, item in drawn:
661 if kind == "message":
662 event, x1, x2, arrow, label_top, lines = item # type: ignore[misc]
663 self._message(canvas, event, x1 + dx, x2 + dx, arrow, label_top, lines)
664 elif kind == "self":
665 event, x, y1, y2, lines = item # type: ignore[misc]
666 self._self(canvas, event, x + dx, y1, y2, lines)
667 else:
668 left_x, y0, w, h, lines = item # type: ignore[misc]
669 canvas.rect(
670 left_x + dx,
671 y0,
672 w,
673 h,
674 fill=look.NOTE_FILL,
675 stroke=look.NOTE_STROKE,
676 width=0.6,
677 )
678 canvas.lines(
679 left_x + dx + w / 2,
680 y0 + h / 2,
681 lines,
682 font=font,
683 size=size,
684 color=look.TEXT,
685 )
686 for actor, at in destroyed_at.items():
687 x = X[actor]
688 for sign in (1, -1):
689 canvas.line(
690 x - 6,
691 at - 6 * sign,
692 x + 6,
693 at + 6 * sign,
694 color=look.LINE,
695 width=1.4,
696 )
698 return Layout(
699 canvas.drawing(),
700 width,
701 height,
702 breaks=tuple(b for b in breaks if top + head + 20 < b < foot - 4),
703 header=header.drawing(),
704 )
706 def _actor(
707 self,
708 canvas: Canvas,
709 x: float,
710 y: float,
711 size: tuple[float, float],
712 actor: Actor,
713 lines: list[str],
714 ) -> None:
715 w, h = size
716 font, fsize = self.font, self.size
717 if actor.kind == "actor":
718 cx, head_r = x, 4.5
719 top = y + 2
720 canvas.circle(
721 cx,
722 top + head_r,
723 head_r,
724 fill=look.NODE_FILL,
725 stroke=look.NODE_STROKE,
726 width=1.0,
727 )
728 neck, hip = top + 2 * head_r, top + 2 * head_r + 10
729 canvas.line(cx, neck, cx, hip, color=look.NODE_STROKE, width=1.0)
730 canvas.line(
731 cx - 8, neck + 4, cx + 8, neck + 4, color=look.NODE_STROKE, width=1.0
732 )
733 canvas.line(
734 cx, hip, cx - 7, top + STICK - 2, color=look.NODE_STROKE, width=1.0
735 )
736 canvas.line(
737 cx, hip, cx + 7, top + STICK - 2, color=look.NODE_STROKE, width=1.0
738 )
739 _, th = block_size(lines, font, fsize)
740 canvas.lines(
741 cx,
742 y + STICK + 4 + th / 2,
743 lines,
744 font=font,
745 size=fsize,
746 color=look.TEXT,
747 )
748 return
749 canvas.rect(
750 x - w / 2,
751 y,
752 w,
753 h,
754 radius=3.0,
755 fill=look.NODE_FILL,
756 stroke=look.NODE_STROKE,
757 width=look.NODE_STROKE_WIDTH,
758 )
759 canvas.lines(x, y + h / 2, lines, font=font, size=fsize, color=look.TEXT)
761 def _message(
762 self,
763 canvas: Canvas,
764 event: Message,
765 x1: float,
766 x2: float,
767 arrow: float,
768 label_top: float,
769 lines: list[str],
770 ) -> None:
771 dash = (3.0, 3.0) if event.stroke == "dotted" else None
772 draw_edge(
773 canvas, [(x1, arrow), (x2, arrow)], color=look.LINE, width=look.EDGE_WIDTH,
774 dash=dash, start=event.start, end=event.end,
775 ) # fmt: skip
776 if lines:
777 _, th = block_size(lines, self.font, self.size)
778 canvas.lines(
779 (x1 + x2) / 2,
780 label_top + th / 2,
781 lines,
782 font=self.font,
783 size=self.size,
784 color=look.TEXT,
785 )
786 if event.number is not None:
787 self._number(canvas, x1, arrow, event.number)
789 def _self(
790 self,
791 canvas: Canvas,
792 event: Message,
793 x: float,
794 y1: float,
795 y2: float,
796 lines: list[str],
797 ) -> None:
798 dash = (3.0, 3.0) if event.stroke == "dotted" else None
799 points = [(x, y1), (x + LOOP, y1), (x + LOOP, y2), (x, y2)]
800 draw_edge(
801 canvas, points, color=look.LINE, width=look.EDGE_WIDTH,
802 dash=dash, start=event.start, end=event.end,
803 ) # fmt: skip
804 shift = 16.0 if event.number is not None else 0.0
805 if lines:
806 canvas.lines(
807 x + LOOP + 6 + shift, (y1 + y2) / 2, lines,
808 font=self.font, size=self.size, color=look.TEXT, anchor="start",
809 ) # fmt: skip
810 if event.number is not None:
811 self._number(canvas, x + LOOP + 6 + 6, (y1 + y2) / 2, event.number)
813 def _number(self, canvas: Canvas, x: float, y: float, number: int) -> None:
814 text = str(number)
815 r = max(6.0, measure(text, self.theme.bold, 7.0) / 2 + 2.5)
816 canvas.circle(x, y, r, fill=look.LINE, stroke=look.LINE, width=0.5)
817 canvas.text(x, y + 2.5, text, font=self.theme.bold, size=7.0, color=look.WHITE)
819 def _frame(self, canvas: Canvas, frame: _Frame, dx: float) -> None:
820 lo, hi = frame.lo + dx, frame.hi + dx
821 bold, size, lh = self.theme.bold, self.size, self.lh
822 canvas.rect(
823 lo,
824 frame.top,
825 hi - lo,
826 frame.bottom - frame.top,
827 fill=None,
828 stroke=FRAME,
829 width=0.9,
830 )
831 tab_w = measure(frame.kind, bold, size) + 14.0
832 tab_h = lh + 4.0
833 t = frame.top
834 canvas.polygon(
835 [(lo, t), (lo + tab_w, t), (lo + tab_w, t + tab_h - 5), (lo + tab_w - 5, t + tab_h), (lo, t + tab_h)],
836 fill=look.NODE_FILL, stroke=FRAME, width=0.9,
837 ) # fmt: skip
838 canvas.text(
839 lo + 6,
840 t + tab_h / 2 + size * 0.35,
841 frame.kind,
842 font=bold,
843 size=size,
844 color=look.TEXT,
845 anchor="start",
846 )
847 if frame.text:
848 text = f"[{frame.text}]"
849 centre = (lo + hi) / 2
850 wide = measure(text, self.font, size)
851 if centre - wide / 2 < lo + tab_w + 6:
852 canvas.text(
853 lo + tab_w + 8,
854 t + tab_h / 2 + size * 0.35,
855 text,
856 font=self.font,
857 size=size,
858 color=look.TEXT,
859 anchor="start",
860 )
861 else:
862 canvas.text(
863 centre,
864 t + tab_h / 2 + size * 0.35,
865 text,
866 font=self.font,
867 size=size,
868 color=look.TEXT,
869 )
870 for at, text in frame.sections:
871 canvas.line(lo, at, hi, at, color=FRAME, width=0.9, dash=(3.0, 3.0))
872 if text:
873 canvas.text(
874 (lo + hi) / 2,
875 at + lh / 2 + size * 0.35 + 2,
876 f"[{text}]",
877 font=self.font,
878 size=size,
879 color=look.TEXT,
880 )