mgram 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mgram/__init__.py +107 -0
- mgram/__main__.py +6 -0
- mgram/check.py +321 -0
- mgram/cli.py +319 -0
- mgram/dsl.py +303 -0
- mgram/geometry.py +213 -0
- mgram/grid.py +610 -0
- mgram/labels.py +209 -0
- mgram/place.py +671 -0
- mgram/refs.py +85 -0
- mgram/registry.py +245 -0
- mgram/route.py +646 -0
- mgram/scene.py +153 -0
- mgram/sphinx.py +332 -0
- mgram/svg.py +138 -0
- mgram/text.py +28 -0
- mgram/theme.py +190 -0
- mgram/types/__init__.py +4 -0
- mgram/types/block.py +203 -0
- mgram/types/ceremony.py +208 -0
- mgram/types/classes.py +162 -0
- mgram/types/component.py +129 -0
- mgram/types/dfd.py +160 -0
- mgram/types/gantt.py +730 -0
- mgram/types/hydraulic.py +393 -0
- mgram/types/layers.py +272 -0
- mgram/types/packet.py +391 -0
- mgram/types/sequence.py +695 -0
- mgram/types/state.py +219 -0
- mgram/types/uml.py +62 -0
- mgram-0.1.0.dist-info/METADATA +139 -0
- mgram-0.1.0.dist-info/RECORD +35 -0
- mgram-0.1.0.dist-info/WHEEL +4 -0
- mgram-0.1.0.dist-info/entry_points.txt +2 -0
- mgram-0.1.0.dist-info/licenses/LICENSE +202 -0
mgram/__init__.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Jonas Remmert
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""mgram: diagrams from text files on a grid, with readability checks."""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
from dataclasses import dataclass, field, replace
|
|
9
|
+
|
|
10
|
+
from . import check, grid, refs as _refs, svg as _svg
|
|
11
|
+
from .dsl import SIZES, MgramError, Model, parse, validate
|
|
12
|
+
from .registry import DiagramType, get as get_type, register, types as diagram_types
|
|
13
|
+
from .scene import Scene
|
|
14
|
+
from .theme import DEFAULT as DEFAULT_THEME, Theme, load as load_theme
|
|
15
|
+
|
|
16
|
+
__all__ = ["Diagram", "DiagramType", "MgramError", "Theme", "catalog", "freeze", "get_type", "load_theme",
|
|
17
|
+
"parse", "register", "render", "diagram_types"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Diagram:
|
|
22
|
+
scene: Scene
|
|
23
|
+
theme: Theme
|
|
24
|
+
findings: list = field(default_factory=list)
|
|
25
|
+
model: Model | None = None
|
|
26
|
+
layout: object = None
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def svg(self):
|
|
30
|
+
"""Standalone SVG with fixed size and the background of the theme."""
|
|
31
|
+
return _svg.render(self.scene, self.theme)
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def svg_inline(self):
|
|
35
|
+
"""SVG for inline use in HTML: scales to the page width; transparent with the default background."""
|
|
36
|
+
return _svg.render(self.scene, self.theme, html=True)
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def elements(self):
|
|
40
|
+
"""[{id, refs, kind, bbox: [x, y, w, h]}] in SVG user units; a connection adds points."""
|
|
41
|
+
return _refs.elements(self.scene)
|
|
42
|
+
|
|
43
|
+
def png(self, path=None, scale=1.5):
|
|
44
|
+
return _svg.png(self.svg, path, scale, self.theme.palette["bg"])
|
|
45
|
+
|
|
46
|
+
def pdf(self, path=None):
|
|
47
|
+
return _svg.pdf(self.svg, path)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build(model, theme=None, title="diagram", base=None, size=None):
|
|
51
|
+
"""Model -> Diagram: build the scene with the type's build (default: grid pipeline) and run all checks.
|
|
52
|
+
|
|
53
|
+
theme: a Theme, the name default or the path of a .toml theme file.
|
|
54
|
+
size: small, medium, large or tall; replaces the size setting of the source."""
|
|
55
|
+
if size is not None:
|
|
56
|
+
if size not in SIZES:
|
|
57
|
+
raise MgramError(f"unknown size '{size}' (sizes: {', '.join(SIZES)})")
|
|
58
|
+
model = replace(model, size=size)
|
|
59
|
+
dtype = get_type(model.type)
|
|
60
|
+
validate(model, dtype, check.check_names(dtype))
|
|
61
|
+
theme = load_theme(theme).for_type(dtype)
|
|
62
|
+
scene, layout = (dtype.build or grid.build)(model, dtype, theme, title)
|
|
63
|
+
scene.units = _refs.units(model, scene)
|
|
64
|
+
findings = check.run(scene, layout, dtype, theme, model.allows, base)
|
|
65
|
+
return Diagram(scene, theme, findings, model, layout)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def render(text, theme=None, title="diagram", base=None, size=None):
|
|
69
|
+
"""Source text -> Diagram with .svg, .svg_inline, .findings, .png(), .pdf(); theme and size as for build().
|
|
70
|
+
|
|
71
|
+
base: directory of the source file, for detail= (default: the current directory).
|
|
72
|
+
Raises MgramError (with .line) on a syntax error."""
|
|
73
|
+
return build(parse(text), theme, title, base, size)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def freeze(text):
|
|
77
|
+
"""Write the placer's cells into the source as `col` and `row` on each element and group, in place
|
|
78
|
+
of the hints there; all other text stays as it is, and the render stays the same. A source in
|
|
79
|
+
which each element has `at` comes back unchanged."""
|
|
80
|
+
model = parse(text)
|
|
81
|
+
dtype = get_type(model.type)
|
|
82
|
+
validate(model, dtype, check.check_names(dtype))
|
|
83
|
+
if dtype.build:
|
|
84
|
+
raise MgramError(f"{dtype.name} has no placer: the order of the statements is the layout, "
|
|
85
|
+
"so freeze has nothing to write", 1)
|
|
86
|
+
if all(e.at is not None for e in model.elements.values()):
|
|
87
|
+
return text
|
|
88
|
+
theme = DEFAULT_THEME.for_type(dtype)
|
|
89
|
+
cells = grid.positions(grid.prepare(model, dtype, theme), dtype, theme).cells
|
|
90
|
+
rows = text.splitlines(keepends=True)
|
|
91
|
+
for u in list(model.elements.values()) + list(model.groups.values()):
|
|
92
|
+
head, colon, rest = rows[u.line - 1].partition(":")
|
|
93
|
+
head = re.sub(r"\s+(?:col|row)=\S+", "", head)
|
|
94
|
+
m = re.match(r"\s*\S+\s+\w+", head)
|
|
95
|
+
col, row = cells[u.id]
|
|
96
|
+
rows[u.line - 1] = f"{head[:m.end()]} col={col} row={row}{head[m.end():]}{colon}{rest}"
|
|
97
|
+
return "".join(rows)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def catalog(type_name, theme=None):
|
|
101
|
+
"""All element kinds of a diagram type with their port names. A type with its own build has no
|
|
102
|
+
symbols with ports; its catalog is its example, which uses each kind."""
|
|
103
|
+
dtype = get_type(type_name)
|
|
104
|
+
if dtype.build:
|
|
105
|
+
return render(dtype.example, theme, f"{dtype.name} catalog")
|
|
106
|
+
theme = load_theme(theme).for_type(dtype)
|
|
107
|
+
return Diagram(grid.catalog(dtype, theme), theme)
|
mgram/__main__.py
ADDED
mgram/check.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Jonas Remmert
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Findings and the geometric checks, which see only the scene."""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
from dataclasses import asdict, dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from .geometry import (crossing, edges, ellipse_ov, gap, head_boxes, horizontal, inset, num, overlap, parallel_gap,
|
|
12
|
+
rect_ov, seg_hits, seg_hits_ellipse, shared)
|
|
13
|
+
from .place import downward
|
|
14
|
+
|
|
15
|
+
CHECKS = {
|
|
16
|
+
"overlap": "two element outlines overlap",
|
|
17
|
+
"through": "a line runs through an element",
|
|
18
|
+
"on-top": "two lines run on top of each other",
|
|
19
|
+
"label-overlap": "a label overlaps another label, an element or a line",
|
|
20
|
+
"label-fit": "a label does not fit inside its element",
|
|
21
|
+
"label-between": "a label beside a line that lies as close to another parallel line",
|
|
22
|
+
"spacing": "elements or parallel lines closer than the minimum spacing",
|
|
23
|
+
"crossings": "more line crossings than the limit of the theme",
|
|
24
|
+
"size": "the diagram is larger than its size setting",
|
|
25
|
+
"frame": "an element or frame inside a group frame it does not belong to, or two frames that overlap",
|
|
26
|
+
"border": "a line that runs along a frame border, or a label that crosses one",
|
|
27
|
+
"detail": "a detail= file that does not exist",
|
|
28
|
+
}
|
|
29
|
+
SIDE_NAMES = {"n": "north", "e": "east", "s": "south", "w": "west"}
|
|
30
|
+
TOLERANCE = 1.03 # a diagram may exceed its size setting by 3 %
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class Finding:
|
|
35
|
+
check: str
|
|
36
|
+
line: int
|
|
37
|
+
message: str
|
|
38
|
+
fix: str = ""
|
|
39
|
+
|
|
40
|
+
def __str__(self):
|
|
41
|
+
return f"line {self.line}: {self.message}" + (f"; fix: {self.fix}" if self.fix else "") + f" [{self.check}]"
|
|
42
|
+
|
|
43
|
+
def to_dict(self):
|
|
44
|
+
return asdict(self)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def check_names(dtype):
|
|
48
|
+
return {**CHECKS, **{c.name: c.doc for c in dtype.checks}}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def run(scene, layout, dtype, theme, allows=None, base=None):
|
|
52
|
+
"""base: directory that detail= files are relative to (default: the current directory)."""
|
|
53
|
+
model = getattr(layout, "model", None)
|
|
54
|
+
turn = None
|
|
55
|
+
if dtype.placer is not None and model is not None and not downward(model, dtype):
|
|
56
|
+
turn = "remove the flag horizontal" if dtype.down else "try the flag vertical"
|
|
57
|
+
found = (geometric(scene, theme) + size(scene, theme, turn) + frames(scene, theme)
|
|
58
|
+
+ details(scene, Path(base or ".")))
|
|
59
|
+
for c in dtype.checks:
|
|
60
|
+
found += [Finding(c.name, *item) for item in c.fn(layout)]
|
|
61
|
+
out, seen = [], set()
|
|
62
|
+
for f in found:
|
|
63
|
+
key = (f.check, f.message)
|
|
64
|
+
if key not in seen and f.check not in (allows or {}):
|
|
65
|
+
seen.add(key)
|
|
66
|
+
out.append(f)
|
|
67
|
+
return sorted(out, key=lambda f: f.line)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Units:
|
|
71
|
+
"""Positions and distances of the scene in grid units, for messages."""
|
|
72
|
+
|
|
73
|
+
def __init__(self, theme):
|
|
74
|
+
self.g = theme.grid
|
|
75
|
+
|
|
76
|
+
def pt(self, x, y):
|
|
77
|
+
return f"{num(x / self.g)},{num(y / self.g)}"
|
|
78
|
+
|
|
79
|
+
def len(self, px):
|
|
80
|
+
return f"{math.ceil(px / self.g * 2) / 2:g}"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def geometric(scene, theme):
|
|
84
|
+
u, space, out = Units(theme), theme.min_space, []
|
|
85
|
+
|
|
86
|
+
def push(a, b, need):
|
|
87
|
+
"""Fix text: move outline b away from a until `need` px are free."""
|
|
88
|
+
ox = min(a.box[2], b.box[2]) - max(a.box[0], b.box[0]) + need
|
|
89
|
+
oy = min(a.box[3], b.box[3]) - max(a.box[1], b.box[1]) + need
|
|
90
|
+
ca, cb = ((a.box[0] + a.box[2]) / 2, (a.box[1] + a.box[3]) / 2), ((b.box[0] + b.box[2]) / 2,
|
|
91
|
+
(b.box[1] + b.box[3]) / 2)
|
|
92
|
+
if ox <= oy:
|
|
93
|
+
return f"move {b.id} {u.len(ox)} units {'right' if cb[0] >= ca[0] else 'left'}"
|
|
94
|
+
return f"move {b.id} {u.len(oy)} units {'down' if cb[1] >= ca[1] else 'up'}"
|
|
95
|
+
|
|
96
|
+
def where(s):
|
|
97
|
+
return f"{s.kind} {s.id} ({u.pt(*s.box[:2])} to {u.pt(*s.box[2:])})"
|
|
98
|
+
|
|
99
|
+
shapes = [s for s in scene.elements if not s.point]
|
|
100
|
+
segs = [(w, a, b) for w in scene.lines for a, b in w.segments()]
|
|
101
|
+
|
|
102
|
+
for i, a in enumerate(shapes):
|
|
103
|
+
for b in shapes[i + 1:]:
|
|
104
|
+
first, second = (a, b) if a.line <= b.line else (b, a)
|
|
105
|
+
if rect_ov(a.box, b.box, 1):
|
|
106
|
+
out.append(Finding("overlap", second.line, f"{where(second)} overlaps {where(first)}",
|
|
107
|
+
push(first, second, space)))
|
|
108
|
+
elif 0.5 < gap(a.box, b.box) < space:
|
|
109
|
+
out.append(Finding("spacing", second.line, f"{where(second)} is {gap(a.box, b.box):.0f} px from "
|
|
110
|
+
f"{where(first)}, less than {space:g} px", push(first, second, space)))
|
|
111
|
+
for w, a, b in segs:
|
|
112
|
+
for s in shapes:
|
|
113
|
+
if (seg_hits_ellipse if s.round else seg_hits)(a, b, inset(s.box, 1.5)):
|
|
114
|
+
out.append(Finding("through", w.line, f"{w.name} runs through {s.kind} {s.id} near {u.pt(*a)} -> "
|
|
115
|
+
f"{u.pt(*b)}", f"add a via point that leads around {s.id}, or move {s.id}"))
|
|
116
|
+
crossings = []
|
|
117
|
+
for i, (w, a, b) in enumerate(segs):
|
|
118
|
+
for v, c, d in segs[i + 1:]:
|
|
119
|
+
if v is w:
|
|
120
|
+
continue
|
|
121
|
+
if overlap(a, b, c, d):
|
|
122
|
+
out.append(Finding("on-top", v.line, f"{w.name} and {v.name} run on top of each other near "
|
|
123
|
+
f"{u.pt(*a)}", f"give one of them a via point at least {u.len(space)} units away"))
|
|
124
|
+
continue
|
|
125
|
+
d_par = parallel_gap(a, b, c, d, theme.grid / 2)
|
|
126
|
+
if d_par is not None and 1 <= d_par < space:
|
|
127
|
+
out.append(Finding("spacing", v.line, f"{w.name} and {v.name} run {d_par:.0f} px apart near "
|
|
128
|
+
f"{u.pt(*c)}, less than {space:g} px",
|
|
129
|
+
f"move a via point of one of them by {u.len(space)} units"))
|
|
130
|
+
x = crossing(a, b, c, d)
|
|
131
|
+
if x:
|
|
132
|
+
crossings.append((x, v))
|
|
133
|
+
if len(crossings) > theme.crossing_limit:
|
|
134
|
+
pts = ", ".join(u.pt(*x) for x, _ in crossings[:5])
|
|
135
|
+
out.append(Finding("crossings", crossings[0][1].line,
|
|
136
|
+
f"{len(crossings)} line crossings, more than {theme.crossing_limit} (at {pts}, ...)",
|
|
137
|
+
"move elements so that connected ones are neighbours, split the diagram, "
|
|
138
|
+
"or write 'allow crossings : <reason>'"))
|
|
139
|
+
return out + labels(scene, theme, shapes, segs)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def labels(scene, theme, shapes, segs):
|
|
143
|
+
out, wires = [], {w.name: w for w in scene.lines}
|
|
144
|
+
for i, l in enumerate(scene.labels):
|
|
145
|
+
name = f"label '{l.lines[0]}'"
|
|
146
|
+
for m in scene.labels[i + 1:]:
|
|
147
|
+
if rect_ov(l.box, m.box, 1):
|
|
148
|
+
out.append(Finding("label-overlap", max(l.line, m.line), f"{name} overlaps label '{m.lines[0]}'",
|
|
149
|
+
label_fix(scene, l, m)))
|
|
150
|
+
for s in shapes:
|
|
151
|
+
if s.id != l.inside and (ellipse_ov if s.round else rect_ov)(l.box, s.box, 1):
|
|
152
|
+
out.append(Finding("label-overlap", l.line, f"{name} overlaps {s.id}", label_fix(scene, l)))
|
|
153
|
+
for w, a, b in segs:
|
|
154
|
+
if seg_hits(a, b, inset(l.box, 1)) and not (l.on_line and w.name == l.owner):
|
|
155
|
+
out.append(Finding("label-overlap", l.line, f"{name} is crossed by {w.name}",
|
|
156
|
+
label_fix(scene, l, wires.get(w.name))))
|
|
157
|
+
for w in scene.lines:
|
|
158
|
+
if any(rect_ov(l.box, b, 1) for b in head_boxes(w.pts, w.heads)):
|
|
159
|
+
out.append(Finding("label-overlap", l.line, f"{name} covers an arrow head of {w.name}",
|
|
160
|
+
label_fix(scene, l, w)))
|
|
161
|
+
if l.inside:
|
|
162
|
+
s = next(s for s in scene.elements if s.id == l.inside)
|
|
163
|
+
if not (in_ellipse if s.round else contains)(inset(s.box, 2), l.box):
|
|
164
|
+
out.append(Finding("label-fit", l.line, f"{name} does not fit inside {s.kind} {s.id}",
|
|
165
|
+
f"shorten the label or enlarge {s.id}"))
|
|
166
|
+
own = wires.get(l.owner)
|
|
167
|
+
if own and not l.on_line:
|
|
168
|
+
other = between(l.box, own, scene.lines, theme.grid)
|
|
169
|
+
if other:
|
|
170
|
+
out.append(Finding("label-between", l.line, f"{name} of {own.name} lies as close to {other.name}",
|
|
171
|
+
label_fix(scene, l, other)))
|
|
172
|
+
return out
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def side_of(box, pt):
|
|
176
|
+
x, y = pt
|
|
177
|
+
d = {"w": abs(x - box[0]), "e": abs(x - box[2]), "n": abs(y - box[1]), "s": abs(y - box[3])}
|
|
178
|
+
return min(d, key=d.get)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def crowded(scene, wires):
|
|
182
|
+
"""(count, element id, side) of the side with most line ends among the ends of the given lines."""
|
|
183
|
+
shapes = {s.id: s for s in scene.elements if not s.point}
|
|
184
|
+
count = {}
|
|
185
|
+
for w in scene.lines:
|
|
186
|
+
for el, pt in zip(w.ends, (w.pts[0], w.pts[-1])):
|
|
187
|
+
if el in shapes:
|
|
188
|
+
key = (el, side_of(shapes[el].box, pt))
|
|
189
|
+
count[key] = count.get(key, 0) + 1
|
|
190
|
+
keys = {(el, side_of(shapes[el].box, pt)) for w in wires for el, pt in zip(w.ends, (w.pts[0], w.pts[-1]))
|
|
191
|
+
if el in shapes}
|
|
192
|
+
return max(((count[k], *k) for k in keys), default=None)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def label_fix(scene, l, other=None):
|
|
196
|
+
"""Fix text for a crowded label: names the crowded side or what to move apart."""
|
|
197
|
+
if l.inside:
|
|
198
|
+
return f"shorten the label or enlarge {l.owner}"
|
|
199
|
+
wires = [w for w in scene.lines if w.name == l.owner]
|
|
200
|
+
if not wires:
|
|
201
|
+
if l.owner in {s.id for s in scene.elements}:
|
|
202
|
+
return f"set label=<side> on {l.owner}, move {l.owner} or shorten the label"
|
|
203
|
+
return "move the line or text, or shorten the label"
|
|
204
|
+
if other is not None and hasattr(other, "ends"):
|
|
205
|
+
wires.append(other)
|
|
206
|
+
elif other is not None:
|
|
207
|
+
wires += [w for w in scene.lines if w.name == other.owner]
|
|
208
|
+
busy = crowded(scene, wires)
|
|
209
|
+
if busy and busy[0] >= 3:
|
|
210
|
+
n, el, side = busy
|
|
211
|
+
turn = "n" if side in "ew" else "e"
|
|
212
|
+
return (f"{n} lines on the {SIDE_NAMES[side]} side of {el}; make {el} "
|
|
213
|
+
f"{'taller' if side in 'ew' else 'wider'} or attach one of them to another side ({el}.{turn})")
|
|
214
|
+
ends = sorted({e for w in wires for e in w.ends})
|
|
215
|
+
return f"shorten the label, or give its line more room: move {' or '.join(ends)}"
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def between(box, own, lines, grid):
|
|
219
|
+
"""Another line that runs parallel beside the label `box` as close as its own line `own`."""
|
|
220
|
+
def dist(a, b):
|
|
221
|
+
h = horizontal(a, b)
|
|
222
|
+
lo, hi = (box[0], box[2]) if h else (box[1], box[3])
|
|
223
|
+
if shared(a, b, (lo, lo), (hi, hi), 0 if h else 1) <= 0:
|
|
224
|
+
return None
|
|
225
|
+
c, (b0, b1) = (a[1], (box[1], box[3])) if h else (a[0], (box[0], box[2]))
|
|
226
|
+
return h, (-1 if c <= b0 else 1 if c >= b1 else 0), max(b0 - c, c - b1, 0)
|
|
227
|
+
|
|
228
|
+
near = [d for a, b in own.segments() if (d := dist(a, b)) and d[1]]
|
|
229
|
+
if not near:
|
|
230
|
+
return None
|
|
231
|
+
h, side, d0 = min(near, key=lambda d: d[2])
|
|
232
|
+
for w in lines:
|
|
233
|
+
if w is own:
|
|
234
|
+
continue
|
|
235
|
+
for a, b in w.segments():
|
|
236
|
+
d = dist(a, b)
|
|
237
|
+
if d and d[0] == h and d[1] == -side and d[2] <= max(d0 + 4, 0) and d[2] < grid:
|
|
238
|
+
return w
|
|
239
|
+
return None
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def size(scene, theme, turn=None):
|
|
243
|
+
"""A diagram larger than its size setting. When it is only slightly larger, shorter labels or `turn`,
|
|
244
|
+
the fix that lays a left-to-right diagram out from top to bottom, come first in the fix."""
|
|
245
|
+
x0, y0, x1, y1 = scene.bounds()
|
|
246
|
+
w, h = x1 - x0 + 2 * theme.pad, y1 - y0 + 2 * theme.pad
|
|
247
|
+
mw, mh = theme.sizes[scene.size]
|
|
248
|
+
if w <= mw * TOLERANCE and h <= mh * TOLERANCE:
|
|
249
|
+
return []
|
|
250
|
+
fixes = []
|
|
251
|
+
if max(w / mw, h / mh) <= 1.15 and w / mw >= h / mh:
|
|
252
|
+
lines = {w.name for w in scene.lines}
|
|
253
|
+
longest = sorted((l for l in scene.labels if l.owner in lines), key=lambda l: l.box[0] - l.box[2])[:3]
|
|
254
|
+
fixes.append("shorten the longest labels (" + ", ".join(f"'{' '.join(l.lines)}'" for l in longest) + ")")
|
|
255
|
+
if turn and w / mw > h / mh:
|
|
256
|
+
fixes.append(turn)
|
|
257
|
+
bigger = sorted((k for k, (a, b) in theme.sizes.items() if a >= w and b >= h and k != scene.size),
|
|
258
|
+
key=lambda k: theme.sizes[k][0] * theme.sizes[k][1])
|
|
259
|
+
fixes += [f"write 'size {bigger[0]}'"] if bigger else []
|
|
260
|
+
fixes.append("split it into an overview and detail diagrams")
|
|
261
|
+
return [Finding("size", scene.size_line, f"diagram is {w:.0f} x {h:.0f} px, larger than size {scene.size} "
|
|
262
|
+
f"({mw} x {mh} px)", ", or ".join(fixes))]
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def frames(scene, theme):
|
|
266
|
+
out, inside = [], {f.id: set(f.members) for f in scene.frames}
|
|
267
|
+
for f in scene.frames: # members of nested groups belong to the outer frame too
|
|
268
|
+
stack = list(inside[f.id])
|
|
269
|
+
while stack:
|
|
270
|
+
m = stack.pop()
|
|
271
|
+
new = inside.get(m, set()) - inside[f.id]
|
|
272
|
+
inside[f.id] |= new
|
|
273
|
+
stack += new
|
|
274
|
+
u = Units(theme)
|
|
275
|
+
for f in scene.frames:
|
|
276
|
+
for s in scene.elements:
|
|
277
|
+
if s.id not in inside[f.id] and rect_ov(f.box, s.box, 1):
|
|
278
|
+
out.append(Finding("frame", s.line, f"{s.kind} {s.id} lies inside the frame of {f.kind} {f.id}, "
|
|
279
|
+
f"which it does not belong to", f"move {s.id} out of the frame, or into "
|
|
280
|
+
f"the group in the source"))
|
|
281
|
+
for o in scene.frames:
|
|
282
|
+
if o is f or o.id in inside[f.id] or f.id in inside[o.id] or not rect_ov(f.box, o.box, 1):
|
|
283
|
+
continue
|
|
284
|
+
if contains(f.box, o.box):
|
|
285
|
+
out.append(Finding("frame", o.line, f"frame of {o.kind} {o.id} lies inside {f.kind} {f.id}, "
|
|
286
|
+
f"which it does not belong to", f"move the members of {o.id} out of {f.id}"))
|
|
287
|
+
elif o.line > f.line and not contains(o.box, f.box):
|
|
288
|
+
out.append(Finding("frame", o.line, f"frames of {f.kind} {f.id} and {o.kind} {o.id} overlap",
|
|
289
|
+
"move the members of one of them apart"))
|
|
290
|
+
for w in scene.lines:
|
|
291
|
+
for a, b in w.segments():
|
|
292
|
+
if any((d := parallel_gap(a, b, c, e, theme.grid)) is not None and d < theme.min_space
|
|
293
|
+
for c, e in edges(f.box)):
|
|
294
|
+
out.append(Finding("border", w.line, f"{w.name} runs along the border of {f.kind} {f.id} "
|
|
295
|
+
f"near {u.pt(*a)}", f"move {' or '.join(w.ends)} so that the line keeps "
|
|
296
|
+
f"{u.len(theme.min_space)} units from the border"))
|
|
297
|
+
break
|
|
298
|
+
for l in scene.labels:
|
|
299
|
+
if l.owner != f.id and any(seg_hits(a, b, inset(l.box, 1)) for a, b in edges(f.box)):
|
|
300
|
+
out.append(Finding("border", l.line, f"label '{l.lines[0]}' crosses the border of {f.kind} "
|
|
301
|
+
f"{f.id}", "shorten the label, or move its line or element away from the border"))
|
|
302
|
+
return out
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def details(scene, base):
|
|
306
|
+
return [Finding("detail", s.line, f"detail diagram '{s.link}' of {s.id} does not exist (in {base})",
|
|
307
|
+
"fix the path; it is relative to this file")
|
|
308
|
+
for s in scene.elements if s.link and not (base / s.link).is_file()]
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def in_ellipse(outer, inner):
|
|
312
|
+
a, b = (outer[2] - outer[0]) / 2, (outer[3] - outer[1]) / 2
|
|
313
|
+
if a <= 0 or b <= 0:
|
|
314
|
+
return False
|
|
315
|
+
cx, cy = outer[0] + a, outer[1] + b
|
|
316
|
+
return all(((x - cx) / a) ** 2 + ((y - cy) / b) ** 2 <= 1.0001 for x in inner[::2] for y in inner[1::2])
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def contains(outer, inner):
|
|
320
|
+
return (outer[0] <= inner[0] + 0.01 and outer[1] <= inner[1] + 0.01
|
|
321
|
+
and inner[2] <= outer[2] + 0.01 and inner[3] <= outer[3] + 0.01)
|