| 1 |
|
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import math as Math |
| 5 |
import sys |
| 6 |
|
| 7 |
from typing import TYPE_CHECKING |
| 8 |
|
| 9 |
if TYPE_CHECKING: |
| 10 |
from typing import ( |
| 11 |
Any, |
| 12 |
Callable, |
| 13 |
Dict, |
| 14 |
Generator, |
| 15 |
List, |
| 16 |
Optional as Opt, |
| 17 |
Sequence as Seq, |
| 18 |
Tuple, |
| 19 |
Type, |
| 20 |
TypeVar, |
| 21 |
Union, |
| 22 |
) |
| 23 |
|
| 24 |
T = TypeVar("T") |
| 25 |
Node = Union[str, DiagramItem] |
| 26 |
WriterF = Callable[[str], Any] |
| 27 |
WalkerF = Callable[[DiagramItem], Any] |
| 28 |
AttrsT = Dict[str, Any] |
| 29 |
|
| 30 |
|
| 31 |
DEBUG = False |
| 32 |
VS = 8 |
| 33 |
AR = 10 |
| 34 |
DIAGRAM_CLASS = "railroad-diagram" |
| 35 |
STROKE_ODD_PIXEL_LENGTH = ( |
| 36 |
True |
| 37 |
) |
| 38 |
INTERNAL_ALIGNMENT = ( |
| 39 |
"center" |
| 40 |
) |
| 41 |
CHAR_WIDTH = 8.5 |
| 42 |
COMMENT_CHAR_WIDTH = 7 |
| 43 |
ESCAPE_HTML = True |
| 44 |
|
| 45 |
|
| 46 |
def escapeAttr(val: Union[str, float]) -> str: |
| 47 |
if isinstance(val, str): |
| 48 |
return val.replace("&", "&").replace("'", "'").replace('"', """) |
| 49 |
return f"{val:g}" |
| 50 |
|
| 51 |
|
| 52 |
def escapeHtml(val: str) -> str: |
| 53 |
return escapeAttr(val).replace("<", "<") |
| 54 |
|
| 55 |
|
| 56 |
def determineGaps(outer: float, inner: float) -> Tuple[float, float]: |
| 57 |
diff = outer - inner |
| 58 |
if INTERNAL_ALIGNMENT == "left": |
| 59 |
return 0, diff |
| 60 |
elif INTERNAL_ALIGNMENT == "right": |
| 61 |
return diff, 0 |
| 62 |
else: |
| 63 |
return diff / 2, diff / 2 |
| 64 |
|
| 65 |
|
| 66 |
def doubleenumerate(seq: Seq[T]) -> Generator[Tuple[int, int, T], None, None]: |
| 67 |
length = len(list(seq)) |
| 68 |
for i, item in enumerate(seq): |
| 69 |
yield i, i - length, item |
| 70 |
|
| 71 |
|
| 72 |
def addDebug(el: DiagramItem) -> None: |
| 73 |
if not DEBUG: |
| 74 |
return |
| 75 |
el.attrs["data-x"] = "{0} w:{1} h:{2}/{3}/{4}".format( |
| 76 |
type(el).__name__, el.width, el.up, el.height, el.down |
| 77 |
) |
| 78 |
|
| 79 |
|
| 80 |
class DiagramItem: |
| 81 |
def __init__(self, name: str, attrs: Opt[AttrsT] = None, text: Opt[Node] = None): |
| 82 |
self.name = name |
| 83 |
|
| 84 |
self.up: float = 0 |
| 85 |
|
| 86 |
self.height: float = 0 |
| 87 |
|
| 88 |
self.down: float = 0 |
| 89 |
|
| 90 |
self.width: float = 0 |
| 91 |
|
| 92 |
self.needsSpace = False |
| 93 |
|
| 94 |
|
| 95 |
self.attrs: AttrsT = attrs or {} |
| 96 |
|
| 97 |
|
| 98 |
self.children: List[Union[Node, Path, Style]] = [text] if text else [] |
| 99 |
|
| 100 |
def format(self, x: float, y: float, width: float) -> DiagramItem: |
| 101 |
raise NotImplementedError |
| 102 |
|
| 103 |
def textDiagram() -> TextDiagram: |
| 104 |
raise NotImplementedError("Virtual") |
| 105 |
|
| 106 |
def addTo(self, parent: DiagramItem) -> DiagramItem: |
| 107 |
parent.children.append(self) |
| 108 |
return self |
| 109 |
|
| 110 |
def writeSvg(self, write: WriterF) -> None: |
| 111 |
write("<{0}".format(self.name)) |
| 112 |
for name, value in sorted(self.attrs.items()): |
| 113 |
write(' {0}="{1}"'.format(name, escapeAttr(value))) |
| 114 |
write(">") |
| 115 |
if self.name in ["g", "svg"]: |
| 116 |
write("\n") |
| 117 |
for child in self.children: |
| 118 |
if isinstance(child, (DiagramItem, Path, Style)): |
| 119 |
child.writeSvg(write) |
| 120 |
else: |
| 121 |
write(escapeHtml(child)) |
| 122 |
write("</{0}>".format(self.name)) |
| 123 |
|
| 124 |
def walk(self, cb: WalkerF) -> None: |
| 125 |
cb(self) |
| 126 |
|
| 127 |
def __repr__(self) -> str: |
| 128 |
return f"DiagramItem({self.name}, {self.attrs}, {self.children})" |
| 129 |
|
| 130 |
|
| 131 |
class DiagramMultiContainer(DiagramItem): |
| 132 |
def __init__( |
| 133 |
self, |
| 134 |
name: str, |
| 135 |
items: Seq[Node], |
| 136 |
attrs: Opt[Dict[str, str]] = None, |
| 137 |
text: Opt[str] = None, |
| 138 |
): |
| 139 |
DiagramItem.__init__(self, name, attrs, text) |
| 140 |
self.items: List[DiagramItem] = [wrapString(item) for item in items] |
| 141 |
|
| 142 |
def format(self, x: float, y: float, width: float) -> DiagramItem: |
| 143 |
raise NotImplementedError |
| 144 |
|
| 145 |
def walk(self, cb: WalkerF) -> None: |
| 146 |
cb(self) |
| 147 |
for item in self.items: |
| 148 |
item.walk(cb) |
| 149 |
|
| 150 |
def __repr__(self) -> str: |
| 151 |
return f"DiagramMultiContainer({self.name}, {self.items}. {self.attrs}, {self.children})" |
| 152 |
|
| 153 |
|
| 154 |
class Path: |
| 155 |
def __init__(self, x: float, y: float): |
| 156 |
self.x = x |
| 157 |
self.y = y |
| 158 |
self.attrs = {"d": f"M{x} {y}"} |
| 159 |
|
| 160 |
def m(self, x: float, y: float) -> Path: |
| 161 |
self.attrs["d"] += f"m{x} {y}" |
| 162 |
return self |
| 163 |
|
| 164 |
def l(self, x: float, y: float) -> Path: |
| 165 |
self.attrs["d"] += f"l{x} {y}" |
| 166 |
return self |
| 167 |
|
| 168 |
def h(self, val: float) -> Path: |
| 169 |
self.attrs["d"] += f"h{val}" |
| 170 |
return self |
| 171 |
|
| 172 |
def right(self, val: float) -> Path: |
| 173 |
return self.h(max(0, val)) |
| 174 |
|
| 175 |
def left(self, val: float) -> Path: |
| 176 |
return self.h(-max(0, val)) |
| 177 |
|
| 178 |
def v(self, val: float) -> Path: |
| 179 |
self.attrs["d"] += f"v{val}" |
| 180 |
return self |
| 181 |
|
| 182 |
def down(self, val: float) -> Path: |
| 183 |
return self.v(max(0, val)) |
| 184 |
|
| 185 |
def up(self, val: float) -> Path: |
| 186 |
return self.v(-max(0, val)) |
| 187 |
|
| 188 |
def arc_8(self, start: str, dir: str) -> Path: |
| 189 |
|
| 190 |
arc = AR |
| 191 |
s2 = 1 / Math.sqrt(2) * arc |
| 192 |
s2inv = arc - s2 |
| 193 |
sweep = "1" if dir == "cw" else "0" |
| 194 |
path = f"a {arc} {arc} 0 0 {sweep} " |
| 195 |
sd = start + dir |
| 196 |
offset: List[float] |
| 197 |
if sd == "ncw": |
| 198 |
offset = [s2, s2inv] |
| 199 |
elif sd == "necw": |
| 200 |
offset = [s2inv, s2] |
| 201 |
elif sd == "ecw": |
| 202 |
offset = [-s2inv, s2] |
| 203 |
elif sd == "secw": |
| 204 |
offset = [-s2, s2inv] |
| 205 |
elif sd == "scw": |
| 206 |
offset = [-s2, -s2inv] |
| 207 |
elif sd == "swcw": |
| 208 |
offset = [-s2inv, -s2] |
| 209 |
elif sd == "wcw": |
| 210 |
offset = [s2inv, -s2] |
| 211 |
elif sd == "nwcw": |
| 212 |
offset = [s2, -s2inv] |
| 213 |
elif sd == "nccw": |
| 214 |
offset = [-s2, s2inv] |
| 215 |
elif sd == "nwccw": |
| 216 |
offset = [-s2inv, s2] |
| 217 |
elif sd == "wccw": |
| 218 |
offset = [s2inv, s2] |
| 219 |
elif sd == "swccw": |
| 220 |
offset = [s2, s2inv] |
| 221 |
elif sd == "sccw": |
| 222 |
offset = [s2, -s2inv] |
| 223 |
elif sd == "seccw": |
| 224 |
offset = [s2inv, -s2] |
| 225 |
elif sd == "eccw": |
| 226 |
offset = [-s2inv, -s2] |
| 227 |
elif sd == "neccw": |
| 228 |
offset = [-s2, -s2inv] |
| 229 |
|
| 230 |
path += " ".join(str(x) for x in offset) |
| 231 |
self.attrs["d"] += path |
| 232 |
return self |
| 233 |
|
| 234 |
def arc(self, sweep: str) -> Path: |
| 235 |
x = AR |
| 236 |
y = AR |
| 237 |
if sweep[0] == "e" or sweep[1] == "w": |
| 238 |
x *= -1 |
| 239 |
if sweep[0] == "s" or sweep[1] == "n": |
| 240 |
y *= -1 |
| 241 |
cw = 1 if sweep in ("ne", "es", "sw", "wn") else 0 |
| 242 |
self.attrs["d"] += f"a{AR} {AR} 0 0 {cw} {x} {y}" |
| 243 |
return self |
| 244 |
|
| 245 |
def addTo(self, parent: DiagramItem) -> Path: |
| 246 |
parent.children.append(self) |
| 247 |
return self |
| 248 |
|
| 249 |
def writeSvg(self, write: WriterF) -> None: |
| 250 |
write("<path") |
| 251 |
for name, value in sorted(self.attrs.items()): |
| 252 |
write(f' {name}="{escapeAttr(value)}"') |
| 253 |
write(" />") |
| 254 |
|
| 255 |
def format(self) -> Path: |
| 256 |
self.attrs["d"] += "h.5" |
| 257 |
return self |
| 258 |
|
| 259 |
def textDiagram(self) -> TextDiagram: |
| 260 |
return TextDiagram(0, 0, []) |
| 261 |
|
| 262 |
def __repr__(self) -> str: |
| 263 |
return f"Path({repr(self.x)}, {repr(self.y)})" |
| 264 |
|
| 265 |
|
| 266 |
def wrapString(value: Node) -> DiagramItem: |
| 267 |
return value if isinstance(value, DiagramItem) else Terminal(value) |
| 268 |
|
| 269 |
|
| 270 |
DEFAULT_STYLE = """\ |
| 271 |
svg.railroad-diagram { |
| 272 |
background-color:hsl(30,20%,95%); |
| 273 |
} |
| 274 |
svg.railroad-diagram path { |
| 275 |
stroke-width:3; |
| 276 |
stroke:black; |
| 277 |
fill:rgba(0,0,0,0); |
| 278 |
} |
| 279 |
svg.railroad-diagram text { |
| 280 |
font:bold 14px monospace; |
| 281 |
text-anchor:middle; |
| 282 |
} |
| 283 |
svg.railroad-diagram text.label{ |
| 284 |
text-anchor:start; |
| 285 |
} |
| 286 |
svg.railroad-diagram text.comment{ |
| 287 |
font:italic 12px monospace; |
| 288 |
} |
| 289 |
svg.railroad-diagram rect{ |
| 290 |
stroke-width:3; |
| 291 |
stroke:black; |
| 292 |
fill:hsl(120,100%,90%); |
| 293 |
} |
| 294 |
svg.railroad-diagram rect.group-box { |
| 295 |
stroke: gray; |
| 296 |
stroke-dasharray: 10 5; |
| 297 |
fill: none; |
| 298 |
} |
| 299 |
""" |
| 300 |
|
| 301 |
|
| 302 |
class Style: |
| 303 |
def __init__(self, css: str): |
| 304 |
self.css = css |
| 305 |
|
| 306 |
def __repr__(self) -> str: |
| 307 |
return f"Style({repr(self.css)})" |
| 308 |
|
| 309 |
def addTo(self, parent: DiagramItem) -> Style: |
| 310 |
parent.children.append(self) |
| 311 |
return self |
| 312 |
|
| 313 |
def format(self) -> Style: |
| 314 |
return self |
| 315 |
|
| 316 |
def textDiagram(self) -> TextDiagram: |
| 317 |
return TextDiagram(0, 0, []) |
| 318 |
|
| 319 |
def writeSvg(self, write: WriterF) -> None: |
| 320 |
|
| 321 |
cdata = "/* <![CDATA[ */\n{css}\n/* ]]> */\n".format(css=self.css) |
| 322 |
write("<style>{cdata}</style>".format(cdata=cdata)) |
| 323 |
|
| 324 |
|
| 325 |
class Diagram(DiagramMultiContainer): |
| 326 |
def __init__(self, *items: Node, **kwargs: str): |
| 327 |
|
| 328 |
DiagramMultiContainer.__init__( |
| 329 |
self, |
| 330 |
"svg", |
| 331 |
list(items), |
| 332 |
{ |
| 333 |
"class": DIAGRAM_CLASS, |
| 334 |
}, |
| 335 |
) |
| 336 |
self.type = kwargs.get("type", "simple") |
| 337 |
if items and not isinstance(items[0], Start): |
| 338 |
self.items.insert(0, Start(self.type)) |
| 339 |
if items and not isinstance(items[-1], End): |
| 340 |
self.items.append(End(self.type)) |
| 341 |
self.up = 0 |
| 342 |
self.down = 0 |
| 343 |
self.height = 0 |
| 344 |
self.width = 0 |
| 345 |
for item in self.items: |
| 346 |
if isinstance(item, Style): |
| 347 |
continue |
| 348 |
self.width += item.width + (20 if item.needsSpace else 0) |
| 349 |
self.up = max(self.up, item.up - self.height) |
| 350 |
self.height += item.height |
| 351 |
self.down = max(self.down - item.height, item.down) |
| 352 |
if self.items[0].needsSpace: |
| 353 |
self.width -= 10 |
| 354 |
if self.items[-1].needsSpace: |
| 355 |
self.width -= 10 |
| 356 |
self.formatted = False |
| 357 |
|
| 358 |
def __repr__(self) -> str: |
| 359 |
items = ", ".join(map(repr, self.items[1:-1])) |
| 360 |
pieces = [] if not items else [items] |
| 361 |
if self.type != "simple": |
| 362 |
pieces.append(f"type={repr(self.type)}") |
| 363 |
return f'Diagram({", ".join(pieces)})' |
| 364 |
|
| 365 |
def format( |
| 366 |
self, |
| 367 |
paddingTop: float = 20, |
| 368 |
paddingRight: Opt[float] = None, |
| 369 |
paddingBottom: Opt[float] = None, |
| 370 |
paddingLeft: Opt[float] = None, |
| 371 |
) -> Diagram: |
| 372 |
if paddingRight is None: |
| 373 |
paddingRight = paddingTop |
| 374 |
if paddingBottom is None: |
| 375 |
paddingBottom = paddingTop |
| 376 |
if paddingLeft is None: |
| 377 |
paddingLeft = paddingRight |
| 378 |
assert paddingRight is not None |
| 379 |
assert paddingBottom is not None |
| 380 |
assert paddingLeft is not None |
| 381 |
x = paddingLeft |
| 382 |
y = paddingTop + self.up |
| 383 |
g = DiagramItem("g") |
| 384 |
if STROKE_ODD_PIXEL_LENGTH: |
| 385 |
g.attrs["transform"] = "translate(.5 .5)" |
| 386 |
for item in self.items: |
| 387 |
if item.needsSpace: |
| 388 |
Path(x, y).h(10).addTo(g) |
| 389 |
x += 10 |
| 390 |
item.format(x, y, item.width).addTo(g) |
| 391 |
x += item.width |
| 392 |
y += item.height |
| 393 |
if item.needsSpace: |
| 394 |
Path(x, y).h(10).addTo(g) |
| 395 |
x += 10 |
| 396 |
self.attrs["width"] = str(self.width + paddingLeft + paddingRight) |
| 397 |
self.attrs["height"] = str( |
| 398 |
self.up + self.height + self.down + paddingTop + paddingBottom |
| 399 |
) |
| 400 |
self.attrs["viewBox"] = f"0 0 {self.attrs['width']} {self.attrs['height']}" |
| 401 |
g.addTo(self) |
| 402 |
self.formatted = True |
| 403 |
return self |
| 404 |
|
| 405 |
def textDiagram(self) -> TextDiagram: |
| 406 |
(separator, ) = TextDiagram._getParts(["separator"]) |
| 407 |
diagramTD = self.items[0].textDiagram() |
| 408 |
for item in self.items[1:]: |
| 409 |
itemTD = item.textDiagram() |
| 410 |
if item.needsSpace: |
| 411 |
itemTD = itemTD.expand(1, 1, 0, 0) |
| 412 |
diagramTD = diagramTD.appendRight(itemTD, separator) |
| 413 |
return diagramTD |
| 414 |
|
| 415 |
def writeSvg(self, write: WriterF) -> None: |
| 416 |
if not self.formatted: |
| 417 |
self.format() |
| 418 |
return DiagramItem.writeSvg(self, write) |
| 419 |
|
| 420 |
def writeText(self, write: WriterF) -> None: |
| 421 |
output = self.textDiagram() |
| 422 |
output = "\n".join(output.lines) + "\n" |
| 423 |
if ESCAPE_HTML: |
| 424 |
output = output.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """) |
| 425 |
write(output) |
| 426 |
|
| 427 |
def writeStandalone(self, write: WriterF, css: str | None = None) -> None: |
| 428 |
if not self.formatted: |
| 429 |
self.format() |
| 430 |
if css is None: |
| 431 |
css = DEFAULT_STYLE |
| 432 |
Style(css).addTo(self) |
| 433 |
self.attrs["xmlns"] = "http://www.w3.org/2000/svg" |
| 434 |
self.attrs['xmlns:xlink'] = "http://www.w3.org/1999/xlink" |
| 435 |
DiagramItem.writeSvg(self, write) |
| 436 |
self.children.pop() |
| 437 |
del self.attrs["xmlns"] |
| 438 |
del self.attrs["xmlns:xlink"] |
| 439 |
|
| 440 |
|
| 441 |
class Sequence(DiagramMultiContainer): |
| 442 |
def __init__(self, *items: Node): |
| 443 |
DiagramMultiContainer.__init__(self, "g", items) |
| 444 |
self.needsSpace = True |
| 445 |
self.up = 0 |
| 446 |
self.down = 0 |
| 447 |
self.height = 0 |
| 448 |
self.width = 0 |
| 449 |
for item in self.items: |
| 450 |
self.width += item.width + (20 if item.needsSpace else 0) |
| 451 |
self.up = max(self.up, item.up - self.height) |
| 452 |
self.height += item.height |
| 453 |
self.down = max(self.down - item.height, item.down) |
| 454 |
if self.items[0].needsSpace: |
| 455 |
self.width -= 10 |
| 456 |
if self.items[-1].needsSpace: |
| 457 |
self.width -= 10 |
| 458 |
addDebug(self) |
| 459 |
|
| 460 |
def __repr__(self) -> str: |
| 461 |
items = ", ".join(repr(item) for item in self.items) |
| 462 |
return f"Sequence({items})" |
| 463 |
|
| 464 |
def format(self, x: float, y: float, width: float) -> Sequence: |
| 465 |
leftGap, rightGap = determineGaps(width, self.width) |
| 466 |
Path(x, y).h(leftGap).addTo(self) |
| 467 |
Path(x + leftGap + self.width, y + self.height).h(rightGap).addTo(self) |
| 468 |
x += leftGap |
| 469 |
for i, item in enumerate(self.items): |
| 470 |
if item.needsSpace and i > 0: |
| 471 |
Path(x, y).h(10).addTo(self) |
| 472 |
x += 10 |
| 473 |
item.format(x, y, item.width).addTo(self) |
| 474 |
x += item.width |
| 475 |
y += item.height |
| 476 |
if item.needsSpace and i < len(self.items) - 1: |
| 477 |
Path(x, y).h(10).addTo(self) |
| 478 |
x += 10 |
| 479 |
return self |
| 480 |
|
| 481 |
def textDiagram(self) -> TextDiagram: |
| 482 |
(separator, ) = TextDiagram._getParts(["separator"]) |
| 483 |
diagramTD = TextDiagram(0, 0, [""]) |
| 484 |
for item in self.items: |
| 485 |
itemTD = item.textDiagram() |
| 486 |
if item.needsSpace: |
| 487 |
itemTD = itemTD.expand(1, 1, 0, 0) |
| 488 |
diagramTD = diagramTD.appendRight(itemTD, separator) |
| 489 |
return diagramTD |
| 490 |
|
| 491 |
|
| 492 |
class Stack(DiagramMultiContainer): |
| 493 |
def __init__(self, *items: Node): |
| 494 |
DiagramMultiContainer.__init__(self, "g", items) |
| 495 |
self.needsSpace = True |
| 496 |
self.width = max( |
| 497 |
item.width + (20 if item.needsSpace else 0) for item in self.items |
| 498 |
) |
| 499 |
|
| 500 |
if len(self.items) > 1: |
| 501 |
self.width += AR * 2 |
| 502 |
self.up = self.items[0].up |
| 503 |
self.down = self.items[-1].down |
| 504 |
self.height = 0 |
| 505 |
last = len(self.items) - 1 |
| 506 |
for i, item in enumerate(self.items): |
| 507 |
self.height += item.height |
| 508 |
if i > 0: |
| 509 |
self.height += max(AR * 2, item.up + VS) |
| 510 |
if i < last: |
| 511 |
self.height += max(AR * 2, item.down + VS) |
| 512 |
addDebug(self) |
| 513 |
|
| 514 |
def __repr__(self) -> str: |
| 515 |
items = ", ".join(repr(item) for item in self.items) |
| 516 |
return f"Stack({items})" |
| 517 |
|
| 518 |
def format(self, x: float, y: float, width: float) -> Stack: |
| 519 |
leftGap, rightGap = determineGaps(width, self.width) |
| 520 |
Path(x, y).h(leftGap).addTo(self) |
| 521 |
x += leftGap |
| 522 |
xInitial = x |
| 523 |
if len(self.items) > 1: |
| 524 |
Path(x, y).h(AR).addTo(self) |
| 525 |
x += AR |
| 526 |
innerWidth = self.width - AR * 2 |
| 527 |
else: |
| 528 |
innerWidth = self.width |
| 529 |
for i, item in enumerate(self.items): |
| 530 |
item.format(x, y, innerWidth).addTo(self) |
| 531 |
x += innerWidth |
| 532 |
y += item.height |
| 533 |
if i != len(self.items) - 1: |
| 534 |
( |
| 535 |
Path(x, y) |
| 536 |
.arc("ne") |
| 537 |
.down(max(0, item.down + VS - AR * 2)) |
| 538 |
.arc("es") |
| 539 |
.left(innerWidth) |
| 540 |
.arc("nw") |
| 541 |
.down(max(0, self.items[i + 1].up + VS - AR * 2)) |
| 542 |
.arc("ws") |
| 543 |
.addTo(self) |
| 544 |
) |
| 545 |
y += max(item.down + VS, AR * 2) + max( |
| 546 |
self.items[i + 1].up + VS, AR * 2 |
| 547 |
) |
| 548 |
x = xInitial + AR |
| 549 |
if len(self.items) > 1: |
| 550 |
Path(x, y).h(AR).addTo(self) |
| 551 |
x += AR |
| 552 |
Path(x, y).h(rightGap).addTo(self) |
| 553 |
return self |
| 554 |
|
| 555 |
def textDiagram(self) -> TextDiagram: |
| 556 |
corner_bot_left, corner_bot_right, corner_top_left, corner_top_right, line, line_vertical = TextDiagram._getParts(["corner_bot_left", "corner_bot_right", "corner_top_left", "corner_top_right", "line", "line_vertical"]) |
| 557 |
|
| 558 |
|
| 559 |
itemTDs = [] |
| 560 |
for item in self.items: |
| 561 |
itemTDs.append(item.textDiagram()) |
| 562 |
maxWidth = max([itemTD.width for itemTD in itemTDs]) |
| 563 |
|
| 564 |
leftLines = [] |
| 565 |
rightLines = [] |
| 566 |
separatorTD = TextDiagram(0, 0, [line * maxWidth]) |
| 567 |
diagramTD = None |
| 568 |
|
| 569 |
for itemNum, itemTD in enumerate(itemTDs): |
| 570 |
if itemNum == 0: |
| 571 |
|
| 572 |
leftLines += [line * 2] |
| 573 |
leftLines += [" " * 2] * (itemTD.height - itemTD.entry - 1) |
| 574 |
else: |
| 575 |
|
| 576 |
|
| 577 |
diagramTD = diagramTD.appendBelow(separatorTD, []) |
| 578 |
leftLines += [corner_top_left + line] |
| 579 |
leftLines += [line_vertical + " "] * (itemTD.entry) |
| 580 |
leftLines += [corner_bot_left + line] |
| 581 |
leftLines += [" " * 2] * (itemTD.height - itemTD.entry - 1) |
| 582 |
rightLines += [" " * 2] * (itemTD.exit) |
| 583 |
if itemNum < len(itemTDs) - 1: |
| 584 |
|
| 585 |
|
| 586 |
rightLines += [line + corner_top_right] |
| 587 |
rightLines += [" " + line_vertical] * (itemTD.height - itemTD.exit - 1) |
| 588 |
rightLines += [line + corner_bot_right] |
| 589 |
else: |
| 590 |
|
| 591 |
rightLines += [line * 2] |
| 592 |
leftPad, rightPad = TextDiagram._gaps(maxWidth, itemTD.width) |
| 593 |
itemTD = itemTD.expand(leftPad, rightPad, 0, 0) |
| 594 |
if itemNum == 0: |
| 595 |
diagramTD = itemTD |
| 596 |
else: |
| 597 |
diagramTD = diagramTD.appendBelow(itemTD, []) |
| 598 |
|
| 599 |
leftTD = TextDiagram(0, 0, leftLines) |
| 600 |
diagramTD = leftTD.appendRight(diagramTD, "") |
| 601 |
rightTD = TextDiagram(0, len(rightLines) - 1, rightLines) |
| 602 |
diagramTD = diagramTD.appendRight(rightTD, "") |
| 603 |
return diagramTD |
| 604 |
|
| 605 |
|
| 606 |
class OptionalSequence(DiagramMultiContainer): |
| 607 |
def __new__(cls, *items: Node) -> Any: |
| 608 |
if len(items) <= 1: |
| 609 |
return Sequence(*items) |
| 610 |
else: |
| 611 |
return super(OptionalSequence, cls).__new__(cls) |
| 612 |
|
| 613 |
def __init__(self, *items: Node): |
| 614 |
DiagramMultiContainer.__init__(self, "g", items) |
| 615 |
self.needsSpace = False |
| 616 |
self.width = 0 |
| 617 |
self.up = 0 |
| 618 |
self.height = sum(item.height for item in self.items) |
| 619 |
self.down = self.items[0].down |
| 620 |
heightSoFar: float = 0 |
| 621 |
for i, item in enumerate(self.items): |
| 622 |
self.up = max(self.up, max(AR * 2, item.up + VS) - heightSoFar) |
| 623 |
heightSoFar += item.height |
| 624 |
if i > 0: |
| 625 |
self.down = ( |
| 626 |
max( |
| 627 |
self.height + self.down, |
| 628 |
heightSoFar + max(AR * 2, item.down + VS), |
| 629 |
) |
| 630 |
- self.height |
| 631 |
) |
| 632 |
itemWidth = item.width + (10 if item.needsSpace else 0) |
| 633 |
if i == 0: |
| 634 |
self.width += AR + max(itemWidth, AR) |
| 635 |
else: |
| 636 |
self.width += AR * 2 + max(itemWidth, AR) + AR |
| 637 |
addDebug(self) |
| 638 |
|
| 639 |
def __repr__(self) -> str: |
| 640 |
items = ", ".join(repr(item) for item in self.items) |
| 641 |
return f"OptionalSequence({items})" |
| 642 |
|
| 643 |
def format(self, x: float, y: float, width: float) -> OptionalSequence: |
| 644 |
leftGap, rightGap = determineGaps(width, self.width) |
| 645 |
Path(x, y).right(leftGap).addTo(self) |
| 646 |
Path(x + leftGap + self.width, y + self.height).right(rightGap).addTo(self) |
| 647 |
x += leftGap |
| 648 |
upperLineY = y - self.up |
| 649 |
last = len(self.items) - 1 |
| 650 |
for i, item in enumerate(self.items): |
| 651 |
itemSpace = 10 if item.needsSpace else 0 |
| 652 |
itemWidth = item.width + itemSpace |
| 653 |
if i == 0: |
| 654 |
|
| 655 |
( |
| 656 |
Path(x, y) |
| 657 |
.arc("se") |
| 658 |
.up(y - upperLineY - AR * 2) |
| 659 |
.arc("wn") |
| 660 |
.right(itemWidth - AR) |
| 661 |
.arc("ne") |
| 662 |
.down(y + item.height - upperLineY - AR * 2) |
| 663 |
.arc("ws") |
| 664 |
.addTo(self) |
| 665 |
) |
| 666 |
|
| 667 |
(Path(x, y).right(itemSpace + AR).addTo(self)) |
| 668 |
item.format(x + itemSpace + AR, y, item.width).addTo(self) |
| 669 |
x += itemWidth + AR |
| 670 |
y += item.height |
| 671 |
elif i < last: |
| 672 |
|
| 673 |
( |
| 674 |
Path(x, upperLineY) |
| 675 |
.right(AR * 2 + max(itemWidth, AR) + AR) |
| 676 |
.arc("ne") |
| 677 |
.down(y - upperLineY + item.height - AR * 2) |
| 678 |
.arc("ws") |
| 679 |
.addTo(self) |
| 680 |
) |
| 681 |
|
| 682 |
(Path(x, y).right(AR * 2).addTo(self)) |
| 683 |
item.format(x + AR * 2, y, item.width).addTo(self) |
| 684 |
( |
| 685 |
Path(x + item.width + AR * 2, y + item.height) |
| 686 |
.right(itemSpace + AR) |
| 687 |
.addTo(self) |
| 688 |
) |
| 689 |
|
| 690 |
( |
| 691 |
Path(x, y) |
| 692 |
.arc("ne") |
| 693 |
.down(item.height + max(item.down + VS, AR * 2) - AR * 2) |
| 694 |
.arc("ws") |
| 695 |
.right(itemWidth - AR) |
| 696 |
.arc("se") |
| 697 |
.up(item.down + VS - AR * 2) |
| 698 |
.arc("wn") |
| 699 |
.addTo(self) |
| 700 |
) |
| 701 |
x += AR * 2 + max(itemWidth, AR) + AR |
| 702 |
y += item.height |
| 703 |
else: |
| 704 |
|
| 705 |
(Path(x, y).right(AR * 2).addTo(self)) |
| 706 |
item.format(x + AR * 2, y, item.width).addTo(self) |
| 707 |
( |
| 708 |
Path(x + AR * 2 + item.width, y + item.height) |
| 709 |
.right(itemSpace + AR) |
| 710 |
.addTo(self) |
| 711 |
) |
| 712 |
|
| 713 |
( |
| 714 |
Path(x, y) |
| 715 |
.arc("ne") |
| 716 |
.down(item.height + max(item.down + VS, AR * 2) - AR * 2) |
| 717 |
.arc("ws") |
| 718 |
.right(itemWidth - AR) |
| 719 |
.arc("se") |
| 720 |
.up(item.down + VS - AR * 2) |
| 721 |
.arc("wn") |
| 722 |
.addTo(self) |
| 723 |
) |
| 724 |
return self |
| 725 |
|
| 726 |
def textDiagram(self) -> TextDiagram: |
| 727 |
line, line_vertical, roundcorner_bot_left, roundcorner_bot_right, roundcorner_top_left, roundcorner_top_right = TextDiagram._getParts(["line", "line_vertical", "roundcorner_bot_left", "roundcorner_bot_right", "roundcorner_top_left", "roundcorner_top_right"]) |
| 728 |
|
| 729 |
|
| 730 |
itemTDs = [] |
| 731 |
for item in self.items: |
| 732 |
itemTDs.append(item.textDiagram()) |
| 733 |
|
| 734 |
diagramEntry = max([itemTD.entry for itemTD in itemTDs]) |
| 735 |
|
| 736 |
SOILHeight = max([itemTD.entry for itemTD in itemTDs[:-1]]) |
| 737 |
|
| 738 |
topToSOIL = diagramEntry - SOILHeight |
| 739 |
|
| 740 |
|
| 741 |
lines = [" " * 2] * topToSOIL |
| 742 |
lines += [roundcorner_top_left + line] |
| 743 |
lines += [line_vertical + " "] * SOILHeight |
| 744 |
lines += [roundcorner_bot_right + line] |
| 745 |
diagramTD = TextDiagram(len(lines) - 1, len(lines) - 1, lines) |
| 746 |
for itemNum, itemTD in enumerate(itemTDs): |
| 747 |
if itemNum > 0: |
| 748 |
|
| 749 |
|
| 750 |
lines = [] |
| 751 |
lines += [" " * 2] * topToSOIL |
| 752 |
lines += [line * 2] |
| 753 |
lines += [" " * 2] * (diagramTD.exit - topToSOIL - 1) |
| 754 |
lines += [line + roundcorner_top_right] |
| 755 |
lines += [" " + line_vertical] * (itemTD.height - itemTD.entry - 1) |
| 756 |
lines += [" " + roundcorner_bot_left] |
| 757 |
skipDownTD = TextDiagram(diagramTD.exit, diagramTD.exit, lines) |
| 758 |
diagramTD = diagramTD.appendRight(skipDownTD, "") |
| 759 |
|
| 760 |
|
| 761 |
lines = [] |
| 762 |
lines += [" " * 2] * topToSOIL |
| 763 |
|
| 764 |
lineToNextItem = line if itemNum < len(itemTDs) - 1 else " " |
| 765 |
lines += [line + roundcorner_top_right + lineToNextItem] |
| 766 |
lines += [" " + line_vertical + " "] * (diagramTD.exit - topToSOIL - 1) |
| 767 |
lines += [line + roundcorner_bot_left + line] |
| 768 |
lines += [" " * 3] * (itemTD.height - itemTD.entry - 1) |
| 769 |
lines += [line * 3] |
| 770 |
entryTD = TextDiagram(diagramTD.exit, diagramTD.exit, lines) |
| 771 |
diagramTD = diagramTD.appendRight(entryTD, "") |
| 772 |
partTD = TextDiagram(0, 0, []) |
| 773 |
if itemNum < len(itemTDs) - 1: |
| 774 |
|
| 775 |
|
| 776 |
lines = [] |
| 777 |
lines += [line * itemTD.width] |
| 778 |
lines += [" " * itemTD.width] * (SOILHeight - itemTD.entry) |
| 779 |
SOILSegment = TextDiagram(0, 0, lines) |
| 780 |
partTD = partTD.appendBelow(SOILSegment, []) |
| 781 |
partTD = partTD.appendBelow(itemTD, [], moveEntry=True, moveExit=True) |
| 782 |
if itemNum > 0: |
| 783 |
|
| 784 |
SUILSegment = TextDiagram(0, 0, [line * itemTD.width]) |
| 785 |
partTD = partTD.appendBelow(SUILSegment, []) |
| 786 |
diagramTD = diagramTD.appendRight(partTD, "") |
| 787 |
if 0 < itemNum: |
| 788 |
|
| 789 |
lines = [] |
| 790 |
lines += [" " * 2] * topToSOIL |
| 791 |
|
| 792 |
skipOverChar = line if itemNum < len(itemTDs) - 1 else " " |
| 793 |
lines += [skipOverChar * 2] |
| 794 |
lines += [" " * 2] * (diagramTD.exit - topToSOIL - 1) |
| 795 |
lines += [line + roundcorner_top_left] |
| 796 |
lines += [" " + line_vertical] * (partTD.height - partTD.exit - 2) |
| 797 |
lines += [line + roundcorner_bot_right] |
| 798 |
skipUpTD = TextDiagram(diagramTD.exit, diagramTD.exit, lines) |
| 799 |
diagramTD = diagramTD.appendRight(skipUpTD, "") |
| 800 |
return diagramTD |
| 801 |
|
| 802 |
|
| 803 |
class AlternatingSequence(DiagramMultiContainer): |
| 804 |
def __new__(cls, *items: Node) -> AlternatingSequence: |
| 805 |
if len(items) == 2: |
| 806 |
return super(AlternatingSequence, cls).__new__(cls) |
| 807 |
else: |
| 808 |
raise Exception( |
| 809 |
"AlternatingSequence takes exactly two arguments, but got {0} arguments.".format( |
| 810 |
len(items) |
| 811 |
) |
| 812 |
) |
| 813 |
|
| 814 |
def __init__(self, *items: Node): |
| 815 |
DiagramMultiContainer.__init__(self, "g", items) |
| 816 |
self.needsSpace = False |
| 817 |
|
| 818 |
arc = AR |
| 819 |
vert = VS |
| 820 |
first = self.items[0] |
| 821 |
second = self.items[1] |
| 822 |
|
| 823 |
arcX = 1 / Math.sqrt(2) * arc * 2 |
| 824 |
arcY = (1 - 1 / Math.sqrt(2)) * arc * 2 |
| 825 |
crossY = max(arc, vert) |
| 826 |
crossX = (crossY - arcY) + arcX |
| 827 |
|
| 828 |
firstOut = max( |
| 829 |
arc + arc, crossY / 2 + arc + arc, crossY / 2 + vert + first.down |
| 830 |
) |
| 831 |
self.up = firstOut + first.height + first.up |
| 832 |
|
| 833 |
secondIn = max(arc + arc, crossY / 2 + arc + arc, crossY / 2 + vert + second.up) |
| 834 |
self.down = secondIn + second.height + second.down |
| 835 |
|
| 836 |
self.height = 0 |
| 837 |
|
| 838 |
firstWidth = (20 if first.needsSpace else 0) + first.width |
| 839 |
secondWidth = (20 if second.needsSpace else 0) + second.width |
| 840 |
self.width = 2 * arc + max(firstWidth, crossX, secondWidth) + 2 * arc |
| 841 |
addDebug(self) |
| 842 |
|
| 843 |
def __repr__(self) -> str: |
| 844 |
items = ", ".join(repr(item) for item in self.items) |
| 845 |
return f"AlternatingSequence({items})" |
| 846 |
|
| 847 |
def format(self, x: float, y: float, width: float) -> AlternatingSequence: |
| 848 |
arc = AR |
| 849 |
gaps = determineGaps(width, self.width) |
| 850 |
Path(x, y).right(gaps[0]).addTo(self) |
| 851 |
x += gaps[0] |
| 852 |
Path(x + self.width, y).right(gaps[1]).addTo(self) |
| 853 |
|
| 854 |
|
| 855 |
first = self.items[0] |
| 856 |
second = self.items[1] |
| 857 |
|
| 858 |
|
| 859 |
firstIn = self.up - first.up |
| 860 |
firstOut = self.up - first.up - first.height |
| 861 |
Path(x, y).arc("se").up(firstIn - 2 * arc).arc("wn").addTo(self) |
| 862 |
first.format(x + 2 * arc, y - firstIn, self.width - 4 * arc).addTo(self) |
| 863 |
Path(x + self.width - 2 * arc, y - firstOut).arc("ne").down( |
| 864 |
firstOut - 2 * arc |
| 865 |
).arc("ws").addTo(self) |
| 866 |
|
| 867 |
|
| 868 |
secondIn = self.down - second.down - second.height |
| 869 |
secondOut = self.down - second.down |
| 870 |
Path(x, y).arc("ne").down(secondIn - 2 * arc).arc("ws").addTo(self) |
| 871 |
second.format(x + 2 * arc, y + secondIn, self.width - 4 * arc).addTo(self) |
| 872 |
Path(x + self.width - 2 * arc, y + secondOut).arc("se").up( |
| 873 |
secondOut - 2 * arc |
| 874 |
).arc("wn").addTo(self) |
| 875 |
|
| 876 |
|
| 877 |
arcX = 1 / Math.sqrt(2) * arc * 2 |
| 878 |
arcY = (1 - 1 / Math.sqrt(2)) * arc * 2 |
| 879 |
crossY = max(arc, VS) |
| 880 |
crossX = (crossY - arcY) + arcX |
| 881 |
crossBar = (self.width - 4 * arc - crossX) / 2 |
| 882 |
( |
| 883 |
Path(x + arc, y - crossY / 2 - arc) |
| 884 |
.arc("ws") |
| 885 |
.right(crossBar) |
| 886 |
.arc_8("n", "cw") |
| 887 |
.l(crossX - arcX, crossY - arcY) |
| 888 |
.arc_8("sw", "ccw") |
| 889 |
.right(crossBar) |
| 890 |
.arc("ne") |
| 891 |
.addTo(self) |
| 892 |
) |
| 893 |
( |
| 894 |
Path(x + arc, y + crossY / 2 + arc) |
| 895 |
.arc("wn") |
| 896 |
.right(crossBar) |
| 897 |
.arc_8("s", "ccw") |
| 898 |
.l(crossX - arcX, -(crossY - arcY)) |
| 899 |
.arc_8("nw", "cw") |
| 900 |
.right(crossBar) |
| 901 |
.arc("se") |
| 902 |
.addTo(self) |
| 903 |
) |
| 904 |
|
| 905 |
return self |
| 906 |
|
| 907 |
def textDiagram(self) -> TextDiagram: |
| 908 |
cross_diag, corner_bot_left, corner_bot_right, corner_top_left, corner_top_right, line, line_vertical, tee_left, tee_right = TextDiagram._getParts(["cross_diag", "roundcorner_bot_left", "roundcorner_bot_right", "roundcorner_top_left", "roundcorner_top_right", "line", "line_vertical", "tee_left", "tee_right"]) |
| 909 |
|
| 910 |
firstTD = self.items[0].textDiagram() |
| 911 |
secondTD = self.items[1].textDiagram() |
| 912 |
maxWidth = TextDiagram._maxWidth(firstTD, secondTD) |
| 913 |
leftWidth, rightWidth = TextDiagram._gaps(maxWidth, 0) |
| 914 |
leftLines = [] |
| 915 |
rightLines = [] |
| 916 |
separator = [] |
| 917 |
leftSize, rightSize = TextDiagram._gaps(firstTD.width, 0) |
| 918 |
diagramTD = firstTD.expand(leftWidth - leftSize, rightWidth - rightSize, 0, 0) |
| 919 |
leftLines += [" " * 2] * (diagramTD.entry) |
| 920 |
leftLines += [corner_top_left + line] |
| 921 |
leftLines += [line_vertical + " "] * (diagramTD.height - diagramTD.entry - 1) |
| 922 |
leftLines += [corner_bot_left + line] |
| 923 |
rightLines += [" " * 2] * (diagramTD.entry) |
| 924 |
rightLines += [line + corner_top_right] |
| 925 |
rightLines += [" " + line_vertical] * (diagramTD.height - diagramTD.entry - 1) |
| 926 |
rightLines += [line + corner_bot_right] |
| 927 |
|
| 928 |
leftSepWidth, rightSepWidth = TextDiagram._gaps(firstTD.width - 3, 0) |
| 929 |
separator += [(line * leftSepWidth) + corner_top_right + " " + corner_top_left + (line * rightSepWidth)] |
| 930 |
separator += [(" " * leftSepWidth) + " " + cross_diag + " " + (" " * (rightSepWidth))] |
| 931 |
separator += [(line * leftSepWidth) + corner_bot_right + " " + corner_bot_left + (line * rightSepWidth)] |
| 932 |
leftLines += [" " * 2] |
| 933 |
rightLines += [" " * 2] |
| 934 |
|
| 935 |
leftSize, rightSize = TextDiagram._gaps(secondTD.width, 0) |
| 936 |
secondTD = secondTD.expand(leftWidth - leftSize, rightWidth - rightSize, 0, 0) |
| 937 |
diagramTD = diagramTD.appendBelow(secondTD, separator, moveEntry=True, moveExit=True) |
| 938 |
leftLines += [corner_top_left + line] |
| 939 |
leftLines += [line_vertical + " "] * secondTD.entry |
| 940 |
leftLines += [corner_bot_left + line] |
| 941 |
rightLines += [line + corner_top_right] |
| 942 |
rightLines += [" " + line_vertical] * secondTD.entry |
| 943 |
rightLines += [line + corner_bot_right] |
| 944 |
|
| 945 |
diagramTD = diagramTD.alter(entry=firstTD.height + (len(separator) // 2), exit=firstTD.height + (len(separator) // 2)) |
| 946 |
leftTD = TextDiagram(firstTD.height + (len(separator) // 2), firstTD.height + (len(separator) // 2), leftLines) |
| 947 |
rightTD = TextDiagram(firstTD.height + (len(separator) // 2), firstTD.height + (len(separator) // 2), rightLines) |
| 948 |
diagramTD = leftTD.appendRight(diagramTD, "").appendRight(rightTD, "") |
| 949 |
diagramTD = TextDiagram(1, 1, [corner_top_left, tee_left, corner_bot_left]).appendRight(diagramTD, "").appendRight(TextDiagram(1, 1, [corner_top_right, tee_right, corner_bot_right]), "") |
| 950 |
return diagramTD |
| 951 |
|
| 952 |
|
| 953 |
class Choice(DiagramMultiContainer): |
| 954 |
def __init__(self, default: int, *items: Node): |
| 955 |
DiagramMultiContainer.__init__(self, "g", items) |
| 956 |
assert default < len(items) |
| 957 |
self.default = default |
| 958 |
self.width = AR * 4 + max(item.width for item in self.items) |
| 959 |
|
| 960 |
|
| 961 |
|
| 962 |
|
| 963 |
|
| 964 |
self.separators: list[int] = [VS] * (len(items) - 1) |
| 965 |
|
| 966 |
|
| 967 |
|
| 968 |
|
| 969 |
self.up = 0 |
| 970 |
for i in range(default - 1, -1, -1): |
| 971 |
if i == default-1: |
| 972 |
arcs = AR * 2 |
| 973 |
else: |
| 974 |
arcs = AR |
| 975 |
|
| 976 |
item = self.items[i] |
| 977 |
lowerItem = self.items[i+1] |
| 978 |
|
| 979 |
entryDelta = lowerItem.up + VS + item.down + item.height |
| 980 |
exitDelta = lowerItem.height + lowerItem.up + VS + item.down |
| 981 |
|
| 982 |
separator = VS |
| 983 |
if exitDelta < arcs or entryDelta < arcs: |
| 984 |
separator += max(arcs - entryDelta, arcs - exitDelta) |
| 985 |
self.separators[i] = separator |
| 986 |
self.up += lowerItem.up + separator + item.down + item.height |
| 987 |
self.up += self.items[0].up |
| 988 |
|
| 989 |
self.height = self.items[default].height |
| 990 |
|
| 991 |
for i in range(default+1, len(self.items)): |
| 992 |
if i == default+1: |
| 993 |
arcs = AR * 2 |
| 994 |
else: |
| 995 |
arcs = AR |
| 996 |
|
| 997 |
item = self.items[i] |
| 998 |
upperItem = self.items[i-1] |
| 999 |
|
| 1000 |
entryDelta = upperItem.height + upperItem.down + VS + item.up |
| 1001 |
exitDelta = upperItem.down + VS + item.up + item.height |
| 1002 |
|
| 1003 |
separator = VS |
| 1004 |
if entryDelta < arcs or exitDelta < arcs: |
| 1005 |
separator += max(arcs - entryDelta, arcs - exitDelta) |
| 1006 |
self.separators[i-1] = separator |
| 1007 |
self.down += upperItem.down + separator + item.up + item.height |
| 1008 |
self.down += self.items[-1].down |
| 1009 |
addDebug(self) |
| 1010 |
|
| 1011 |
def __repr__(self) -> str: |
| 1012 |
items = ", ".join(repr(item) for item in self.items) |
| 1013 |
return f"Choice({self.default}, {items})" |
| 1014 |
|
| 1015 |
def format(self, x: float, y: float, width: float) -> Choice: |
| 1016 |
leftGap, rightGap = determineGaps(width, self.width) |
| 1017 |
|
| 1018 |
|
| 1019 |
Path(x, y).h(leftGap).addTo(self) |
| 1020 |
Path(x + leftGap + self.width, y + self.height).h(rightGap).addTo(self) |
| 1021 |
x += leftGap |
| 1022 |
|
| 1023 |
innerWidth = self.width - AR * 4 |
| 1024 |
default = self.items[self.default] |
| 1025 |
|
| 1026 |
|
| 1027 |
distanceFromY = 0 |
| 1028 |
for i in range(self.default - 1, -1, -1): |
| 1029 |
item = self.items[i] |
| 1030 |
lowerItem = self.items[i+1] |
| 1031 |
distanceFromY += lowerItem.up + self.separators[i] + item.down + item.height |
| 1032 |
Path(x, y).arc("se").up(distanceFromY - AR * 2).arc("wn").addTo(self) |
| 1033 |
item.format(x + AR * 2, y - distanceFromY, innerWidth).addTo(self) |
| 1034 |
Path(x + AR * 2 + innerWidth, y - distanceFromY + item.height).arc( |
| 1035 |
"ne" |
| 1036 |
).down(distanceFromY - item.height + default.height - AR * 2).arc( |
| 1037 |
"ws" |
| 1038 |
).addTo( |
| 1039 |
self |
| 1040 |
) |
| 1041 |
|
| 1042 |
|
| 1043 |
Path(x, y).right(AR * 2).addTo(self) |
| 1044 |
self.items[self.default].format(x + AR * 2, y, innerWidth).addTo(self) |
| 1045 |
Path(x + AR * 2 + innerWidth, y + self.height).right(AR * 2).addTo(self) |
| 1046 |
|
| 1047 |
|
| 1048 |
distanceFromY = 0 |
| 1049 |
for i in range(self.default+1, len(self.items)): |
| 1050 |
item = self.items[i] |
| 1051 |
upperItem = self.items[i-1] |
| 1052 |
distanceFromY += upperItem.height + upperItem.down + self.separators[i-1] + item.up |
| 1053 |
Path(x, y).arc("ne").down(distanceFromY - AR * 2).arc("ws").addTo(self) |
| 1054 |
item.format(x + AR * 2, y + distanceFromY, innerWidth).addTo(self) |
| 1055 |
Path(x + AR * 2 + innerWidth, y + distanceFromY + item.height).arc("se").up( |
| 1056 |
distanceFromY - AR * 2 + item.height - default.height |
| 1057 |
).arc("wn").addTo(self) |
| 1058 |
|
| 1059 |
return self |
| 1060 |
|
| 1061 |
def textDiagram(self) -> TextDiagram: |
| 1062 |
cross, line, line_vertical, roundcorner_bot_left, roundcorner_bot_right, roundcorner_top_left, roundcorner_top_right = TextDiagram._getParts(["cross", "line", "line_vertical", "roundcorner_bot_left", "roundcorner_bot_right", "roundcorner_top_left", "roundcorner_top_right"]) |
| 1063 |
|
| 1064 |
itemTDs = [] |
| 1065 |
for item in self.items: |
| 1066 |
itemTDs.append(item.textDiagram().expand(1, 1, 0, 0)) |
| 1067 |
max_item_width = max([i.width for i in itemTDs]) |
| 1068 |
diagramTD = TextDiagram(0, 0, []) |
| 1069 |
|
| 1070 |
for itemNum, itemTD in enumerate(itemTDs): |
| 1071 |
leftPad, rightPad = TextDiagram._gaps(max_item_width, itemTD.width) |
| 1072 |
itemTD = itemTD.expand(leftPad, rightPad, 0, 0) |
| 1073 |
hasSeparator = True |
| 1074 |
leftLines = [line_vertical] * itemTD.height |
| 1075 |
rightLines = [line_vertical] * itemTD.height |
| 1076 |
moveEntry = False |
| 1077 |
moveExit = False |
| 1078 |
if itemNum <= self.default: |
| 1079 |
|
| 1080 |
leftLines[itemTD.entry] = roundcorner_top_left |
| 1081 |
rightLines[itemTD.exit] = roundcorner_top_right |
| 1082 |
if itemNum == 0: |
| 1083 |
|
| 1084 |
hasSeparator = False |
| 1085 |
for i in range(0, itemTD.entry): |
| 1086 |
leftLines[i] = " " |
| 1087 |
for i in range(0, itemTD.exit): |
| 1088 |
rightLines[i] = " " |
| 1089 |
if itemNum >= self.default: |
| 1090 |
|
| 1091 |
leftLines[itemTD.entry] = roundcorner_bot_left |
| 1092 |
rightLines[itemTD.exit] = roundcorner_bot_right |
| 1093 |
if itemNum == 0: |
| 1094 |
|
| 1095 |
hasSeparator = False |
| 1096 |
if itemNum == (len(self.items) - 1): |
| 1097 |
|
| 1098 |
for i in range(itemTD.entry + 1, itemTD.height): |
| 1099 |
leftLines[i] = " " |
| 1100 |
for i in range(itemTD.exit + 1, itemTD.height): |
| 1101 |
rightLines[i] = " " |
| 1102 |
if itemNum == self.default: |
| 1103 |
|
| 1104 |
leftLines[itemTD.entry] = cross |
| 1105 |
rightLines[itemTD.exit] = cross |
| 1106 |
moveEntry = True |
| 1107 |
moveExit = True |
| 1108 |
if itemNum == 0 and itemNum == (len(self.items) - 1): |
| 1109 |
|
| 1110 |
leftLines[itemTD.entry] = line |
| 1111 |
rightLines[itemTD.exit] = line |
| 1112 |
elif itemNum == 0: |
| 1113 |
|
| 1114 |
leftLines[itemTD.entry] = roundcorner_top_right |
| 1115 |
rightLines[itemTD.exit] = roundcorner_top_left |
| 1116 |
elif itemNum == (len(self.items) - 1): |
| 1117 |
|
| 1118 |
leftLines[itemTD.entry] = roundcorner_bot_right |
| 1119 |
rightLines[itemTD.exit] = roundcorner_bot_left |
| 1120 |
leftJointTD = TextDiagram(itemTD.entry, itemTD.entry, leftLines) |
| 1121 |
rightJointTD = TextDiagram(itemTD.exit, itemTD.exit, rightLines) |
| 1122 |
itemTD = leftJointTD.appendRight(itemTD, "").appendRight(rightJointTD, "") |
| 1123 |
separator = [line_vertical + (" " * (TextDiagram._maxWidth(diagramTD, itemTD) - 2)) + line_vertical] if hasSeparator else [] |
| 1124 |
diagramTD = diagramTD.appendBelow(itemTD, separator, moveEntry=moveEntry, moveExit=moveExit) |
| 1125 |
return diagramTD |
| 1126 |
|
| 1127 |
|
| 1128 |
class MultipleChoice(DiagramMultiContainer): |
| 1129 |
def __init__(self, default: int, type: str, *items: Node): |
| 1130 |
DiagramMultiContainer.__init__(self, "g", items) |
| 1131 |
assert 0 <= default < len(items) |
| 1132 |
assert type in ["any", "all"] |
| 1133 |
self.default = default |
| 1134 |
self.type = type |
| 1135 |
self.needsSpace = True |
| 1136 |
self.innerWidth = max(item.width for item in self.items) |
| 1137 |
self.width = 30 + AR + self.innerWidth + AR + 20 |
| 1138 |
self.up = self.items[0].up |
| 1139 |
self.down = self.items[-1].down |
| 1140 |
self.height = self.items[default].height |
| 1141 |
for i, item in enumerate(self.items): |
| 1142 |
if i in [default - 1, default + 1]: |
| 1143 |
minimum = 10 + AR |
| 1144 |
else: |
| 1145 |
minimum = AR |
| 1146 |
if i < default: |
| 1147 |
self.up += max( |
| 1148 |
minimum, item.height + item.down + VS + self.items[i + 1].up |
| 1149 |
) |
| 1150 |
elif i == default: |
| 1151 |
continue |
| 1152 |
else: |
| 1153 |
self.down += max( |
| 1154 |
minimum, |
| 1155 |
item.up + VS + self.items[i - 1].down + self.items[i - 1].height, |
| 1156 |
) |
| 1157 |
self.down -= self.items[default].height |
| 1158 |
addDebug(self) |
| 1159 |
|
| 1160 |
def __repr__(self) -> str: |
| 1161 |
items = ", ".join(repr(item) for item in self.items) |
| 1162 |
return f"MultipleChoice({repr(self.default)}, {repr(self.type)}, {items})" |
| 1163 |
|
| 1164 |
def format(self, x: float, y: float, width: float) -> MultipleChoice: |
| 1165 |
leftGap, rightGap = determineGaps(width, self.width) |
| 1166 |
|
| 1167 |
|
| 1168 |
Path(x, y).h(leftGap).addTo(self) |
| 1169 |
Path(x + leftGap + self.width, y + self.height).h(rightGap).addTo(self) |
| 1170 |
x += leftGap |
| 1171 |
|
| 1172 |
default = self.items[self.default] |
| 1173 |
|
| 1174 |
|
| 1175 |
above = self.items[: self.default][::-1] |
| 1176 |
if above: |
| 1177 |
distanceFromY = max( |
| 1178 |
10 + AR, default.up + VS + above[0].down + above[0].height |
| 1179 |
) |
| 1180 |
for i, ni, item in doubleenumerate(above): |
| 1181 |
(Path(x + 30, y).up(distanceFromY - AR).arc("wn").addTo(self)) |
| 1182 |
item.format(x + 30 + AR, y - distanceFromY, self.innerWidth).addTo(self) |
| 1183 |
( |
| 1184 |
Path(x + 30 + AR + self.innerWidth, y - distanceFromY + item.height) |
| 1185 |
.arc("ne") |
| 1186 |
.down(distanceFromY - item.height + default.height - AR - 10) |
| 1187 |
.addTo(self) |
| 1188 |
) |
| 1189 |
if ni < -1: |
| 1190 |
distanceFromY += max( |
| 1191 |
AR, item.up + VS + above[i + 1].down + above[i + 1].height |
| 1192 |
) |
| 1193 |
|
| 1194 |
|
| 1195 |
Path(x + 30, y).right(AR).addTo(self) |
| 1196 |
self.items[self.default].format(x + 30 + AR, y, self.innerWidth).addTo(self) |
| 1197 |
Path(x + 30 + AR + self.innerWidth, y + self.height).right(AR).addTo(self) |
| 1198 |
|
| 1199 |
|
| 1200 |
below = self.items[self.default + 1 :] |
| 1201 |
if below: |
| 1202 |
distanceFromY = max( |
| 1203 |
10 + AR, default.height + default.down + VS + below[0].up |
| 1204 |
) |
| 1205 |
for i, item in enumerate(below): |
| 1206 |
(Path(x + 30, y).down(distanceFromY - AR).arc("ws").addTo(self)) |
| 1207 |
item.format(x + 30 + AR, y + distanceFromY, self.innerWidth).addTo(self) |
| 1208 |
( |
| 1209 |
Path(x + 30 + AR + self.innerWidth, y + distanceFromY + item.height) |
| 1210 |
.arc("se") |
| 1211 |
.up(distanceFromY - AR + item.height - default.height - 10) |
| 1212 |
.addTo(self) |
| 1213 |
) |
| 1214 |
distanceFromY += max( |
| 1215 |
AR, |
| 1216 |
item.height |
| 1217 |
+ item.down |
| 1218 |
+ VS |
| 1219 |
+ (below[i + 1].up if i + 1 < len(below) else 0), |
| 1220 |
) |
| 1221 |
text = DiagramItem("g", attrs={"class": "diagram-text"}).addTo(self) |
| 1222 |
DiagramItem( |
| 1223 |
"title", |
| 1224 |
text="take one or more branches, once each, in any order" |
| 1225 |
if self.type == "any" |
| 1226 |
else "take all branches, once each, in any order", |
| 1227 |
).addTo(text) |
| 1228 |
DiagramItem( |
| 1229 |
"path", |
| 1230 |
attrs={ |
| 1231 |
"d": "M {x} {y} h -26 a 4 4 0 0 0 -4 4 v 12 a 4 4 0 0 0 4 4 h 26 z".format( |
| 1232 |
x=x + 30, y=y - 10 |
| 1233 |
), |
| 1234 |
"class": "diagram-text", |
| 1235 |
}, |
| 1236 |
).addTo(text) |
| 1237 |
DiagramItem( |
| 1238 |
"text", |
| 1239 |
text="1+" if self.type == "any" else "all", |
| 1240 |
attrs={"x": x + 15, "y": y + 4, "class": "diagram-text"}, |
| 1241 |
).addTo(text) |
| 1242 |
DiagramItem( |
| 1243 |
"path", |
| 1244 |
attrs={ |
| 1245 |
"d": "M {x} {y} h 16 a 4 4 0 0 1 4 4 v 12 a 4 4 0 0 1 -4 4 h -16 z".format( |
| 1246 |
x=x + self.width - 20, y=y - 10 |
| 1247 |
), |
| 1248 |
"class": "diagram-text", |
| 1249 |
}, |
| 1250 |
).addTo(text) |
| 1251 |
DiagramItem( |
| 1252 |
"text", |
| 1253 |
text="↺", |
| 1254 |
attrs={"x": x + self.width - 10, "y": y + 4, "class": "diagram-arrow"}, |
| 1255 |
).addTo(text) |
| 1256 |
return self |
| 1257 |
|
| 1258 |
def textDiagram(self) -> TextDiagram: |
| 1259 |
(multi_repeat,) = TextDiagram._getParts(["multi_repeat"]) |
| 1260 |
anyAll = TextDiagram.rect("1+" if self.type == "any" else "all") |
| 1261 |
diagramTD = Choice.textDiagram(self) |
| 1262 |
repeatTD = TextDiagram.rect(multi_repeat) |
| 1263 |
diagramTD = anyAll.appendRight(diagramTD, "") |
| 1264 |
diagramTD = diagramTD.appendRight(repeatTD, "") |
| 1265 |
return diagramTD |
| 1266 |
|
| 1267 |
|
| 1268 |
class HorizontalChoice(DiagramMultiContainer): |
| 1269 |
def __new__(cls, *items: Node) -> Any: |
| 1270 |
if len(items) <= 1: |
| 1271 |
return Sequence(*items) |
| 1272 |
else: |
| 1273 |
return super(HorizontalChoice, cls).__new__(cls) |
| 1274 |
|
| 1275 |
def __init__(self, *items: Node): |
| 1276 |
DiagramMultiContainer.__init__(self, "g", items) |
| 1277 |
allButLast = self.items[:-1] |
| 1278 |
middles = self.items[1:-1] |
| 1279 |
first = self.items[0] |
| 1280 |
last = self.items[-1] |
| 1281 |
self.needsSpace = False |
| 1282 |
|
| 1283 |
self.width = ( |
| 1284 |
AR |
| 1285 |
+ AR * 2 * (len(self.items) - 1) |
| 1286 |
+ sum(x.width + (20 if x.needsSpace else 0) for x in self.items) |
| 1287 |
+ (AR if last.height > 0 else 0) |
| 1288 |
+ AR |
| 1289 |
) |
| 1290 |
|
| 1291 |
|
| 1292 |
self.height = 0 |
| 1293 |
|
| 1294 |
|
| 1295 |
self._upperTrack = max(AR * 2, VS, max(x.up for x in allButLast) + VS) |
| 1296 |
self.up = max(self._upperTrack, last.up) |
| 1297 |
|
| 1298 |
|
| 1299 |
|
| 1300 |
self._lowerTrack = max( |
| 1301 |
VS, |
| 1302 |
max(x.height + max(x.down + VS, AR * 2) for x in middles) if middles else 0, |
| 1303 |
last.height + last.down + VS, |
| 1304 |
) |
| 1305 |
if first.height < self._lowerTrack: |
| 1306 |
|
| 1307 |
self._lowerTrack = max(self._lowerTrack, first.height + AR * 2) |
| 1308 |
self.down = max(self._lowerTrack, first.height + first.down) |
| 1309 |
|
| 1310 |
addDebug(self) |
| 1311 |
|
| 1312 |
def format(self, x: float, y: float, width: float) -> HorizontalChoice: |
| 1313 |
|
| 1314 |
leftGap, rightGap = determineGaps(width, self.width) |
| 1315 |
Path(x, y).h(leftGap).addTo(self) |
| 1316 |
Path(x + leftGap + self.width, y + self.height).h(rightGap).addTo(self) |
| 1317 |
x += leftGap |
| 1318 |
|
| 1319 |
first = self.items[0] |
| 1320 |
last = self.items[-1] |
| 1321 |
|
| 1322 |
|
| 1323 |
upperSpan = ( |
| 1324 |
sum(x.width + (20 if x.needsSpace else 0) for x in self.items[:-1]) |
| 1325 |
+ (len(self.items) - 2) * AR * 2 |
| 1326 |
- AR |
| 1327 |
) |
| 1328 |
( |
| 1329 |
Path(x, y) |
| 1330 |
.arc("se") |
| 1331 |
.up(self._upperTrack - AR * 2) |
| 1332 |
.arc("wn") |
| 1333 |
.h(upperSpan) |
| 1334 |
.addTo(self) |
| 1335 |
) |
| 1336 |
|
| 1337 |
|
| 1338 |
lowerSpan = ( |
| 1339 |
sum(x.width + (20 if x.needsSpace else 0) for x in self.items[1:]) |
| 1340 |
+ (len(self.items) - 2) * AR * 2 |
| 1341 |
+ (AR if last.height > 0 else 0) |
| 1342 |
- AR |
| 1343 |
) |
| 1344 |
lowerStart = x + AR + first.width + (20 if first.needsSpace else 0) + AR * 2 |
| 1345 |
( |
| 1346 |
Path(lowerStart, y + self._lowerTrack) |
| 1347 |
.h(lowerSpan) |
| 1348 |
.arc("se") |
| 1349 |
.up(self._lowerTrack - AR * 2) |
| 1350 |
.arc("wn") |
| 1351 |
.addTo(self) |
| 1352 |
) |
| 1353 |
|
| 1354 |
|
| 1355 |
for [i, item] in enumerate(self.items): |
| 1356 |
|
| 1357 |
if i == 0: |
| 1358 |
(Path(x, y).h(AR).addTo(self)) |
| 1359 |
x += AR |
| 1360 |
else: |
| 1361 |
( |
| 1362 |
Path(x, y - self._upperTrack) |
| 1363 |
.arc("ne") |
| 1364 |
.v(self._upperTrack - AR * 2) |
| 1365 |
.arc("ws") |
| 1366 |
.addTo(self) |
| 1367 |
) |
| 1368 |
x += AR * 2 |
| 1369 |
|
| 1370 |
|
| 1371 |
itemWidth = item.width + (20 if item.needsSpace else 0) |
| 1372 |
item.format(x, y, itemWidth).addTo(self) |
| 1373 |
x += itemWidth |
| 1374 |
|
| 1375 |
|
| 1376 |
if i == len(self.items) - 1: |
| 1377 |
if item.height == 0: |
| 1378 |
(Path(x, y).h(AR).addTo(self)) |
| 1379 |
else: |
| 1380 |
(Path(x, y + item.height).arc("se").addTo(self)) |
| 1381 |
elif i == 0 and item.height > self._lowerTrack: |
| 1382 |
|
| 1383 |
if item.height - self._lowerTrack >= AR * 2: |
| 1384 |
( |
| 1385 |
Path(x, y + item.height) |
| 1386 |
.arc("se") |
| 1387 |
.v(self._lowerTrack - item.height + AR * 2) |
| 1388 |
.arc("wn") |
| 1389 |
.addTo(self) |
| 1390 |
) |
| 1391 |
else: |
| 1392 |
|
| 1393 |
|
| 1394 |
( |
| 1395 |
Path(x, y + item.height) |
| 1396 |
.l(AR * 2, self._lowerTrack - item.height) |
| 1397 |
.addTo(self) |
| 1398 |
) |
| 1399 |
else: |
| 1400 |
( |
| 1401 |
Path(x, y + item.height) |
| 1402 |
.arc("ne") |
| 1403 |
.v(self._lowerTrack - item.height - AR * 2) |
| 1404 |
.arc("ws") |
| 1405 |
.addTo(self) |
| 1406 |
) |
| 1407 |
return self |
| 1408 |
|
| 1409 |
def __repr__(self) -> str: |
| 1410 |
items = ", ".join(repr(item) for item in self.items) |
| 1411 |
return f"HorizontalChoice({items})" |
| 1412 |
|
| 1413 |
def textDiagram(self) -> TextDiagram: |
| 1414 |
line, line_vertical, roundcorner_bot_left, roundcorner_bot_right, roundcorner_top_left, roundcorner_top_right = TextDiagram._getParts(["line", "line_vertical", "roundcorner_bot_left", "roundcorner_bot_right", "roundcorner_top_left", "roundcorner_top_right"]) |
| 1415 |
|
| 1416 |
|
| 1417 |
itemTDs = [] |
| 1418 |
for item in self.items: |
| 1419 |
itemTDs.append(item.textDiagram()) |
| 1420 |
|
| 1421 |
diagramEntry = max([itemTD.entry for itemTD in itemTDs]) |
| 1422 |
|
| 1423 |
SOILToBaseline = max([itemTD.entry for itemTD in itemTDs[:-1]]) |
| 1424 |
|
| 1425 |
topToSOIL = diagramEntry - SOILToBaseline |
| 1426 |
|
| 1427 |
baselineToSUIL = max([itemTD.height - min(itemTD.entry, itemTD.exit) for itemTD in itemTDs[1:]]) - 1 |
| 1428 |
|
| 1429 |
|
| 1430 |
lines = [" " * 2] * topToSOIL |
| 1431 |
lines += [roundcorner_top_left + line] |
| 1432 |
lines += [line_vertical + " "] * SOILToBaseline |
| 1433 |
lines += [roundcorner_bot_right + line] |
| 1434 |
diagramTD = TextDiagram(len(lines) - 1, len(lines) - 1, lines) |
| 1435 |
for itemNum, itemTD in enumerate(itemTDs): |
| 1436 |
if itemNum > 0: |
| 1437 |
|
| 1438 |
|
| 1439 |
lines = [] |
| 1440 |
lines += [" " * 2] * topToSOIL |
| 1441 |
|
| 1442 |
lineToNextItem = " " if itemNum == len(itemTDs) - 1 else line |
| 1443 |
lines += [roundcorner_top_right + lineToNextItem] |
| 1444 |
lines += [line_vertical + " "] * SOILToBaseline |
| 1445 |
lines += [roundcorner_bot_left + line] |
| 1446 |
lines += [" " * 2] * baselineToSUIL |
| 1447 |
lines += [line * 2] |
| 1448 |
entryTD = TextDiagram(diagramTD.exit, diagramTD.exit, lines) |
| 1449 |
diagramTD = diagramTD.appendRight(entryTD, "") |
| 1450 |
partTD = TextDiagram(0, 0, []) |
| 1451 |
if itemNum < len(itemTDs) - 1: |
| 1452 |
|
| 1453 |
|
| 1454 |
lines = [] |
| 1455 |
lines += [line * itemTD.width] |
| 1456 |
lines += [" " * itemTD.width] * (SOILToBaseline - itemTD.entry) |
| 1457 |
SOILSegment = TextDiagram(0, 0, lines) |
| 1458 |
partTD = partTD.appendBelow(SOILSegment, []) |
| 1459 |
partTD = partTD.appendBelow(itemTD, [], moveEntry=True, moveExit=True) |
| 1460 |
if itemNum > 0: |
| 1461 |
|
| 1462 |
|
| 1463 |
lines = [] |
| 1464 |
lines += [" " * itemTD.width] * (baselineToSUIL - (itemTD.height - itemTD.entry) + 1) |
| 1465 |
lines += [line * itemTD.width] |
| 1466 |
SUILSegment = TextDiagram(0, 0, lines) |
| 1467 |
partTD = partTD.appendBelow(SUILSegment, []) |
| 1468 |
diagramTD = diagramTD.appendRight(partTD, "") |
| 1469 |
if itemNum < len(itemTDs) - 1: |
| 1470 |
|
| 1471 |
|
| 1472 |
lines = [] |
| 1473 |
lines += [" " * 2] * topToSOIL |
| 1474 |
lines += [line * 2] |
| 1475 |
lines += [" " * 2] * (diagramTD.exit - topToSOIL - 1) |
| 1476 |
lines += [line + roundcorner_top_right] |
| 1477 |
lines += [" " + line_vertical] * (baselineToSUIL - (diagramTD.exit - diagramTD.entry)) |
| 1478 |
|
| 1479 |
lineFromPrevItem = line if itemNum > 0 else " " |
| 1480 |
lines += [lineFromPrevItem + roundcorner_bot_left] |
| 1481 |
entry = diagramEntry + 1 + (diagramTD.exit - diagramTD.entry) |
| 1482 |
exitTD = TextDiagram(entry, diagramEntry + 1, lines) |
| 1483 |
diagramTD = diagramTD.appendRight(exitTD, "") |
| 1484 |
else: |
| 1485 |
|
| 1486 |
lines = [] |
| 1487 |
lineFromExit = " " if diagramTD.exit != diagramTD.entry else line |
| 1488 |
lines += [lineFromExit + roundcorner_top_left] |
| 1489 |
lines += [" " + line_vertical] * (diagramTD.exit - diagramTD.entry - 1) |
| 1490 |
if diagramTD.exit != diagramTD.entry: |
| 1491 |
lines += [line + roundcorner_bot_right] |
| 1492 |
lines += [" " + line_vertical] * (baselineToSUIL - (diagramTD.exit - diagramTD.entry)) |
| 1493 |
lines += [line + roundcorner_bot_right] |
| 1494 |
exitTD = TextDiagram(diagramTD.exit - diagramTD.entry, 0, lines) |
| 1495 |
diagramTD = diagramTD.appendRight(exitTD, "") |
| 1496 |
return diagramTD |
| 1497 |
|
| 1498 |
|
| 1499 |
def Optional(item: Node, skip: bool = False) -> Choice: |
| 1500 |
return Choice(0 if skip else 1, Skip(), item) |
| 1501 |
|
| 1502 |
|
| 1503 |
class OneOrMore(DiagramItem): |
| 1504 |
def __init__(self, item: Node, repeat: Opt[Node] = None): |
| 1505 |
DiagramItem.__init__(self, "g") |
| 1506 |
self.item = wrapString(item) |
| 1507 |
repeat = repeat or Skip() |
| 1508 |
self.rep = wrapString(repeat) |
| 1509 |
self.width = max(self.item.width, self.rep.width) + AR * 2 |
| 1510 |
self.height = self.item.height |
| 1511 |
self.up = self.item.up |
| 1512 |
self.down = max( |
| 1513 |
AR * 2, self.item.down + VS + self.rep.up + self.rep.height + self.rep.down |
| 1514 |
) |
| 1515 |
self.needsSpace = True |
| 1516 |
addDebug(self) |
| 1517 |
|
| 1518 |
def format(self, x: float, y: float, width: float) -> OneOrMore: |
| 1519 |
leftGap, rightGap = determineGaps(width, self.width) |
| 1520 |
|
| 1521 |
|
| 1522 |
Path(x, y).h(leftGap).addTo(self) |
| 1523 |
Path(x + leftGap + self.width, y + self.height).h(rightGap).addTo(self) |
| 1524 |
x += leftGap |
| 1525 |
|
| 1526 |
|
| 1527 |
Path(x, y).right(AR).addTo(self) |
| 1528 |
self.item.format(x + AR, y, self.width - AR * 2).addTo(self) |
| 1529 |
Path(x + self.width - AR, y + self.height).right(AR).addTo(self) |
| 1530 |
|
| 1531 |
|
| 1532 |
distanceFromY = max( |
| 1533 |
AR * 2, self.item.height + self.item.down + VS + self.rep.up |
| 1534 |
) |
| 1535 |
Path(x + AR, y).arc("nw").down(distanceFromY - AR * 2).arc("ws").addTo(self) |
| 1536 |
self.rep.format(x + AR, y + distanceFromY, self.width - AR * 2).addTo(self) |
| 1537 |
Path(x + self.width - AR, y + distanceFromY + self.rep.height).arc("se").up( |
| 1538 |
distanceFromY - AR * 2 + self.rep.height - self.item.height |
| 1539 |
).arc("en").addTo(self) |
| 1540 |
|
| 1541 |
return self |
| 1542 |
|
| 1543 |
def textDiagram(self) -> TextDiagram: |
| 1544 |
line, repeat_top_left, repeat_left, repeat_bot_left, repeat_top_right, repeat_right, repeat_bot_right = TextDiagram._getParts(["line", "repeat_top_left", "repeat_left", "repeat_bot_left", "repeat_top_right", "repeat_right", "repeat_bot_right"]) |
| 1545 |
|
| 1546 |
itemTD = self.item.textDiagram() |
| 1547 |
repeatTD = self.rep.textDiagram() |
| 1548 |
fIRWidth = TextDiagram._maxWidth(itemTD, repeatTD) |
| 1549 |
repeatTD = repeatTD.expand(0, fIRWidth - repeatTD.width, 0, 0) |
| 1550 |
itemTD = itemTD.expand(0, fIRWidth - itemTD.width, 0, 0) |
| 1551 |
itemAndRepeatTD = itemTD.appendBelow(repeatTD, []) |
| 1552 |
|
| 1553 |
leftLines = [] |
| 1554 |
leftLines += [repeat_top_left + line] |
| 1555 |
leftLines += [repeat_left + " "] * ((itemTD.height - itemTD.entry) + repeatTD.entry - 1) |
| 1556 |
leftLines += [repeat_bot_left + line] |
| 1557 |
leftTD = TextDiagram(0, 0, leftLines) |
| 1558 |
leftTD = leftTD.appendRight(itemAndRepeatTD, "") |
| 1559 |
|
| 1560 |
rightLines = [] |
| 1561 |
rightLines += [line + repeat_top_right] |
| 1562 |
rightLines += [" " + repeat_right] * ((itemTD.height - itemTD.exit) + repeatTD.exit - 1) |
| 1563 |
rightLines += [line + repeat_bot_right] |
| 1564 |
rightTD = TextDiagram(0, 0, rightLines) |
| 1565 |
diagramTD = leftTD.appendRight(rightTD, "") |
| 1566 |
return diagramTD |
| 1567 |
|
| 1568 |
def walk(self, cb: WalkerF) -> None: |
| 1569 |
cb(self) |
| 1570 |
self.item.walk(cb) |
| 1571 |
self.rep.walk(cb) |
| 1572 |
|
| 1573 |
def __repr__(self) -> str: |
| 1574 |
return f"OneOrMore({repr(self.item)}, repeat={repr(self.rep)})" |
| 1575 |
|
| 1576 |
|
| 1577 |
def ZeroOrMore(item: Node, repeat: Opt[Node] = None, skip: bool = False) -> Choice: |
| 1578 |
result = Optional(OneOrMore(item, repeat), skip) |
| 1579 |
return result |
| 1580 |
|
| 1581 |
|
| 1582 |
class Group(DiagramItem): |
| 1583 |
def __init__(self, item: Node, label: Opt[Node] = None): |
| 1584 |
DiagramItem.__init__(self, "g") |
| 1585 |
self.item = wrapString(item) |
| 1586 |
self.label: Opt[DiagramItem] |
| 1587 |
if isinstance(label, DiagramItem): |
| 1588 |
self.label = label |
| 1589 |
elif label: |
| 1590 |
self.label = Comment(label) |
| 1591 |
else: |
| 1592 |
self.label = None |
| 1593 |
|
| 1594 |
self.width = max( |
| 1595 |
self.item.width + (20 if self.item.needsSpace else 0), |
| 1596 |
self.label.width if self.label else 0, |
| 1597 |
AR * 2, |
| 1598 |
) |
| 1599 |
self.height = self.item.height |
| 1600 |
self.boxUp = max(self.item.up + VS, AR) |
| 1601 |
self.up = self.boxUp |
| 1602 |
if self.label: |
| 1603 |
self.up += self.label.up + self.label.height + self.label.down |
| 1604 |
self.down = max(self.item.down + VS, AR) |
| 1605 |
self.needsSpace = True |
| 1606 |
addDebug(self) |
| 1607 |
|
| 1608 |
def format(self, x: float, y: float, width: float) -> Group: |
| 1609 |
leftGap, rightGap = determineGaps(width, self.width) |
| 1610 |
Path(x, y).h(leftGap).addTo(self) |
| 1611 |
Path(x + leftGap + self.width, y + self.height).h(rightGap).addTo(self) |
| 1612 |
x += leftGap |
| 1613 |
|
| 1614 |
DiagramItem( |
| 1615 |
"rect", |
| 1616 |
{ |
| 1617 |
"x": x, |
| 1618 |
"y": y - self.boxUp, |
| 1619 |
"width": self.width, |
| 1620 |
"height": self.boxUp + self.height + self.down, |
| 1621 |
"rx": AR, |
| 1622 |
"ry": AR, |
| 1623 |
"class": "group-box", |
| 1624 |
}, |
| 1625 |
).addTo(self) |
| 1626 |
|
| 1627 |
self.item.format(x, y, self.width).addTo(self) |
| 1628 |
if self.label: |
| 1629 |
self.label.format( |
| 1630 |
x, |
| 1631 |
y - (self.boxUp + self.label.down + self.label.height), |
| 1632 |
self.label.width, |
| 1633 |
).addTo(self) |
| 1634 |
|
| 1635 |
return self |
| 1636 |
|
| 1637 |
def textDiagram(self) -> TextDiagram: |
| 1638 |
diagramTD = TextDiagram.roundrect(self.item.textDiagram(), dashed=True) |
| 1639 |
if self.label: |
| 1640 |
labelTD = self.label.textDiagram() |
| 1641 |
diagramTD = labelTD.appendBelow(diagramTD, [], moveEntry=True, moveExit=True).expand(0, 0, 1, 0) |
| 1642 |
return diagramTD |
| 1643 |
|
| 1644 |
def walk(self, cb: WalkerF) -> None: |
| 1645 |
cb(self) |
| 1646 |
self.item.walk(cb) |
| 1647 |
if self.label: |
| 1648 |
self.label.walk(cb) |
| 1649 |
|
| 1650 |
def __repr__(self) -> str: |
| 1651 |
return f"Group({repr(self.item)}, label={repr(self.label)})" |
| 1652 |
|
| 1653 |
|
| 1654 |
class Start(DiagramItem): |
| 1655 |
def __init__(self, type: str = "simple", label: Opt[str] = None): |
| 1656 |
DiagramItem.__init__(self, "g") |
| 1657 |
if label: |
| 1658 |
self.width = max(20, len(label) * CHAR_WIDTH + 10) |
| 1659 |
else: |
| 1660 |
self.width = 20 |
| 1661 |
self.up = 10 |
| 1662 |
self.down = 10 |
| 1663 |
self.type = type |
| 1664 |
self.label = label |
| 1665 |
addDebug(self) |
| 1666 |
|
| 1667 |
def format(self, x: float, y: float, width: float) -> Start: |
| 1668 |
path = Path(x, y - 10) |
| 1669 |
if self.type == "complex": |
| 1670 |
path.down(20).m(0, -10).right(self.width).addTo(self) |
| 1671 |
else: |
| 1672 |
path.down(20).m(10, -20).down(20).m(-10, -10).right(self.width).addTo(self) |
| 1673 |
if self.label: |
| 1674 |
DiagramItem( |
| 1675 |
"text", |
| 1676 |
attrs={"x": x, "y": y - 15, "style": "text-anchor:start"}, |
| 1677 |
text=self.label, |
| 1678 |
).addTo(self) |
| 1679 |
return self |
| 1680 |
|
| 1681 |
def textDiagram(self) -> TextDiagram: |
| 1682 |
cross, line, tee_right = TextDiagram._getParts(["cross", "line", "tee_right"]) |
| 1683 |
if self.type == "simple": |
| 1684 |
start = tee_right + cross + line |
| 1685 |
else: |
| 1686 |
start = tee_right + line |
| 1687 |
labelTD = TextDiagram(0, 0, []) |
| 1688 |
if self.label: |
| 1689 |
labelTD = TextDiagram(0, 0, [self.label]) |
| 1690 |
start = TextDiagram._padR(start, labelTD.width, line) |
| 1691 |
startTD = TextDiagram(0, 0, [start]) |
| 1692 |
return labelTD.appendBelow(startTD, [], moveEntry=True, moveExit=True) |
| 1693 |
|
| 1694 |
def __repr__(self) -> str: |
| 1695 |
return f"Start(type={repr(self.type)}, label={repr(self.label)})" |
| 1696 |
|
| 1697 |
|
| 1698 |
class End(DiagramItem): |
| 1699 |
def __init__(self, type: str = "simple"): |
| 1700 |
DiagramItem.__init__(self, "path") |
| 1701 |
self.width = 20 |
| 1702 |
self.up = 10 |
| 1703 |
self.down = 10 |
| 1704 |
self.type = type |
| 1705 |
addDebug(self) |
| 1706 |
|
| 1707 |
def format(self, x: float, y: float, width: float) -> End: |
| 1708 |
if self.type == "simple": |
| 1709 |
self.attrs["d"] = "M {0} {1} h 20 m -10 -10 v 20 m 10 -20 v 20".format(x, y) |
| 1710 |
elif self.type == "complex": |
| 1711 |
self.attrs["d"] = "M {0} {1} h 20 m 0 -10 v 20".format(x, y) |
| 1712 |
return self |
| 1713 |
|
| 1714 |
def textDiagram(self) -> TextDiagram: |
| 1715 |
cross, line, tee_left = TextDiagram._getParts(["cross", "line", "tee_left"]) |
| 1716 |
if self.type == "simple": |
| 1717 |
end = line + cross + tee_left |
| 1718 |
else: |
| 1719 |
end = line + tee_left |
| 1720 |
return TextDiagram(0, 0, [end]) |
| 1721 |
|
| 1722 |
def __repr__(self) -> str: |
| 1723 |
return f"End(type={repr(self.type)})" |
| 1724 |
|
| 1725 |
|
| 1726 |
class Terminal(DiagramItem): |
| 1727 |
def __init__( |
| 1728 |
self, text: str, href: Opt[str] = None, title: Opt[str] = None, cls: str = "" |
| 1729 |
): |
| 1730 |
DiagramItem.__init__(self, "g", {"class": " ".join(["terminal", cls])}) |
| 1731 |
self.text = text |
| 1732 |
self.href = href |
| 1733 |
self.title = title |
| 1734 |
self.cls = cls |
| 1735 |
self.width = len(text) * CHAR_WIDTH + 20 |
| 1736 |
self.up = 11 |
| 1737 |
self.down = 11 |
| 1738 |
self.needsSpace = True |
| 1739 |
addDebug(self) |
| 1740 |
|
| 1741 |
def __repr__(self) -> str: |
| 1742 |
return f"Terminal({repr(self.text)}, href={repr(self.href)}, title={repr(self.title)}, cls={repr(self.cls)})" |
| 1743 |
|
| 1744 |
def format(self, x: float, y: float, width: float) -> Terminal: |
| 1745 |
leftGap, rightGap = determineGaps(width, self.width) |
| 1746 |
|
| 1747 |
|
| 1748 |
Path(x, y).h(leftGap).addTo(self) |
| 1749 |
Path(x + leftGap + self.width, y).h(rightGap).addTo(self) |
| 1750 |
|
| 1751 |
DiagramItem( |
| 1752 |
"rect", |
| 1753 |
{ |
| 1754 |
"x": x + leftGap, |
| 1755 |
"y": y - 11, |
| 1756 |
"width": self.width, |
| 1757 |
"height": self.up + self.down, |
| 1758 |
"rx": 10, |
| 1759 |
"ry": 10, |
| 1760 |
}, |
| 1761 |
).addTo(self) |
| 1762 |
text = DiagramItem( |
| 1763 |
"text", {"x": x + leftGap + self.width / 2, "y": y + 4}, self.text |
| 1764 |
) |
| 1765 |
if self.href is not None: |
| 1766 |
a = DiagramItem("a", {"xlink:href": self.href}, text).addTo(self) |
| 1767 |
text.addTo(a) |
| 1768 |
else: |
| 1769 |
text.addTo(self) |
| 1770 |
if self.title is not None: |
| 1771 |
DiagramItem("title", {}, self.title).addTo(self) |
| 1772 |
return self |
| 1773 |
|
| 1774 |
def textDiagram(self) -> TextDiagram: |
| 1775 |
|
| 1776 |
return TextDiagram.roundrect(self.text) |
| 1777 |
|
| 1778 |
|
| 1779 |
class NonTerminal(DiagramItem): |
| 1780 |
def __init__( |
| 1781 |
self, text: str, href: Opt[str] = None, title: Opt[str] = None, cls: str = "" |
| 1782 |
): |
| 1783 |
DiagramItem.__init__(self, "g", {"class": " ".join(["non-terminal", cls])}) |
| 1784 |
self.text = text |
| 1785 |
self.href = href |
| 1786 |
self.title = title |
| 1787 |
self.cls = cls |
| 1788 |
self.width = len(text) * CHAR_WIDTH + 20 |
| 1789 |
self.up = 11 |
| 1790 |
self.down = 11 |
| 1791 |
self.needsSpace = True |
| 1792 |
addDebug(self) |
| 1793 |
|
| 1794 |
def __repr__(self) -> str: |
| 1795 |
return f"NonTerminal({repr(self.text)}, href={repr(self.href)}, title={repr(self.title)}, cls={repr(self.cls)})" |
| 1796 |
|
| 1797 |
def format(self, x: float, y: float, width: float) -> NonTerminal: |
| 1798 |
leftGap, rightGap = determineGaps(width, self.width) |
| 1799 |
|
| 1800 |
|
| 1801 |
Path(x, y).h(leftGap).addTo(self) |
| 1802 |
Path(x + leftGap + self.width, y).h(rightGap).addTo(self) |
| 1803 |
|
| 1804 |
DiagramItem( |
| 1805 |
"rect", |
| 1806 |
{ |
| 1807 |
"x": x + leftGap, |
| 1808 |
"y": y - 11, |
| 1809 |
"width": self.width, |
| 1810 |
"height": self.up + self.down, |
| 1811 |
}, |
| 1812 |
).addTo(self) |
| 1813 |
text = DiagramItem( |
| 1814 |
"text", {"x": x + leftGap + self.width / 2, "y": y + 4}, self.text |
| 1815 |
) |
| 1816 |
if self.href is not None: |
| 1817 |
a = DiagramItem("a", {"xlink:href": self.href}, text).addTo(self) |
| 1818 |
text.addTo(a) |
| 1819 |
else: |
| 1820 |
text.addTo(self) |
| 1821 |
if self.title is not None: |
| 1822 |
DiagramItem("title", {}, self.title).addTo(self) |
| 1823 |
return self |
| 1824 |
|
| 1825 |
def textDiagram(self) -> TextDiagram: |
| 1826 |
|
| 1827 |
return TextDiagram.rect(self.text) |
| 1828 |
|
| 1829 |
|
| 1830 |
class Comment(DiagramItem): |
| 1831 |
def __init__( |
| 1832 |
self, text: str, href: Opt[str] = None, title: Opt[str] = None, cls: str = "" |
| 1833 |
): |
| 1834 |
DiagramItem.__init__(self, "g", {"class": " ".join(["non-terminal", cls])}) |
| 1835 |
self.text = text |
| 1836 |
self.href = href |
| 1837 |
self.title = title |
| 1838 |
self.cls = cls |
| 1839 |
self.width = len(text) * COMMENT_CHAR_WIDTH + 10 |
| 1840 |
self.up = 8 |
| 1841 |
self.down = 8 |
| 1842 |
self.needsSpace = True |
| 1843 |
addDebug(self) |
| 1844 |
|
| 1845 |
def __repr__(self) -> str: |
| 1846 |
return f"Comment({repr(self.text)}, href={repr(self.href)}, title={repr(self.title)}, cls={repr(self.cls)})" |
| 1847 |
|
| 1848 |
def format(self, x: float, y: float, width: float) -> Comment: |
| 1849 |
leftGap, rightGap = determineGaps(width, self.width) |
| 1850 |
|
| 1851 |
|
| 1852 |
Path(x, y).h(leftGap).addTo(self) |
| 1853 |
Path(x + leftGap + self.width, y).h(rightGap).addTo(self) |
| 1854 |
|
| 1855 |
text = DiagramItem( |
| 1856 |
"text", |
| 1857 |
{"x": x + leftGap + self.width / 2, "y": y + 5, "class": "comment"}, |
| 1858 |
self.text, |
| 1859 |
) |
| 1860 |
if self.href is not None: |
| 1861 |
a = DiagramItem("a", {"xlink:href": self.href}, text).addTo(self) |
| 1862 |
text.addTo(a) |
| 1863 |
else: |
| 1864 |
text.addTo(self) |
| 1865 |
if self.title is not None: |
| 1866 |
DiagramItem("title", {}, self.title).addTo(self) |
| 1867 |
return self |
| 1868 |
|
| 1869 |
def textDiagram(self) -> TextDiagram: |
| 1870 |
|
| 1871 |
return TextDiagram(0, 0, [self.text]) |
| 1872 |
|
| 1873 |
|
| 1874 |
class Skip(DiagramItem): |
| 1875 |
def __init__(self) -> None: |
| 1876 |
DiagramItem.__init__(self, "g") |
| 1877 |
self.width = 0 |
| 1878 |
self.up = 0 |
| 1879 |
self.down = 0 |
| 1880 |
addDebug(self) |
| 1881 |
|
| 1882 |
def format(self, x: float, y: float, width: float) -> Skip: |
| 1883 |
Path(x, y).right(width).addTo(self) |
| 1884 |
return self |
| 1885 |
|
| 1886 |
def textDiagram(self) -> TextDiagram: |
| 1887 |
(line,) = TextDiagram._getParts(["line"]) |
| 1888 |
return TextDiagram(0, 0, [line]) |
| 1889 |
|
| 1890 |
def __repr__(self) -> str: |
| 1891 |
return "Skip()" |
| 1892 |
|
| 1893 |
|
| 1894 |
class TextDiagram: |
| 1895 |
|
| 1896 |
parts: Dict[str, str] |
| 1897 |
|
| 1898 |
def __init__(self, entry: int, exit: int, lines: List[str]) -> TextDiagram: |
| 1899 |
|
| 1900 |
self.entry: int = entry |
| 1901 |
|
| 1902 |
self.exit: int = exit |
| 1903 |
|
| 1904 |
self.height: int = len(lines) |
| 1905 |
|
| 1906 |
self.lines: List[str] = lines.copy() |
| 1907 |
|
| 1908 |
self.width: int = len(lines[0]) if len(lines) > 0 else 0 |
| 1909 |
nl = "\n" |
| 1910 |
assert entry <= len(lines), f"Entry is not within diagram vertically:{nl}{self._dump(False)}" |
| 1911 |
assert exit <= len(lines), f"Exit is not within diagram vertically:{nl}{self._dump(False)}" |
| 1912 |
for i in range(0, len(lines)): |
| 1913 |
assert len(lines[0]) == len(lines[i]), f"Diagram data is not rectangular:{nl}{self._dump(False)}" |
| 1914 |
|
| 1915 |
def alter(self, entry: int = None, exit: int = None, lines: List[str] = None) -> TextDiagram: |
| 1916 |
""" |
| 1917 |
Create and return a new TextDiagram based on this instance, with the specified changes. |
| 1918 |
|
| 1919 |
Note: This is used sparingly, and may be a bad idea. |
| 1920 |
""" |
| 1921 |
newEntry = entry or self.entry |
| 1922 |
newExit = exit or self.exit |
| 1923 |
newLines = lines or self.lines |
| 1924 |
return self.__class__(newEntry, newExit, newLines.copy()) |
| 1925 |
|
| 1926 |
def appendBelow(self, item: TextDiagram, linesBetween: List[str], moveEntry=False, moveExit=False) -> TextDiagram: |
| 1927 |
""" |
| 1928 |
Create and return a new TextDiagram by appending the specified lines below this instance's data, |
| 1929 |
and then appending the specified TextDiagram below those lines, possibly setting the resulting |
| 1930 |
TextDiagram's entry and or exit indices to those of the appended item. |
| 1931 |
""" |
| 1932 |
newWidth = max(self.width, item.width) |
| 1933 |
newLines = [] |
| 1934 |
newLines += self.center(newWidth, " ").lines |
| 1935 |
for line in linesBetween: |
| 1936 |
newLines += [TextDiagram._padR(line, newWidth, " ")] |
| 1937 |
newLines += item.center(newWidth, " ").lines |
| 1938 |
newEntry = self.height + len(linesBetween) + item.entry if moveEntry else self.entry |
| 1939 |
newExit = self.height + len(linesBetween) + item.exit if moveExit else self.exit |
| 1940 |
newSelf = self.__class__(newEntry, newExit, newLines) |
| 1941 |
return newSelf |
| 1942 |
|
| 1943 |
def appendRight(self, item: TextDiagram, charsBetween: str) -> TextDiagram: |
| 1944 |
""" |
| 1945 |
Create and return a new TextDiagram by appending the specified TextDiagram to the right of this instance's data, |
| 1946 |
aligning the left-hand exit and the right-hand entry points. The charsBetween are inserted between the left-exit |
| 1947 |
and right-entry, and equivalent spaces on all other lines. |
| 1948 |
""" |
| 1949 |
joinLine = max(self.exit, item.entry) |
| 1950 |
newHeight = max(self.height - self.exit, item.height - item.entry) + joinLine |
| 1951 |
leftTopAdd = joinLine - self.exit |
| 1952 |
leftBotAdd = newHeight - self.height - leftTopAdd |
| 1953 |
rightTopAdd = joinLine - item.entry |
| 1954 |
rightBotAdd = newHeight - item.height - rightTopAdd |
| 1955 |
left = self.expand(0, 0, leftTopAdd, leftBotAdd) |
| 1956 |
right = item.expand(0, 0, rightTopAdd, rightBotAdd) |
| 1957 |
newLines = [] |
| 1958 |
for i in range(0, newHeight): |
| 1959 |
sep = " " * len(charsBetween) if i != joinLine else charsBetween |
| 1960 |
newLines += [(left.lines[i] + sep + right.lines[i])] |
| 1961 |
newEntry = self.entry + leftTopAdd |
| 1962 |
newExit = item.exit + rightTopAdd |
| 1963 |
return self.__class__(newEntry, newExit, newLines) |
| 1964 |
|
| 1965 |
def center(self, width: int, pad: str) -> TextDiagram: |
| 1966 |
""" |
| 1967 |
Create and return a new TextDiagram by centering the data of this instance within a new, equal or larger widtth. |
| 1968 |
""" |
| 1969 |
assert width >= self.width, "Cannot center into smaller width" |
| 1970 |
if width == self.width: |
| 1971 |
return self.copy() |
| 1972 |
else: |
| 1973 |
total_padding = width - self.width |
| 1974 |
leftWidth = total_padding // 2 |
| 1975 |
left = [(pad * leftWidth)] * self.height |
| 1976 |
right = [(pad * (total_padding - leftWidth))] * self.height |
| 1977 |
return self.__class__(self.entry, self.exit, TextDiagram._encloseLines(self.lines, left, right)) |
| 1978 |
|
| 1979 |
def copy(self) -> TextDiagram: |
| 1980 |
""" |
| 1981 |
Create and return a new TextDiagram by copying this instance's data. |
| 1982 |
""" |
| 1983 |
return self.__class__(self.entry, self.exit, self.lines.copy()) |
| 1984 |
|
| 1985 |
def expand(self, left: int, right: int, top: int, bottom: int) -> TextDiagram: |
| 1986 |
""" |
| 1987 |
Create and return a new TextDiagram by expanding this instance's data by the specified amount in the specified directions. |
| 1988 |
""" |
| 1989 |
assert left >= 0 |
| 1990 |
assert right >= 0 |
| 1991 |
assert top >= 0 |
| 1992 |
assert bottom >= 0 |
| 1993 |
if left + right + top + bottom == 0: |
| 1994 |
return self.copy() |
| 1995 |
else: |
| 1996 |
line = self.parts["line"] |
| 1997 |
newLines = [] |
| 1998 |
newLines += [(" " * (self.width + left + right))] * top |
| 1999 |
for i in range(0, self.height): |
| 2000 |
leftExpansion = line if i == self.entry else " " |
| 2001 |
rightExpansion = line if i == self.exit else " " |
| 2002 |
newLines += [(leftExpansion * left) + self.lines[i] + (rightExpansion * right)] |
| 2003 |
newLines += [(" " * (self.width + left + right))] * bottom |
| 2004 |
return self.__class__(self.entry + top, self.exit + top, newLines) |
| 2005 |
|
| 2006 |
@classmethod |
| 2007 |
def rect(cls, item: Union[str, TextDiagram], dashed=False) -> TextDiagram: |
| 2008 |
""" |
| 2009 |
Create and return a new TextDiagram for a rectangular box. |
| 2010 |
""" |
| 2011 |
return cls._rectish("rect", item, dashed=dashed) |
| 2012 |
|
| 2013 |
@classmethod |
| 2014 |
def roundrect(cls, item: Union[str, TextDiagram], dashed=False) -> TextDiagram: |
| 2015 |
""" |
| 2016 |
Create and return a new TextDiagram for a rectangular box with rounded corners. |
| 2017 |
""" |
| 2018 |
return cls._rectish("roundrect", item, dashed=dashed) |
| 2019 |
|
| 2020 |
@classmethod |
| 2021 |
def setFormatting(cls, characters: Dict[str, str] = None, defaults: Dict[str, str] = None) -> None: |
| 2022 |
""" |
| 2023 |
Set the characters to use for drawing text diagrams. |
| 2024 |
""" |
| 2025 |
if characters is not None: |
| 2026 |
cls.parts = {} |
| 2027 |
if defaults is not None: |
| 2028 |
cls.parts.update(defaults) |
| 2029 |
cls.parts.update(characters) |
| 2030 |
for name in cls.parts: |
| 2031 |
assert len(cls.parts[name]) == 1, f"Text part {name} is more than 1 character: {cls.parts[name]}" |
| 2032 |
|
| 2033 |
def _dump(self, show=True) -> None: |
| 2034 |
""" |
| 2035 |
Dump out the data of this instance for debugging, either displaying or returning it. |
| 2036 |
DO NOT use this for actual work, only for debugging or in assertion output. |
| 2037 |
""" |
| 2038 |
nl = "\n" |
| 2039 |
result = f"height={self.height}; len(lines)={len(self.lines)}" |
| 2040 |
if self.entry > len(self.lines): |
| 2041 |
result += f"; entry outside diagram: entry={self.entry}" |
| 2042 |
if self.exit > len(self.lines): |
| 2043 |
result += f"; exit outside diagram: exit={self.exit}" |
| 2044 |
for y in range(0, max(len(self.lines), self.entry + 1, self.exit + 1)): |
| 2045 |
result = result + f"{nl}[{y:03}]" |
| 2046 |
if y < len(self.lines): |
| 2047 |
result = result + f" '{self.lines[y]}' len={len(self.lines[y])}" |
| 2048 |
if y == self.entry and y == self.exit: |
| 2049 |
result += " <- entry, exit" |
| 2050 |
elif y == self.entry: |
| 2051 |
result += " <- entry" |
| 2052 |
elif y == self.exit: |
| 2053 |
result += " <- exit" |
| 2054 |
if show: |
| 2055 |
print(result) |
| 2056 |
else: |
| 2057 |
return result |
| 2058 |
|
| 2059 |
@classmethod |
| 2060 |
def _encloseLines(cls, lines: List[str], lefts: List[str], rights: List[str]) -> List[str]: |
| 2061 |
""" |
| 2062 |
Join the lefts, lines, and rights arrays together, line-by-line, and return the result. |
| 2063 |
""" |
| 2064 |
assert len(lines) == len(lefts), "All arguments must be the same length" |
| 2065 |
assert len(lines) == len(rights), "All arguments must be the same length" |
| 2066 |
newLines = [] |
| 2067 |
for i in range(0, len(lines)): |
| 2068 |
newLines.append(lefts[i] + lines[i] + rights[i]) |
| 2069 |
return newLines |
| 2070 |
|
| 2071 |
@staticmethod |
| 2072 |
def _gaps(outerWidth: int, innerWidth: int) -> Tuple[int, int]: |
| 2073 |
""" |
| 2074 |
Return the left and right pad spacing based on the alignment configuration setting. |
| 2075 |
""" |
| 2076 |
diff = outerWidth - innerWidth |
| 2077 |
if INTERNAL_ALIGNMENT == "left": |
| 2078 |
return 0, diff |
| 2079 |
elif INTERNAL_ALIGNMENT == "right": |
| 2080 |
return diff, 0 |
| 2081 |
else: |
| 2082 |
left = diff // 2 |
| 2083 |
right = diff - left |
| 2084 |
return left, right |
| 2085 |
|
| 2086 |
@classmethod |
| 2087 |
def _getParts(cls, partNames: List[str]) -> List[str]: |
| 2088 |
""" |
| 2089 |
Return a list of text diagram drawing characters for the specified character names. |
| 2090 |
""" |
| 2091 |
return [cls.parts[name] for name in partNames] |
| 2092 |
|
| 2093 |
@staticmethod |
| 2094 |
def _maxWidth(*args: List[Union[int, str, List[str], TextDiagram]]) -> int: |
| 2095 |
""" |
| 2096 |
Return the maximum width of all of the arguments. |
| 2097 |
""" |
| 2098 |
maxWidth = 0 |
| 2099 |
for arg in args: |
| 2100 |
if isinstance(arg, TextDiagram): |
| 2101 |
width = arg.width |
| 2102 |
elif isinstance(arg, list): |
| 2103 |
width = max([len(e) for e in arg]) |
| 2104 |
elif isinstance(arg, int): |
| 2105 |
width = len(str(arg)) |
| 2106 |
else: |
| 2107 |
width = len(arg) |
| 2108 |
maxWidth = width if width > maxWidth else maxWidth |
| 2109 |
return maxWidth |
| 2110 |
|
| 2111 |
@staticmethod |
| 2112 |
def _padL(string: str, width: int, pad: str) -> str: |
| 2113 |
""" |
| 2114 |
Pad the specified string on the left to the specified width with the specified pad string and return the result. |
| 2115 |
""" |
| 2116 |
assert (width - len(string)) % len(pad) == 0, f"Gap {width - len(string)} must be a multiple of pad string '{pad}'" |
| 2117 |
return (pad * ((width - len(string) // len(pad)))) + string |
| 2118 |
|
| 2119 |
@staticmethod |
| 2120 |
def _padR(string: str, width: int, pad: str) -> str: |
| 2121 |
""" |
| 2122 |
Pad the specified string on the right to the specified width with the specified pad string and return the result. |
| 2123 |
""" |
| 2124 |
assert (width - len(string)) % len(pad) == 0, f"Gap {width - len(string)} must be a multiple of pad string '{pad}'" |
| 2125 |
return string + (pad * ((width - len(string) // len(pad)))) |
| 2126 |
|
| 2127 |
@classmethod |
| 2128 |
def _rectish(cls, rect_type: str, data: TextDiagram, dashed=False) -> TextDiagram: |
| 2129 |
""" |
| 2130 |
Create and return a new TextDiagram for a rectangular box surrounding the specified TextDiagram, using the |
| 2131 |
specified set of drawing characters (i.e., "rect" or "roundrect"), and possibly using dashed lines. |
| 2132 |
""" |
| 2133 |
lineType = "_dashed" if dashed else "" |
| 2134 |
topLeft, ctrLeft, botLeft, topRight, ctrRight, botRight, topHoriz, botHoriz, line, cross = cls._getParts([f"{rect_type}_top_left", f"{rect_type}_left{lineType}", f"{rect_type}_bot_left", f"{rect_type}_top_right", f"{rect_type}_right{lineType}", f"{rect_type}_bot_right", f"{rect_type}_top{lineType}", f"{rect_type}_bot{lineType}", "line", "cross"]) |
| 2135 |
itemWasFormatted = isinstance(data, TextDiagram) |
| 2136 |
if itemWasFormatted: |
| 2137 |
itemTD = data |
| 2138 |
else: |
| 2139 |
itemTD = TextDiagram(0, 0, [data]) |
| 2140 |
|
| 2141 |
lines = [] |
| 2142 |
lines += [(topHoriz * (itemTD.width + 2))] |
| 2143 |
if itemWasFormatted: |
| 2144 |
lines += itemTD.expand(1, 1, 0, 0).lines |
| 2145 |
else: |
| 2146 |
for i in range(0, len(itemTD.lines)): |
| 2147 |
lines += [(" " + itemTD.lines[i] + " ")] |
| 2148 |
lines += [(botHoriz * (itemTD.width + 2))] |
| 2149 |
entry = itemTD.entry + 1 |
| 2150 |
exit = itemTD.exit + 1 |
| 2151 |
leftMaxWidth = cls._maxWidth(topLeft, ctrLeft, botLeft) |
| 2152 |
lefts = [cls._padR(ctrLeft, leftMaxWidth, " ")] * len(lines) |
| 2153 |
lefts[0] = cls._padR(topLeft, leftMaxWidth, topHoriz) |
| 2154 |
lefts[-1] = cls._padR(botLeft, leftMaxWidth, botHoriz) |
| 2155 |
if itemWasFormatted: |
| 2156 |
lefts[entry] = cross |
| 2157 |
rightMaxWidth = cls._maxWidth(topRight, ctrRight, botRight) |
| 2158 |
rights = [cls._padL(ctrRight, rightMaxWidth, " ")] * len(lines) |
| 2159 |
rights[0] = cls._padL(topRight, rightMaxWidth, topHoriz) |
| 2160 |
rights[-1] = cls._padL(botRight, rightMaxWidth, botHoriz) |
| 2161 |
if itemWasFormatted: |
| 2162 |
rights[exit] = cross |
| 2163 |
|
| 2164 |
lines = TextDiagram._encloseLines(lines, lefts, rights) |
| 2165 |
lefts = [" "] * len(lines) |
| 2166 |
lefts[entry] = line |
| 2167 |
rights = [" "] * len(lines) |
| 2168 |
rights[exit] = line |
| 2169 |
lines = TextDiagram._encloseLines(lines, lefts, rights) |
| 2170 |
return cls(entry, exit, lines) |
| 2171 |
|
| 2172 |
def __repr__(self) -> str: |
| 2173 |
return f"TextDiagram({self.entry}, {self.exit}, {self.lines})" |
| 2174 |
|
| 2175 |
|
| 2176 |
|
| 2177 |
|
| 2178 |
PARTS_UNICODE = { |
| 2179 |
"cross_diag" : "\u2573", |
| 2180 |
"corner_bot_left" : "\u2514", |
| 2181 |
"corner_bot_right" : "\u2518", |
| 2182 |
"corner_top_left" : "\u250c", |
| 2183 |
"corner_top_right" : "\u2510", |
| 2184 |
"cross" : "\u253c", |
| 2185 |
"left" : "\u2502", |
| 2186 |
"line" : "\u2500", |
| 2187 |
"line_vertical" : "\u2502", |
| 2188 |
"multi_repeat" : "\u21ba", |
| 2189 |
"rect_bot" : "\u2500", |
| 2190 |
"rect_bot_dashed" : "\u2504", |
| 2191 |
"rect_bot_left" : "\u2514", |
| 2192 |
"rect_bot_right" : "\u2518", |
| 2193 |
"rect_left" : "\u2502", |
| 2194 |
"rect_left_dashed" : "\u2506", |
| 2195 |
"rect_right" : "\u2502", |
| 2196 |
"rect_right_dashed" : "\u2506", |
| 2197 |
"rect_top" : "\u2500", |
| 2198 |
"rect_top_dashed" : "\u2504", |
| 2199 |
"rect_top_left" : "\u250c", |
| 2200 |
"rect_top_right" : "\u2510", |
| 2201 |
"repeat_bot_left" : "\u2570", |
| 2202 |
"repeat_bot_right" : "\u256f", |
| 2203 |
"repeat_left" : "\u2502", |
| 2204 |
"repeat_right" : "\u2502", |
| 2205 |
"repeat_top_left" : "\u256d", |
| 2206 |
"repeat_top_right" : "\u256e", |
| 2207 |
"right" : "\u2502", |
| 2208 |
"roundcorner_bot_left" : "\u2570", |
| 2209 |
"roundcorner_bot_right" : "\u256f", |
| 2210 |
"roundcorner_top_left" : "\u256d", |
| 2211 |
"roundcorner_top_right" : "\u256e", |
| 2212 |
"roundrect_bot" : "\u2500", |
| 2213 |
"roundrect_bot_dashed" : "\u2504", |
| 2214 |
"roundrect_bot_left" : "\u2570", |
| 2215 |
"roundrect_bot_right" : "\u256f", |
| 2216 |
"roundrect_left" : "\u2502", |
| 2217 |
"roundrect_left_dashed" : "\u2506", |
| 2218 |
"roundrect_right" : "\u2502", |
| 2219 |
"roundrect_right_dashed" : "\u2506", |
| 2220 |
"roundrect_top" : "\u2500", |
| 2221 |
"roundrect_top_dashed" : "\u2504", |
| 2222 |
"roundrect_top_left" : "\u256d", |
| 2223 |
"roundrect_top_right" : "\u256e", |
| 2224 |
"separator" : "\u2500", |
| 2225 |
"tee_left" : "\u2524", |
| 2226 |
"tee_right" : "\u251c", |
| 2227 |
} |
| 2228 |
|
| 2229 |
|
| 2230 |
PARTS_ASCII = { |
| 2231 |
"cross_diag" : "X", |
| 2232 |
"corner_bot_left" : "\\", |
| 2233 |
"corner_bot_right" : "/", |
| 2234 |
"corner_top_left" : "/", |
| 2235 |
"corner_top_right" : "\\", |
| 2236 |
"cross" : "+", |
| 2237 |
"left" : "|", |
| 2238 |
"line" : "-", |
| 2239 |
"line_vertical" : "|", |
| 2240 |
"multi_repeat" : "&", |
| 2241 |
"rect_bot" : "-", |
| 2242 |
"rect_bot_dashed" : "-", |
| 2243 |
"rect_bot_left" : "+", |
| 2244 |
"rect_bot_right" : "+", |
| 2245 |
"rect_left" : "|", |
| 2246 |
"rect_left_dashed" : "|", |
| 2247 |
"rect_right" : "|", |
| 2248 |
"rect_right_dashed" : "|", |
| 2249 |
"rect_top_dashed" : "-", |
| 2250 |
"rect_top" : "-", |
| 2251 |
"rect_top_left" : "+", |
| 2252 |
"rect_top_right" : "+", |
| 2253 |
"repeat_bot_left" : "\\", |
| 2254 |
"repeat_bot_right" : "/", |
| 2255 |
"repeat_left" : "|", |
| 2256 |
"repeat_right" : "|", |
| 2257 |
"repeat_top_left" : "/", |
| 2258 |
"repeat_top_right" : "\\", |
| 2259 |
"right" : "|", |
| 2260 |
"roundcorner_bot_left" : "\\", |
| 2261 |
"roundcorner_bot_right" : "/", |
| 2262 |
"roundcorner_top_left" : "/", |
| 2263 |
"roundcorner_top_right" : "\\", |
| 2264 |
"roundrect_bot" : "-", |
| 2265 |
"roundrect_bot_dashed" : "-", |
| 2266 |
"roundrect_bot_left" : "\\", |
| 2267 |
"roundrect_bot_right" : "/", |
| 2268 |
"roundrect_left" : "|", |
| 2269 |
"roundrect_left_dashed" : "|", |
| 2270 |
"roundrect_right" : "|", |
| 2271 |
"roundrect_right_dashed" : "|", |
| 2272 |
"roundrect_top" : "-", |
| 2273 |
"roundrect_top_dashed" : "-", |
| 2274 |
"roundrect_top_left" : "/", |
| 2275 |
"roundrect_top_right" : "\\", |
| 2276 |
"separator" : "-", |
| 2277 |
"tee_left" : "|", |
| 2278 |
"tee_right" : "|", |
| 2279 |
} |
| 2280 |
|
| 2281 |
|
| 2282 |
|
| 2283 |
TextDiagram.setFormatting(TextDiagram.PARTS_UNICODE) |
| 2284 |
|
| 2285 |
if __name__ == "__main__": |
| 2286 |
|
| 2287 |
if len(sys.argv) < 2 or sys.argv[1] == "": |
| 2288 |
mode = "svg" |
| 2289 |
elif sys.argv[1].lower() in ["svg", "ascii", "unicode", "standalone"]: |
| 2290 |
mode = sys.argv[1].lower() |
| 2291 |
else: |
| 2292 |
raise ValueError(f"Unknown option: {sys.argv[1]}") |
| 2293 |
testList = sys.argv[2:] |
| 2294 |
|
| 2295 |
def add(name: str, diagram: DiagramItem) -> None: |
| 2296 |
if name in testList or len(testList) == 0: |
| 2297 |
sys.stdout.write(f"\n<h1>{escapeHtml(name)}</h1>\n") |
| 2298 |
if mode == "svg": |
| 2299 |
diagram.writeSvg(sys.stdout.write) |
| 2300 |
elif mode == "standalone": |
| 2301 |
diagram.writeStandalone(sys.stdout.write) |
| 2302 |
elif mode in ["ascii", "unicode"]: |
| 2303 |
sys.stdout.write("\n<pre>\n") |
| 2304 |
diagram.writeText(sys.stdout.write) |
| 2305 |
sys.stdout.write("\n</pre>\n") |
| 2306 |
sys.stdout.write("\n") |
| 2307 |
|
| 2308 |
sys.stdout.write("<!doctype html><title>Test</title><body>") |
| 2309 |
if mode == "ascii": |
| 2310 |
TextDiagram.setFormatting(TextDiagram.PARTS_ASCII) |
| 2311 |
elif mode == "unicode": |
| 2312 |
TextDiagram.setFormatting(TextDiagram.PARTS_UNICODE) |
| 2313 |
elif mode in ("svg", "standalone"): |
| 2314 |
sys.stdout.write( |
| 2315 |
f""" |
| 2316 |
<style> |
| 2317 |
{DEFAULT_STYLE} |
| 2318 |
.blue text {{ fill: blue; }} |
| 2319 |
</style> |
| 2320 |
""" |
| 2321 |
) |
| 2322 |
with open("test.py", "r", encoding="utf-8") as fh: |
| 2323 |
exec(fh.read()) |
| 2324 |
sys.stdout.write("</body></html>") |