Inkfish-Sepia 0.2.0__tar.gz
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.
- inkfish_sepia-0.2.0/PKG-INFO +75 -0
- inkfish_sepia-0.2.0/README.md +46 -0
- inkfish_sepia-0.2.0/pyproject.toml +42 -0
- inkfish_sepia-0.2.0/setup.cfg +4 -0
- inkfish_sepia-0.2.0/src/Inkfish_Sepia.egg-info/PKG-INFO +75 -0
- inkfish_sepia-0.2.0/src/Inkfish_Sepia.egg-info/SOURCES.txt +12 -0
- inkfish_sepia-0.2.0/src/Inkfish_Sepia.egg-info/dependency_links.txt +1 -0
- inkfish_sepia-0.2.0/src/Inkfish_Sepia.egg-info/requires.txt +7 -0
- inkfish_sepia-0.2.0/src/Inkfish_Sepia.egg-info/top_level.txt +1 -0
- inkfish_sepia-0.2.0/src/Sepia/__init__.py +19 -0
- inkfish_sepia-0.2.0/src/Sepia/core.py +511 -0
- inkfish_sepia-0.2.0/tests/test_core.py +243 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: Inkfish-Sepia
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Reusable Python flowchart model with SVG and PNG rendering
|
|
5
|
+
Author: iancullinane06
|
|
6
|
+
Project-URL: Homepage, https://inkfish-labs.github.io/
|
|
7
|
+
Project-URL: Documentation, https://inkfish-labs.github.io/
|
|
8
|
+
Keywords: flowchart,diagram,Inkfish,rendering,svg,png
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
Requires-Dist: Pillow>=10.0
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
26
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
27
|
+
Requires-Dist: python-dotenv>=1.0; extra == "dev"
|
|
28
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
29
|
+
|
|
30
|
+
# Inkfish Labs Sepia API
|
|
31
|
+
|
|
32
|
+
Reusable Python flowchart model with SVG and PNG rendering.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```powershell
|
|
37
|
+
python -m pip install
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
For development:
|
|
41
|
+
|
|
42
|
+
```powershell
|
|
43
|
+
python -m pip install -e .[dev]
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Python API
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from Sepia import Flowchart
|
|
50
|
+
|
|
51
|
+
chart = Flowchart()
|
|
52
|
+
chart.add_block("start", "start", "Start")
|
|
53
|
+
svg = chart.render_svg()
|
|
54
|
+
png = chart.render_png()
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Tests
|
|
58
|
+
|
|
59
|
+
```powershell
|
|
60
|
+
python -m pytest
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Build for PyPI
|
|
64
|
+
|
|
65
|
+
```powershell
|
|
66
|
+
python -m build
|
|
67
|
+
python -m twine check --strict dist\*
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Upload a release only after testing the wheel:
|
|
71
|
+
|
|
72
|
+
```powershell
|
|
73
|
+
python -m twine upload --repository testpypi dist\*
|
|
74
|
+
python -m twine upload dist\*
|
|
75
|
+
```
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Inkfish Labs Sepia API
|
|
2
|
+
|
|
3
|
+
Reusable Python flowchart model with SVG and PNG rendering.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```powershell
|
|
8
|
+
python -m pip install
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
For development:
|
|
12
|
+
|
|
13
|
+
```powershell
|
|
14
|
+
python -m pip install -e .[dev]
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Python API
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from Sepia import Flowchart
|
|
21
|
+
|
|
22
|
+
chart = Flowchart()
|
|
23
|
+
chart.add_block("start", "start", "Start")
|
|
24
|
+
svg = chart.render_svg()
|
|
25
|
+
png = chart.render_png()
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Tests
|
|
29
|
+
|
|
30
|
+
```powershell
|
|
31
|
+
python -m pytest
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Build for PyPI
|
|
35
|
+
|
|
36
|
+
```powershell
|
|
37
|
+
python -m build
|
|
38
|
+
python -m twine check --strict dist\*
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Upload a release only after testing the wheel:
|
|
42
|
+
|
|
43
|
+
```powershell
|
|
44
|
+
python -m twine upload --repository testpypi dist\*
|
|
45
|
+
python -m twine upload dist\*
|
|
46
|
+
```
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "Inkfish-Sepia"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Reusable Python flowchart model with SVG and PNG rendering"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
authors = [{ name = "iancullinane06" }]
|
|
12
|
+
keywords = ["flowchart", "diagram", "Inkfish", "rendering", "svg", "png"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
17
|
+
"Programming Language :: Python :: 3.9",
|
|
18
|
+
"Programming Language :: Python :: 3.10",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Programming Language :: Python :: 3.14",
|
|
23
|
+
"Programming Language :: Python :: 3.15",
|
|
24
|
+
"Topic :: Scientific/Engineering :: Visualization",
|
|
25
|
+
"Operating System :: OS Independent",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"Pillow>=10.0",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
dev = ["build>=1.2", "pytest>=8", "python-dotenv>=1.0", "twine>=5"]
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://inkfish-labs.github.io/"
|
|
36
|
+
Documentation = "https://inkfish-labs.github.io/"
|
|
37
|
+
|
|
38
|
+
[tool.setuptools.packages.find]
|
|
39
|
+
where = ["src"]
|
|
40
|
+
|
|
41
|
+
[tool.pytest.ini_options]
|
|
42
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: Inkfish-Sepia
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Reusable Python flowchart model with SVG and PNG rendering
|
|
5
|
+
Author: iancullinane06
|
|
6
|
+
Project-URL: Homepage, https://inkfish-labs.github.io/
|
|
7
|
+
Project-URL: Documentation, https://inkfish-labs.github.io/
|
|
8
|
+
Keywords: flowchart,diagram,Inkfish,rendering,svg,png
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
Requires-Dist: Pillow>=10.0
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
26
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
27
|
+
Requires-Dist: python-dotenv>=1.0; extra == "dev"
|
|
28
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
29
|
+
|
|
30
|
+
# Inkfish Labs Sepia API
|
|
31
|
+
|
|
32
|
+
Reusable Python flowchart model with SVG and PNG rendering.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```powershell
|
|
37
|
+
python -m pip install
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
For development:
|
|
41
|
+
|
|
42
|
+
```powershell
|
|
43
|
+
python -m pip install -e .[dev]
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Python API
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from Sepia import Flowchart
|
|
50
|
+
|
|
51
|
+
chart = Flowchart()
|
|
52
|
+
chart.add_block("start", "start", "Start")
|
|
53
|
+
svg = chart.render_svg()
|
|
54
|
+
png = chart.render_png()
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Tests
|
|
58
|
+
|
|
59
|
+
```powershell
|
|
60
|
+
python -m pytest
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Build for PyPI
|
|
64
|
+
|
|
65
|
+
```powershell
|
|
66
|
+
python -m build
|
|
67
|
+
python -m twine check --strict dist\*
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Upload a release only after testing the wheel:
|
|
71
|
+
|
|
72
|
+
```powershell
|
|
73
|
+
python -m twine upload --repository testpypi dist\*
|
|
74
|
+
python -m twine upload dist\*
|
|
75
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/Inkfish_Sepia.egg-info/PKG-INFO
|
|
4
|
+
src/Inkfish_Sepia.egg-info/SOURCES.txt
|
|
5
|
+
src/Inkfish_Sepia.egg-info/dependency_links.txt
|
|
6
|
+
src/Inkfish_Sepia.egg-info/requires.txt
|
|
7
|
+
src/Inkfish_Sepia.egg-info/top_level.txt
|
|
8
|
+
src/Sepia/__init__.py
|
|
9
|
+
src/Sepia/core.py
|
|
10
|
+
src/sepia/__init__.py
|
|
11
|
+
src/sepia/core.py
|
|
12
|
+
tests/test_core.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sepia
|
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
"""Create flowcharts from Python, or run this file to open the desktop editor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from collections import deque
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from io import BytesIO
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from xml.sax.saxutils import escape
|
|
12
|
+
|
|
13
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
DEFAULT_COLORS = {
|
|
17
|
+
"start": ("#b8e7dd", "#c6efc1"),
|
|
18
|
+
"end": ("#b8e7dd", "#c6efc1"),
|
|
19
|
+
"process": ("#d1ebfa", "#a9d8f6"),
|
|
20
|
+
"decision": ("#ffe2b6", "#ffd0a5"),
|
|
21
|
+
"input_output": ("#e4d7f8", "#d2c4f2"),
|
|
22
|
+
"document": ("#fff2bd", "#ffe4a3"),
|
|
23
|
+
"subprocess": ("#cce8f6", "#a8d7f0"),
|
|
24
|
+
"database": ("#f8dce9", "#edc5e0"),
|
|
25
|
+
"preparation": ("#ffdfc5", "#ffcaab"),
|
|
26
|
+
"connector": ("#c5ece6", "#b6e6d6"),
|
|
27
|
+
}
|
|
28
|
+
KINDS = tuple(DEFAULT_COLORS)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _validate_color(color: str) -> str:
|
|
32
|
+
if not isinstance(color, str) or len(color) != 7 or color[0] != "#":
|
|
33
|
+
raise ValueError("Colors must be in #RRGGBB format.")
|
|
34
|
+
try:
|
|
35
|
+
int(color[1:], 16)
|
|
36
|
+
except ValueError as exc:
|
|
37
|
+
raise ValueError("Colors must be in #RRGGBB format.") from exc
|
|
38
|
+
return color.lower()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class Block:
|
|
43
|
+
id: str
|
|
44
|
+
kind: str
|
|
45
|
+
text: str
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class Connection:
|
|
50
|
+
source: str
|
|
51
|
+
target: str
|
|
52
|
+
label: str = ""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class Flowchart:
|
|
57
|
+
blocks: list[Block] = field(default_factory=list)
|
|
58
|
+
connections: list[Connection] = field(default_factory=list)
|
|
59
|
+
colors: dict[str, tuple[str, str]] = field(
|
|
60
|
+
default_factory=lambda: DEFAULT_COLORS.copy()
|
|
61
|
+
)
|
|
62
|
+
title: str = ""
|
|
63
|
+
|
|
64
|
+
def add_block(self, id: str, kind: str, text: str) -> Block:
|
|
65
|
+
if not isinstance(id, str) or not id.strip():
|
|
66
|
+
raise ValueError("A block ID is required.")
|
|
67
|
+
if any(block.id == id for block in self.blocks):
|
|
68
|
+
raise ValueError(f"Block ID {id!r} already exists.")
|
|
69
|
+
if kind not in KINDS:
|
|
70
|
+
raise ValueError(f"Unknown block type: {kind!r}.")
|
|
71
|
+
if not isinstance(text, str) or not text.strip():
|
|
72
|
+
raise ValueError("Block text is required.")
|
|
73
|
+
block = Block(id, kind, text)
|
|
74
|
+
self.blocks.append(block)
|
|
75
|
+
return block
|
|
76
|
+
|
|
77
|
+
def connect(self, source: str, target: str, label: str = "") -> Connection:
|
|
78
|
+
ids = {block.id for block in self.blocks}
|
|
79
|
+
if source not in ids or target not in ids:
|
|
80
|
+
raise ValueError("Both connection endpoints must be existing block IDs.")
|
|
81
|
+
if not isinstance(label, str):
|
|
82
|
+
raise ValueError("The connection label must be text.")
|
|
83
|
+
edge = Connection(source, target, label)
|
|
84
|
+
self.connections.append(edge)
|
|
85
|
+
return edge
|
|
86
|
+
|
|
87
|
+
def set_colors(self, kind: str, top: str, bottom: str) -> None:
|
|
88
|
+
if kind not in KINDS:
|
|
89
|
+
raise ValueError(f"Unknown block type: {kind!r}.")
|
|
90
|
+
self.colors[kind] = (_validate_color(top), _validate_color(bottom))
|
|
91
|
+
|
|
92
|
+
def to_dict(self) -> dict:
|
|
93
|
+
return {
|
|
94
|
+
"version": 1,
|
|
95
|
+
"title": self.title,
|
|
96
|
+
"blocks": [vars(block).copy() for block in self.blocks],
|
|
97
|
+
"connections": [vars(edge).copy() for edge in self.connections],
|
|
98
|
+
"colors": {kind: list(colors) for kind, colors in self.colors.items()},
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def from_dict(cls, data: dict) -> Flowchart:
|
|
103
|
+
if not isinstance(data, dict) or data.get("version") != 1:
|
|
104
|
+
raise ValueError("Unsupported or invalid flowchart file.")
|
|
105
|
+
chart = cls()
|
|
106
|
+
try:
|
|
107
|
+
title = data.get("title", "")
|
|
108
|
+
if not isinstance(title, str):
|
|
109
|
+
raise ValueError("The chart title must be text.")
|
|
110
|
+
chart.title = title
|
|
111
|
+
for kind, colors in data.get("colors", {}).items():
|
|
112
|
+
if not isinstance(colors, (list, tuple)) or len(colors) != 2:
|
|
113
|
+
raise ValueError(f"Expected two colors for {kind!r}.")
|
|
114
|
+
chart.set_colors(kind, colors[0], colors[1])
|
|
115
|
+
for block in data["blocks"]:
|
|
116
|
+
chart.add_block(block["id"], block["kind"], block["text"])
|
|
117
|
+
for edge in data["connections"]:
|
|
118
|
+
chart.connect(edge["source"], edge["target"], edge.get("label", ""))
|
|
119
|
+
except (KeyError, TypeError, AttributeError) as exc:
|
|
120
|
+
raise ValueError(f"Invalid flowchart file: {exc}") from exc
|
|
121
|
+
return chart
|
|
122
|
+
|
|
123
|
+
def save(self, path: str | Path) -> None:
|
|
124
|
+
Path(path).write_text(
|
|
125
|
+
json.dumps(self.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
@classmethod
|
|
129
|
+
def load(cls, path: str | Path) -> Flowchart:
|
|
130
|
+
return cls.from_dict(json.loads(Path(path).read_text(encoding="utf-8")))
|
|
131
|
+
|
|
132
|
+
def export(self, path: str | Path) -> None:
|
|
133
|
+
path = Path(path)
|
|
134
|
+
if path.suffix.lower() not in (".svg", ".png"):
|
|
135
|
+
raise ValueError("Export filename must end in .svg or .png.")
|
|
136
|
+
renderer = Renderer(self)
|
|
137
|
+
if path.suffix.lower() == ".svg":
|
|
138
|
+
path.write_text(renderer.svg(), encoding="utf-8")
|
|
139
|
+
else:
|
|
140
|
+
renderer.image().save(path, format="PNG")
|
|
141
|
+
|
|
142
|
+
def render_svg(self) -> str:
|
|
143
|
+
return Renderer(self).svg()
|
|
144
|
+
|
|
145
|
+
def render_png(self) -> bytes:
|
|
146
|
+
output = BytesIO()
|
|
147
|
+
Renderer(self).image().save(output, format="PNG")
|
|
148
|
+
return output.getvalue()
|
|
149
|
+
|
|
150
|
+
def render_preview(self) -> Image.Image:
|
|
151
|
+
return Renderer(self).image()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _font(size: int) -> ImageFont.FreeTypeFont:
|
|
155
|
+
# Prefer widely available Unicode-capable system fonts.
|
|
156
|
+
candidates = [
|
|
157
|
+
Path(os.environ.get("WINDIR", "C:\\Windows")) / "Fonts" / "arial.ttf",
|
|
158
|
+
Path(os.environ.get("WINDIR", "C:\\Windows")) / "Fonts" / "seguisym.ttf",
|
|
159
|
+
Path("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"),
|
|
160
|
+
Path("/System/Library/Fonts/Supplemental/Arial Unicode.ttf"),
|
|
161
|
+
]
|
|
162
|
+
for candidate in candidates:
|
|
163
|
+
if candidate.is_file():
|
|
164
|
+
return ImageFont.truetype(str(candidate), size)
|
|
165
|
+
raise RuntimeError("No supported Unicode font found (Arial or DejaVu Sans).")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _wrap(text: str, font: ImageFont.FreeTypeFont, width: int) -> list[str]:
|
|
169
|
+
lines = []
|
|
170
|
+
for paragraph in text.split("\n"):
|
|
171
|
+
if not paragraph:
|
|
172
|
+
lines.append("")
|
|
173
|
+
continue
|
|
174
|
+
current = ""
|
|
175
|
+
for word in paragraph.split():
|
|
176
|
+
candidate = f"{current} {word}".strip()
|
|
177
|
+
if font.getlength(candidate) <= width:
|
|
178
|
+
current = candidate
|
|
179
|
+
continue
|
|
180
|
+
if current:
|
|
181
|
+
lines.append(current)
|
|
182
|
+
current = ""
|
|
183
|
+
for char in word:
|
|
184
|
+
if current and font.getlength(current + char) > width:
|
|
185
|
+
lines.append(current)
|
|
186
|
+
current = ""
|
|
187
|
+
current += char
|
|
188
|
+
lines.append(current)
|
|
189
|
+
return lines or [""]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class Renderer:
|
|
193
|
+
FONT_SIZE = 16
|
|
194
|
+
BLOCK_WIDTH = 240
|
|
195
|
+
GAP_X = 70
|
|
196
|
+
GAP_Y = 100
|
|
197
|
+
MARGIN = 45
|
|
198
|
+
TITLE_SIZE = 30
|
|
199
|
+
TITLE_LINE_HEIGHT = 42
|
|
200
|
+
CORNER_RADIUS = 16
|
|
201
|
+
|
|
202
|
+
def __init__(self, chart: Flowchart):
|
|
203
|
+
if not chart.blocks:
|
|
204
|
+
raise ValueError("Add at least one block before exporting or previewing.")
|
|
205
|
+
self.chart = chart
|
|
206
|
+
self.font = _font(self.FONT_SIZE)
|
|
207
|
+
self.label_font = _font(14)
|
|
208
|
+
if not isinstance(chart.title, str):
|
|
209
|
+
raise ValueError("The chart title must be text.")
|
|
210
|
+
self.title_font = _font(self.TITLE_SIZE)
|
|
211
|
+
self.title_lines = []
|
|
212
|
+
self.edge_lines = [_wrap(edge.label, self.label_font, 180)
|
|
213
|
+
for edge in chart.connections]
|
|
214
|
+
self.gap_y = max(self.GAP_Y, max(
|
|
215
|
+
(len(lines) * 18 + 60 for lines in self.edge_lines), default=0
|
|
216
|
+
))
|
|
217
|
+
self.lines = {}
|
|
218
|
+
self.sizes = {}
|
|
219
|
+
for block in chart.blocks:
|
|
220
|
+
width = 56 if block.kind == "connector" else self.BLOCK_WIDTH
|
|
221
|
+
text_width = 44 if block.kind == "connector" else 140 if block.kind == "decision" else 185
|
|
222
|
+
lines = _wrap(block.text, self.font, text_width)
|
|
223
|
+
height = 56 if block.kind == "connector" else max(80, len(lines) * 22 + 36)
|
|
224
|
+
if block.kind == "decision":
|
|
225
|
+
height = max(120, len(lines) * 40 + 48)
|
|
226
|
+
self.lines[block.id] = lines
|
|
227
|
+
self.sizes[block.id] = (width, height)
|
|
228
|
+
self.positions, self.width, self.height, self.levels, self.row_bounds = self._layout()
|
|
229
|
+
self.routes = self._routes()
|
|
230
|
+
|
|
231
|
+
def _layout(self):
|
|
232
|
+
ids = [block.id for block in self.chart.blocks]
|
|
233
|
+
outgoing = {id: [] for id in ids}
|
|
234
|
+
incoming = {id: 0 for id in ids}
|
|
235
|
+
for edge in self.chart.connections:
|
|
236
|
+
outgoing[edge.source].append(edge.target)
|
|
237
|
+
incoming[edge.target] += 1
|
|
238
|
+
# Remove depth-first back edges before assigning levels. This keeps
|
|
239
|
+
# joins below all of their forward predecessors, even in cyclic charts.
|
|
240
|
+
roots = [id for id in ids if incoming[id] == 0]
|
|
241
|
+
states = {id: 0 for id in ids}
|
|
242
|
+
forward = {id: [] for id in ids}
|
|
243
|
+
for root in roots + ids:
|
|
244
|
+
if states[root]:
|
|
245
|
+
continue
|
|
246
|
+
states[root] = 1
|
|
247
|
+
stack = [(root, iter(outgoing[root]))]
|
|
248
|
+
while stack:
|
|
249
|
+
node, targets = stack[-1]
|
|
250
|
+
target = next(targets, None)
|
|
251
|
+
if target is None:
|
|
252
|
+
states[node] = 2
|
|
253
|
+
stack.pop()
|
|
254
|
+
elif states[target] != 1:
|
|
255
|
+
forward[node].append(target)
|
|
256
|
+
if states[target] == 0:
|
|
257
|
+
states[target] = 1
|
|
258
|
+
stack.append((target, iter(outgoing[target])))
|
|
259
|
+
forward_incoming = {id: 0 for id in ids}
|
|
260
|
+
for targets in forward.values():
|
|
261
|
+
for target in targets:
|
|
262
|
+
forward_incoming[target] += 1
|
|
263
|
+
levels = {id: 0 for id in ids}
|
|
264
|
+
queue = deque(id for id in ids if forward_incoming[id] == 0)
|
|
265
|
+
while queue:
|
|
266
|
+
node = queue.popleft()
|
|
267
|
+
for target in forward[node]:
|
|
268
|
+
levels[target] = max(levels[target], levels[node] + 1)
|
|
269
|
+
forward_incoming[target] -= 1
|
|
270
|
+
if forward_incoming[target] == 0:
|
|
271
|
+
queue.append(target)
|
|
272
|
+
rows = {}
|
|
273
|
+
for id in ids:
|
|
274
|
+
rows.setdefault(levels[id], []).append(id)
|
|
275
|
+
content_width = max(
|
|
276
|
+
sum(self.sizes[id][0] for id in row) + (len(row) - 1) * self.GAP_X
|
|
277
|
+
for row in rows.values()
|
|
278
|
+
)
|
|
279
|
+
positions = {}
|
|
280
|
+
row_bounds = {}
|
|
281
|
+
y = self.MARGIN
|
|
282
|
+
if self.chart.title.strip():
|
|
283
|
+
self.title_lines = _wrap(self.chart.title, self.title_font, content_width)
|
|
284
|
+
y += len(self.title_lines) * self.TITLE_LINE_HEIGHT + 30
|
|
285
|
+
for level in sorted(rows):
|
|
286
|
+
row = rows[level]
|
|
287
|
+
row_width = (
|
|
288
|
+
sum(self.sizes[id][0] for id in row)
|
|
289
|
+
+ (len(row) - 1) * self.GAP_X
|
|
290
|
+
)
|
|
291
|
+
x = self.MARGIN + (content_width - row_width) / 2
|
|
292
|
+
row_height = max(self.sizes[id][1] for id in row)
|
|
293
|
+
row_bounds[level] = (y, y + row_height)
|
|
294
|
+
for id in row:
|
|
295
|
+
positions[id] = (x, y + (row_height - self.sizes[id][1]) / 2)
|
|
296
|
+
x += self.sizes[id][0] + self.GAP_X
|
|
297
|
+
y += row_height + self.gap_y
|
|
298
|
+
# Reserve a separate outside lane for each long or backward connection.
|
|
299
|
+
outside = len({
|
|
300
|
+
self._outside_key(index, edge, levels)
|
|
301
|
+
for index, edge in enumerate(self.chart.connections)
|
|
302
|
+
if levels[edge.target] != levels[edge.source] + 1
|
|
303
|
+
})
|
|
304
|
+
width = self.MARGIN * 2 + content_width + outside * 24 + (30 if outside else 0)
|
|
305
|
+
if any(edge.label for edge in self.chart.connections):
|
|
306
|
+
width += 100
|
|
307
|
+
bottom_padding = self.gap_y // 2 if outside else 0
|
|
308
|
+
return positions, int(width), int(y - self.gap_y + self.MARGIN + bottom_padding), levels, row_bounds
|
|
309
|
+
|
|
310
|
+
@staticmethod
|
|
311
|
+
def _outside_key(index, edge, levels):
|
|
312
|
+
if not edge.label and levels[edge.target] <= levels[edge.source]:
|
|
313
|
+
return ("return", edge.target, levels[edge.source])
|
|
314
|
+
return ("edge", index)
|
|
315
|
+
|
|
316
|
+
def _routes(self):
|
|
317
|
+
routes = []
|
|
318
|
+
outside_lanes = {}
|
|
319
|
+
content_right = max(
|
|
320
|
+
self.positions[id][0] + self.sizes[id][0] for id in self.positions
|
|
321
|
+
)
|
|
322
|
+
for index, (edge, lines) in enumerate(zip(self.chart.connections, self.edge_lines)):
|
|
323
|
+
sx, sy = self.positions[edge.source]
|
|
324
|
+
tx, ty = self.positions[edge.target]
|
|
325
|
+
sw, sh = self.sizes[edge.source]
|
|
326
|
+
tw, _ = self.sizes[edge.target]
|
|
327
|
+
start = (sx + sw / 2, sy + sh)
|
|
328
|
+
end = (tx + tw / 2, ty)
|
|
329
|
+
if self.levels[edge.target] == self.levels[edge.source] + 1:
|
|
330
|
+
mid = (self.row_bounds[self.levels[edge.source]][1]
|
|
331
|
+
+ self.row_bounds[self.levels[edge.target]][0]) / 2
|
|
332
|
+
points = [start, (start[0], mid), (end[0], mid), end]
|
|
333
|
+
label_at = ((start[0] + end[0]) / 2, mid - 7 - (len(lines) - 1) * 9)
|
|
334
|
+
if start[0] == end[0] and edge.label:
|
|
335
|
+
label_width = max(self.label_font.getlength(line) for line in lines)
|
|
336
|
+
label_at = (start[0] + label_width / 2 + 10, label_at[1])
|
|
337
|
+
else:
|
|
338
|
+
key = self._outside_key(index, edge, self.levels)
|
|
339
|
+
if key not in outside_lanes:
|
|
340
|
+
outside_lanes[key] = content_right + 30 + len(outside_lanes) * 24
|
|
341
|
+
lane = outside_lanes[key]
|
|
342
|
+
exit_y = self.row_bounds[self.levels[edge.source]][1] + self.gap_y / 2
|
|
343
|
+
entry_y = self.row_bounds[self.levels[edge.target]][0] - 25
|
|
344
|
+
source_has_right_neighbor = any(
|
|
345
|
+
self.levels[id] == self.levels[edge.source]
|
|
346
|
+
and self.positions[id][0] > sx
|
|
347
|
+
for id in self.positions
|
|
348
|
+
)
|
|
349
|
+
if (self.levels[edge.target] > self.levels[edge.source] + 1
|
|
350
|
+
and not source_has_right_neighbor):
|
|
351
|
+
source_block = next(block for block in self.chart.blocks
|
|
352
|
+
if block.id == edge.source)
|
|
353
|
+
side_x = sx + sw - (12.5 if source_block.kind == "input_output" else 0)
|
|
354
|
+
start = (side_x, sy + sh / 2)
|
|
355
|
+
points = [start, (lane, start[1]), (lane, entry_y),
|
|
356
|
+
(end[0], entry_y), end]
|
|
357
|
+
label_at = ((start[0] + lane) / 2,
|
|
358
|
+
start[1] - 7 - (len(lines) - 1) * 9)
|
|
359
|
+
else:
|
|
360
|
+
points = [start, (start[0], exit_y), (lane, exit_y),
|
|
361
|
+
(lane, entry_y), (end[0], entry_y), end]
|
|
362
|
+
label_at = ((start[0] + lane) / 2, exit_y - 7 - (len(lines) - 1) * 9)
|
|
363
|
+
routes.append((edge, points, label_at, "\n".join(lines)))
|
|
364
|
+
return routes
|
|
365
|
+
|
|
366
|
+
def _shape(self, block: Block):
|
|
367
|
+
x, y = self.positions[block.id]
|
|
368
|
+
w, h = self.sizes[block.id]
|
|
369
|
+
kind = block.kind
|
|
370
|
+
if kind in ("start", "end"):
|
|
371
|
+
return "capsule", (x, y, x + w, y + h)
|
|
372
|
+
if kind == "connector":
|
|
373
|
+
return "ellipse", (x, y, x + w, y + h)
|
|
374
|
+
if kind == "decision":
|
|
375
|
+
return "polygon", [(x + w / 2, y), (x + w, y + h / 2),
|
|
376
|
+
(x + w / 2, y + h), (x, y + h / 2)]
|
|
377
|
+
if kind == "input_output":
|
|
378
|
+
return "polygon", [(x + 25, y), (x + w, y), (x + w - 25, y + h), (x, y + h)]
|
|
379
|
+
if kind == "preparation":
|
|
380
|
+
return "polygon", [(x + 30, y), (x + w - 30, y), (x + w, y + h / 2),
|
|
381
|
+
(x + w - 30, y + h), (x + 30, y + h), (x, y + h / 2)]
|
|
382
|
+
if kind == "document":
|
|
383
|
+
return "polygon", [(x, y), (x + w, y), (x + w, y + h - 10),
|
|
384
|
+
(x + w * .75, y + h), (x + w * .5, y + h - 10),
|
|
385
|
+
(x + w * .25, y + h), (x, y + h - 10)]
|
|
386
|
+
if kind in ("process", "subprocess"):
|
|
387
|
+
return "rounded_rect", (x, y, x + w, y + h)
|
|
388
|
+
return "rect", (x, y, x + w, y + h)
|
|
389
|
+
|
|
390
|
+
def _radius(self, shape, block):
|
|
391
|
+
if shape == "capsule":
|
|
392
|
+
return min(self.sizes[block.id]) / 2
|
|
393
|
+
return self.CORNER_RADIUS
|
|
394
|
+
|
|
395
|
+
def image(self) -> Image.Image:
|
|
396
|
+
image = Image.new("RGBA", (self.width, self.height), (0, 0, 0, 0))
|
|
397
|
+
draw = ImageDraw.Draw(image)
|
|
398
|
+
for index, line in enumerate(self.title_lines):
|
|
399
|
+
draw.text((self.MARGIN, self.MARGIN + index * self.TITLE_LINE_HEIGHT),
|
|
400
|
+
line, fill="#17283c", font=self.title_font, anchor="la")
|
|
401
|
+
for edge, points, label, wrapped_label in self.routes:
|
|
402
|
+
draw.line(points, fill="#46546b", width=2, joint="curve")
|
|
403
|
+
ex, ey = points[-1]
|
|
404
|
+
draw.polygon([(ex, ey), (ex - 6, ey - 11), (ex + 6, ey - 11)], fill="#46546b")
|
|
405
|
+
if edge.label:
|
|
406
|
+
draw.multiline_text(label, wrapped_label, font=self.label_font,
|
|
407
|
+
fill="#273447", anchor="ms", align="center")
|
|
408
|
+
for block in self.chart.blocks:
|
|
409
|
+
shape, coords = self._shape(block)
|
|
410
|
+
pillow_shape = ("rounded_rectangle" if shape in ("capsule", "rounded_rect")
|
|
411
|
+
else "rectangle" if shape == "rect" else shape)
|
|
412
|
+
mask = Image.new("L", image.size, 0)
|
|
413
|
+
mask_draw = ImageDraw.Draw(mask)
|
|
414
|
+
options = {"radius": self._radius(shape, block)} if pillow_shape == "rounded_rectangle" else {}
|
|
415
|
+
getattr(mask_draw, pillow_shape)(coords, fill=255, **options)
|
|
416
|
+
x, y = self.positions[block.id]
|
|
417
|
+
w, h = self.sizes[block.id]
|
|
418
|
+
left, right = self.chart.colors[block.kind]
|
|
419
|
+
a = tuple(bytes.fromhex(left[1:]))
|
|
420
|
+
b = tuple(bytes.fromhex(right[1:]))
|
|
421
|
+
gradient = Image.new("RGBA", image.size)
|
|
422
|
+
gd = ImageDraw.Draw(gradient)
|
|
423
|
+
for step in range(int(w) + 1):
|
|
424
|
+
t = step / w
|
|
425
|
+
color = tuple(round(a[i] * (1 - t) + b[i] * t) for i in range(3)) + (255,)
|
|
426
|
+
gd.line((x + step, y, x + step, y + h), fill=color)
|
|
427
|
+
image.paste(gradient, (0, 0), mask)
|
|
428
|
+
draw = ImageDraw.Draw(image)
|
|
429
|
+
self._image_details(draw, block)
|
|
430
|
+
lines = self.lines[block.id]
|
|
431
|
+
first_y = y + h / 2 - (len(lines) - 1) * 11
|
|
432
|
+
for index, line in enumerate(lines):
|
|
433
|
+
draw.text((x + w / 2, first_y + index * 22), line,
|
|
434
|
+
fill="#17283c", font=self.font, anchor="mm")
|
|
435
|
+
return image
|
|
436
|
+
|
|
437
|
+
def _image_details(self, draw, block):
|
|
438
|
+
x, y = self.positions[block.id]
|
|
439
|
+
w, h = self.sizes[block.id]
|
|
440
|
+
if block.kind == "subprocess":
|
|
441
|
+
for offset in (15, w - 15):
|
|
442
|
+
draw.line((x + offset, y, x + offset, y + h), fill="#60768b", width=2)
|
|
443
|
+
elif block.kind == "database":
|
|
444
|
+
draw.arc((x, y - 10, x + w, y + 10), 0, 180, fill="#60768b", width=2)
|
|
445
|
+
draw.arc((x, y + h - 20, x + w, y + h), 0, 180, fill="#60768b", width=2)
|
|
446
|
+
|
|
447
|
+
def svg(self) -> str:
|
|
448
|
+
parts = [
|
|
449
|
+
f'<svg xmlns="http://www.w3.org/2000/svg" width="{self.width}" height="{self.height}" '
|
|
450
|
+
f'viewBox="0 0 {self.width} {self.height}">',
|
|
451
|
+
"<defs>",
|
|
452
|
+
]
|
|
453
|
+
for index, block in enumerate(self.chart.blocks):
|
|
454
|
+
left, right = self.chart.colors[block.kind]
|
|
455
|
+
parts.append(
|
|
456
|
+
f'<linearGradient id="g{index}" x1="0%" y1="0%" x2="100%" y2="0%">'
|
|
457
|
+
f'<stop offset="0%" stop-color="{left}"/>'
|
|
458
|
+
f'<stop offset="100%" stop-color="{right}"/></linearGradient>'
|
|
459
|
+
)
|
|
460
|
+
parts.append("</defs>")
|
|
461
|
+
ascent, _ = self.title_font.getmetrics()
|
|
462
|
+
for index, line in enumerate(self.title_lines):
|
|
463
|
+
parts.append(
|
|
464
|
+
f'<text x="{self.MARGIN}" y="{self.MARGIN + ascent + index * self.TITLE_LINE_HEIGHT}" '
|
|
465
|
+
f'fill="#17283c" font-family="Arial, DejaVu Sans, sans-serif" '
|
|
466
|
+
f'font-size="{self.TITLE_SIZE}">{escape(line)}</text>'
|
|
467
|
+
)
|
|
468
|
+
for edge, points, label, wrapped_label in self.routes:
|
|
469
|
+
path = " ".join(f"{x:.1f},{y:.1f}" for x, y in points)
|
|
470
|
+
parts.append(f'<polyline points="{path}" fill="none" stroke="#46546b" stroke-width="2"/>')
|
|
471
|
+
ex, ey = points[-1]
|
|
472
|
+
parts.append(f'<polygon points="{ex},{ey} {ex-6},{ey-11} {ex+6},{ey-11}" fill="#46546b"/>')
|
|
473
|
+
if edge.label:
|
|
474
|
+
parts.append(self._svg_text(label[0], label[1], wrapped_label, 14))
|
|
475
|
+
for index, block in enumerate(self.chart.blocks):
|
|
476
|
+
shape, coords = self._shape(block)
|
|
477
|
+
style = f'fill="url(#g{index})"'
|
|
478
|
+
x, y = self.positions[block.id]
|
|
479
|
+
w, h = self.sizes[block.id]
|
|
480
|
+
if shape == "polygon":
|
|
481
|
+
points = " ".join(f"{px},{py}" for px, py in coords)
|
|
482
|
+
parts.append(f'<polygon points="{points}" {style}/>')
|
|
483
|
+
elif shape == "ellipse":
|
|
484
|
+
parts.append(f'<ellipse cx="{x+w/2}" cy="{y+h/2}" rx="{w/2}" ry="{h/2}" {style}/>')
|
|
485
|
+
else:
|
|
486
|
+
radius = self._radius(shape, block) if shape in ("capsule", "rounded_rect") else 0
|
|
487
|
+
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="{radius}" {style}/>')
|
|
488
|
+
if block.kind == "subprocess":
|
|
489
|
+
for offset in (15, w - 15):
|
|
490
|
+
parts.append(f'<line x1="{x+offset}" y1="{y}" x2="{x+offset}" y2="{y+h}" stroke="#60768b" stroke-width="2"/>')
|
|
491
|
+
elif block.kind == "database":
|
|
492
|
+
parts.append(f'<path d="M {x} {y} Q {x+w/2} {y+20} {x+w} {y} M {x} {y+h-10} Q {x+w/2} {y+h+10} {x+w} {y+h-10}" fill="none" stroke="#60768b" stroke-width="2"/>')
|
|
493
|
+
first_y = y + h / 2 - (len(self.lines[block.id]) - 1) * 11 + 5
|
|
494
|
+
for line_index, line in enumerate(self.lines[block.id]):
|
|
495
|
+
parts.append(self._svg_text(x + w / 2, first_y + line_index * 22, line, 16))
|
|
496
|
+
parts.append("</svg>")
|
|
497
|
+
return "\n".join(parts)
|
|
498
|
+
|
|
499
|
+
@staticmethod
|
|
500
|
+
def _svg_text(x, y, text, size):
|
|
501
|
+
# Preserve multiline edge labels without interpreting them as markup.
|
|
502
|
+
lines = text.split("\n")
|
|
503
|
+
spans = "".join(
|
|
504
|
+
f'<tspan x="{x}" dy="{0 if i == 0 else size + 3}">{escape(line)}</tspan>'
|
|
505
|
+
for i, line in enumerate(lines)
|
|
506
|
+
)
|
|
507
|
+
return (f'<text x="{x}" y="{y}" text-anchor="middle" fill="#17283c" '
|
|
508
|
+
f'font-family="Arial, DejaVu Sans, sans-serif" font-size="{size}">{spans}</text>')
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
_Renderer = Renderer
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import tempfile
|
|
3
|
+
import unittest
|
|
4
|
+
import xml.etree.ElementTree as ET
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from PIL import Image
|
|
8
|
+
|
|
9
|
+
from sepia import Flowchart, KINDS, Renderer as _Renderer
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class FlowchartTests(unittest.TestCase):
|
|
13
|
+
def chart(self):
|
|
14
|
+
chart = Flowchart()
|
|
15
|
+
chart.add_block("start", "start", "Start")
|
|
16
|
+
chart.add_block("decision", "decision", "Is α ≤ 5?")
|
|
17
|
+
chart.add_block("process", "process", "x² = ∑ n\nSecond paragraph")
|
|
18
|
+
chart.add_block("end", "end", "End")
|
|
19
|
+
chart.connect("start", "decision")
|
|
20
|
+
chart.connect("decision", "process", "Yes & continue")
|
|
21
|
+
chart.connect("decision", "end", "No < 0")
|
|
22
|
+
chart.connect("process", "decision", "Repeat")
|
|
23
|
+
chart.connect("process", "end")
|
|
24
|
+
return chart
|
|
25
|
+
|
|
26
|
+
def test_round_trip(self):
|
|
27
|
+
chart = self.chart()
|
|
28
|
+
chart.title = "Calculation α & β"
|
|
29
|
+
chart.set_colors("process", "#aabbcc", "#ddeeff")
|
|
30
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
31
|
+
path = Path(directory) / "chart.json"
|
|
32
|
+
chart.save(path)
|
|
33
|
+
self.assertEqual(Flowchart.load(path).to_dict(), chart.to_dict())
|
|
34
|
+
self.assertIn("α", path.read_text(encoding="utf-8"))
|
|
35
|
+
|
|
36
|
+
def test_old_projects_and_invalid_titles(self):
|
|
37
|
+
project = self.chart().to_dict()
|
|
38
|
+
del project["title"]
|
|
39
|
+
self.assertEqual(Flowchart.from_dict(project).title, "")
|
|
40
|
+
project["title"] = 42
|
|
41
|
+
with self.assertRaisesRegex(ValueError, "title"):
|
|
42
|
+
Flowchart.from_dict(project)
|
|
43
|
+
|
|
44
|
+
def test_title_in_svg_png_and_layout(self):
|
|
45
|
+
chart = self.chart()
|
|
46
|
+
untitled = _Renderer(chart)
|
|
47
|
+
chart.title = "A long overview of α ≤ β & other calculation results"
|
|
48
|
+
renderer = _Renderer(chart)
|
|
49
|
+
self.assertGreater(len(renderer.title_lines), 1)
|
|
50
|
+
self.assertGreater(renderer.row_bounds[0][0], untitled.row_bounds[0][0])
|
|
51
|
+
self.assertTrue(all(renderer.title_font.getlength(line) <= 550
|
|
52
|
+
for line in renderer.title_lines))
|
|
53
|
+
svg = ET.fromstring(renderer.svg())
|
|
54
|
+
self.assertIn("α ≤ β &", "".join(svg.itertext()))
|
|
55
|
+
image = renderer.image()
|
|
56
|
+
title_area = image.getchannel("A").crop(
|
|
57
|
+
(0, 0, image.width, int(renderer.row_bounds[0][0] - 25))
|
|
58
|
+
)
|
|
59
|
+
self.assertIsNotNone(title_area.getbbox())
|
|
60
|
+
self.assertEqual(image.getpixel((0, 0))[3], 0)
|
|
61
|
+
|
|
62
|
+
def test_rounded_shapes_and_horizontal_gradient_match_exports(self):
|
|
63
|
+
chart = Flowchart()
|
|
64
|
+
for kind in ("start", "process", "end"):
|
|
65
|
+
chart.add_block(kind, kind, kind.title())
|
|
66
|
+
chart.connect("start", "process")
|
|
67
|
+
chart.connect("process", "end")
|
|
68
|
+
chart.set_colors("process", "#112233", "#aabbcc")
|
|
69
|
+
renderer = _Renderer(chart)
|
|
70
|
+
svg = ET.fromstring(renderer.svg())
|
|
71
|
+
ns = "{http://www.w3.org/2000/svg}"
|
|
72
|
+
rects = svg.findall(f"{ns}rect")
|
|
73
|
+
self.assertEqual([float(rect.get("rx")) for rect in rects], [40, 16, 40])
|
|
74
|
+
gradient = svg.find(f"{ns}defs/{ns}linearGradient[@id='g1']")
|
|
75
|
+
self.assertEqual((gradient.get("x2"), gradient.get("y2")), ("100%", "0%"))
|
|
76
|
+
self.assertEqual([stop.get("stop-color") for stop in gradient], ["#112233", "#aabbcc"])
|
|
77
|
+
image = renderer.image()
|
|
78
|
+
x, y = renderer.positions["process"]
|
|
79
|
+
x, y = int(x), int(y)
|
|
80
|
+
self.assertEqual(image.getpixel((x, y))[3], 0)
|
|
81
|
+
left = image.getpixel((x + 20, y + 20))
|
|
82
|
+
right = image.getpixel((x + 220, y + 20))
|
|
83
|
+
self.assertLess(left[0], right[0])
|
|
84
|
+
self.assertEqual(left, image.getpixel((x + 20, y + 60)))
|
|
85
|
+
x, y = map(int, renderer.positions["start"])
|
|
86
|
+
self.assertEqual(image.getpixel((x, y))[3], 0)
|
|
87
|
+
self.assertGreater(image.getpixel((x + 80, y + 1))[3], 0)
|
|
88
|
+
|
|
89
|
+
def test_exports_are_transparent_and_svg_is_valid_xml(self):
|
|
90
|
+
chart = self.chart()
|
|
91
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
92
|
+
svg = Path(directory) / "chart.svg"
|
|
93
|
+
png = Path(directory) / "chart.png"
|
|
94
|
+
chart.export(svg)
|
|
95
|
+
chart.export(png)
|
|
96
|
+
root = ET.parse(svg).getroot()
|
|
97
|
+
text = "".join(root.itertext())
|
|
98
|
+
self.assertIn("α ≤ 5", text)
|
|
99
|
+
self.assertIn("Yes & continue", text)
|
|
100
|
+
self.assertIn("No < 0", text)
|
|
101
|
+
self.assertEqual(len(root.findall(".//{http://www.w3.org/2000/svg}polyline")), 5)
|
|
102
|
+
with Image.open(png) as image:
|
|
103
|
+
self.assertEqual(image.mode, "RGBA")
|
|
104
|
+
self.assertEqual(image.getpixel((0, 0))[3], 0)
|
|
105
|
+
self.assertGreater(image.getchannel("A").getextrema()[1], 0)
|
|
106
|
+
|
|
107
|
+
def test_all_block_types_render(self):
|
|
108
|
+
chart = Flowchart()
|
|
109
|
+
for kind in KINDS:
|
|
110
|
+
chart.add_block(kind, kind, f"{kind}\nα ≤ 5")
|
|
111
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
112
|
+
chart.export(Path(directory) / "all.png")
|
|
113
|
+
chart.export(Path(directory) / "all.svg")
|
|
114
|
+
ET.parse(Path(directory) / "all.svg")
|
|
115
|
+
|
|
116
|
+
def test_invalid_inputs(self):
|
|
117
|
+
chart = Flowchart()
|
|
118
|
+
with self.assertRaises(ValueError):
|
|
119
|
+
chart.export("unused.svg")
|
|
120
|
+
chart.add_block("x", "process", "Text")
|
|
121
|
+
for action in (
|
|
122
|
+
lambda: chart.add_block("x", "process", "duplicate"),
|
|
123
|
+
lambda: chart.add_block("y", "unknown", "text"),
|
|
124
|
+
lambda: chart.add_block("y", "process", " "),
|
|
125
|
+
lambda: chart.connect("x", "missing"),
|
|
126
|
+
lambda: chart.set_colors("process", "#invalid", "#ffffff"),
|
|
127
|
+
lambda: chart.export("unused.jpg"),
|
|
128
|
+
lambda: Flowchart.from_dict({"version": 1, "blocks": [], "connections": [], "colors": {"process": ["#fff"]}}),
|
|
129
|
+
):
|
|
130
|
+
with self.assertRaises(ValueError):
|
|
131
|
+
action()
|
|
132
|
+
|
|
133
|
+
def test_routes_clear_rows_for_unequal_block_heights(self):
|
|
134
|
+
chart = Flowchart()
|
|
135
|
+
chart.add_block("a", "process", "Short")
|
|
136
|
+
chart.add_block("b", "process", "Tall\n" * 10)
|
|
137
|
+
chart.add_block("c", "process", "Next")
|
|
138
|
+
chart.connect("a", "c")
|
|
139
|
+
chart.connect("c", "a")
|
|
140
|
+
renderer = _Renderer(chart)
|
|
141
|
+
self.assertEqual(renderer.levels["a"], renderer.levels["b"])
|
|
142
|
+
forward = renderer.routes[0][1]
|
|
143
|
+
self.assertGreater(forward[1][1], renderer.row_bounds[0][1])
|
|
144
|
+
backward = renderer.routes[1][1]
|
|
145
|
+
self.assertLess(backward[-2][1], renderer.row_bounds[0][0])
|
|
146
|
+
|
|
147
|
+
def test_long_connection_labels_wrap_without_clipping(self):
|
|
148
|
+
chart = Flowchart()
|
|
149
|
+
chart.add_block("a", "start", "Start")
|
|
150
|
+
chart.add_block("b", "end", "End")
|
|
151
|
+
chart.connect("a", "b", "A long label " * 20)
|
|
152
|
+
renderer = _Renderer(chart)
|
|
153
|
+
lines = renderer.routes[0][3].split("\n")
|
|
154
|
+
self.assertGreater(len(lines), 1)
|
|
155
|
+
self.assertTrue(all(renderer.label_font.getlength(line) <= 180 for line in lines))
|
|
156
|
+
self.assertGreaterEqual(renderer.gap_y, len(lines) * 18 + 60)
|
|
157
|
+
renderer.image()
|
|
158
|
+
ET.fromstring(renderer.svg())
|
|
159
|
+
|
|
160
|
+
def test_simulation_joins_and_return_routes(self):
|
|
161
|
+
chart = Flowchart()
|
|
162
|
+
for id, kind in (
|
|
163
|
+
("start", "start"), ("diagnostics", "process"),
|
|
164
|
+
("record_check", "decision"), ("record", "input_output"),
|
|
165
|
+
("more_steps", "decision"), ("derivatives", "process"),
|
|
166
|
+
("end", "end"), ("method", "decision"),
|
|
167
|
+
("euler", "process"), ("rk2", "process"), ("rk4", "process"),
|
|
168
|
+
):
|
|
169
|
+
chart.add_block(id, kind, id)
|
|
170
|
+
for source, target, label in (
|
|
171
|
+
("start", "diagnostics", ""), ("diagnostics", "record_check", ""),
|
|
172
|
+
("record_check", "record", "Yes"), ("record_check", "more_steps", "No"),
|
|
173
|
+
("record", "more_steps", ""), ("more_steps", "derivatives", "Yes"),
|
|
174
|
+
("more_steps", "end", "No"), ("derivatives", "method", ""),
|
|
175
|
+
("method", "euler", "Euler"), ("method", "rk2", "RK2"),
|
|
176
|
+
("method", "rk4", "RK4"), ("euler", "diagnostics", ""),
|
|
177
|
+
("rk2", "diagnostics", ""), ("rk4", "diagnostics", ""),
|
|
178
|
+
):
|
|
179
|
+
chart.connect(source, target, label)
|
|
180
|
+
renderer = _Renderer(chart)
|
|
181
|
+
self.assertLess(renderer.levels["record_check"], renderer.levels["record"])
|
|
182
|
+
self.assertLess(renderer.levels["record"], renderer.levels["more_steps"])
|
|
183
|
+
self.assertLess(renderer.levels["more_steps"], renderer.levels["derivatives"])
|
|
184
|
+
by_edge = {(edge.source, edge.target): (points, label)
|
|
185
|
+
for edge, points, label, _ in renderer.routes}
|
|
186
|
+
bypass, _ = by_edge["record_check", "more_steps"]
|
|
187
|
+
decision_x, decision_y = renderer.positions["record_check"]
|
|
188
|
+
decision_w, decision_h = renderer.sizes["record_check"]
|
|
189
|
+
self.assertEqual(bypass[0], (decision_x + decision_w, decision_y + decision_h / 2))
|
|
190
|
+
record_x, record_y = renderer.positions["record"]
|
|
191
|
+
record_w, record_h = renderer.sizes["record"]
|
|
192
|
+
for start, end in zip(bypass, bypass[1:]):
|
|
193
|
+
if start[0] == end[0]:
|
|
194
|
+
self.assertFalse(record_x < start[0] < record_x + record_w and
|
|
195
|
+
min(start[1], end[1]) < record_y + record_h and
|
|
196
|
+
max(start[1], end[1]) > record_y)
|
|
197
|
+
else:
|
|
198
|
+
self.assertFalse(record_y < start[1] < record_y + record_h and
|
|
199
|
+
min(start[0], end[0]) < record_x + record_w and
|
|
200
|
+
max(start[0], end[0]) > record_x)
|
|
201
|
+
returns = [by_edge[source, "diagnostics"][0] for source in ("euler", "rk2", "rk4")]
|
|
202
|
+
self.assertEqual(len({points[2][0] for points in returns}), 1)
|
|
203
|
+
points, label = by_edge["method", "rk2"]
|
|
204
|
+
self.assertGreater(label[0], points[0][0])
|
|
205
|
+
|
|
206
|
+
def test_long_forward_edge_from_input_output_meets_slanted_side(self):
|
|
207
|
+
chart = Flowchart()
|
|
208
|
+
chart.add_block("a", "input_output", "Input")
|
|
209
|
+
chart.add_block("b", "process", "Middle")
|
|
210
|
+
chart.add_block("c", "process", "End")
|
|
211
|
+
chart.connect("a", "b")
|
|
212
|
+
chart.connect("b", "c")
|
|
213
|
+
chart.connect("a", "c", "Skip")
|
|
214
|
+
renderer = _Renderer(chart)
|
|
215
|
+
points = renderer.routes[2][1]
|
|
216
|
+
x, y = renderer.positions["a"]
|
|
217
|
+
width, height = renderer.sizes["a"]
|
|
218
|
+
self.assertEqual(points[0], (x + width - 12.5, y + height / 2))
|
|
219
|
+
|
|
220
|
+
def test_connectors_are_compact_join_nodes(self):
|
|
221
|
+
chart = Flowchart()
|
|
222
|
+
chart.add_block("a", "process", "Left")
|
|
223
|
+
chart.add_block("b", "process", "Right")
|
|
224
|
+
chart.add_block("join", "connector", "1")
|
|
225
|
+
chart.add_block("end", "end", "End")
|
|
226
|
+
chart.connect("a", "join")
|
|
227
|
+
chart.connect("b", "join")
|
|
228
|
+
chart.connect("join", "end")
|
|
229
|
+
renderer = _Renderer(chart)
|
|
230
|
+
self.assertEqual(renderer.sizes["join"], (56, 56))
|
|
231
|
+
self.assertLess(renderer.sizes["join"][0], renderer.BLOCK_WIDTH)
|
|
232
|
+
self.assertGreater(renderer.levels["join"], renderer.levels["a"])
|
|
233
|
+
self.assertGreater(renderer.levels["join"], renderer.levels["b"])
|
|
234
|
+
|
|
235
|
+
def test_invalid_project_does_not_silently_load(self):
|
|
236
|
+
with self.assertRaises(ValueError):
|
|
237
|
+
Flowchart.from_dict({"version": 1, "blocks": [{"id": "x"}], "connections": []})
|
|
238
|
+
with self.assertRaises(json.JSONDecodeError):
|
|
239
|
+
json.loads("{")
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
if __name__ == "__main__":
|
|
243
|
+
unittest.main()
|