-
Notifications
You must be signed in to change notification settings - Fork 153
/
railroad.py
2323 lines (2074 loc) · 92 KB
/
railroad.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import annotations
import math as Math
import sys
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import (
Any,
Callable,
Dict,
Generator,
List,
Optional as Opt,
Sequence as Seq,
Tuple,
Type,
TypeVar,
Union,
)
T = TypeVar("T")
Node = Union[str, DiagramItem] # pylint: disable=used-before-assignment
WriterF = Callable[[str], Any]
WalkerF = Callable[[DiagramItem], Any] # pylint: disable=used-before-assignment
AttrsT = Dict[str, Any]
# Display constants
DEBUG = False # if true, writes some debug information into attributes
VS = 8 # minimum vertical separation between things. For a 3px stroke, must be at least 4
AR = 10 # radius of arcs
DIAGRAM_CLASS = "railroad-diagram" # class to put on the root <svg>
STROKE_ODD_PIXEL_LENGTH = (
True # is the stroke width an odd (1px, 3px, etc) pixel length?
)
INTERNAL_ALIGNMENT = (
"center" # how to align items when they have extra space. left/right/center
)
CHAR_WIDTH = 8.5 # width of each monospace character. play until you find the right value for your font
COMMENT_CHAR_WIDTH = 7 # comments are in smaller text by default
ESCAPE_HTML = True # Should Diagram.writeText() produce HTML-escaped text, or raw?
def escapeAttr(val: Union[str, float]) -> str:
if isinstance(val, str):
return val.replace("&", "&").replace("'", "'").replace('"', """)
return f"{val:g}"
def escapeHtml(val: str) -> str:
return escapeAttr(val).replace("<", "<")
def determineGaps(outer: float, inner: float) -> Tuple[float, float]:
diff = outer - inner
if INTERNAL_ALIGNMENT == "left":
return 0, diff
elif INTERNAL_ALIGNMENT == "right":
return diff, 0
else:
return diff / 2, diff / 2
def doubleenumerate(seq: Seq[T]) -> Generator[Tuple[int, int, T], None, None]:
length = len(list(seq))
for i, item in enumerate(seq):
yield i, i - length, item
def addDebug(el: DiagramItem) -> None:
if not DEBUG:
return
el.attrs["data-x"] = "{0} w:{1} h:{2}/{3}/{4}".format(
type(el).__name__, el.width, el.up, el.height, el.down
)
class DiagramItem:
def __init__(self, name: str, attrs: Opt[AttrsT] = None, text: Opt[Node] = None):
self.name = name
# up = distance it projects above the entry line
self.up: float = 0
# height = distance between the entry/exit lines
self.height: float = 0
# down = distance it projects below the exit line
self.down: float = 0
# width = distance between the entry/exit lines horizontally
self.width: float = 0
# Whether the item is okay with being snug against another item or not
self.needsSpace = False
# DiagramItems pull double duty as SVG elements.
self.attrs: AttrsT = attrs or {}
# Subclasses store their meaningful children as .item or .items;
# .children instead stores their formatted SVG nodes.
self.children: List[Union[Node, Path, Style]] = [text] if text else []
def format(self, x: float, y: float, width: float) -> DiagramItem:
raise NotImplementedError # Virtual
def textDiagram() -> TextDiagram:
raise NotImplementedError("Virtual")
def addTo(self, parent: DiagramItem) -> DiagramItem:
parent.children.append(self)
return self
def writeSvg(self, write: WriterF) -> None:
write("<{0}".format(self.name))
for name, value in sorted(self.attrs.items()):
write(' {0}="{1}"'.format(name, escapeAttr(value)))
write(">")
if self.name in ["g", "svg"]:
write("\n")
for child in self.children:
if isinstance(child, (DiagramItem, Path, Style)):
child.writeSvg(write)
else:
write(escapeHtml(child))
write("</{0}>".format(self.name))
def walk(self, cb: WalkerF) -> None:
cb(self)
def __repr__(self) -> str:
return f"DiagramItem({self.name}, {self.attrs}, {self.children})"
class DiagramMultiContainer(DiagramItem):
def __init__(
self,
name: str,
items: Seq[Node],
attrs: Opt[Dict[str, str]] = None,
text: Opt[str] = None,
):
DiagramItem.__init__(self, name, attrs, text)
self.items: List[DiagramItem] = [wrapString(item) for item in items]
def format(self, x: float, y: float, width: float) -> DiagramItem:
raise NotImplementedError # Virtual
def walk(self, cb: WalkerF) -> None:
cb(self)
for item in self.items:
item.walk(cb)
def __repr__(self) -> str:
return f"DiagramMultiContainer({self.name}, {self.items}. {self.attrs}, {self.children})"
class Path:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
self.attrs = {"d": f"M{x} {y}"}
def m(self, x: float, y: float) -> Path:
self.attrs["d"] += f"m{x} {y}"
return self
def l(self, x: float, y: float) -> Path:
self.attrs["d"] += f"l{x} {y}"
return self
def h(self, val: float) -> Path:
self.attrs["d"] += f"h{val}"
return self
def right(self, val: float) -> Path:
return self.h(max(0, val))
def left(self, val: float) -> Path:
return self.h(-max(0, val))
def v(self, val: float) -> Path:
self.attrs["d"] += f"v{val}"
return self
def down(self, val: float) -> Path:
return self.v(max(0, val))
def up(self, val: float) -> Path:
return self.v(-max(0, val))
def arc_8(self, start: str, dir: str) -> Path:
# 1/8 of a circle
arc = AR
s2 = 1 / Math.sqrt(2) * arc
s2inv = arc - s2
sweep = "1" if dir == "cw" else "0"
path = f"a {arc} {arc} 0 0 {sweep} "
sd = start + dir
offset: List[float]
if sd == "ncw":
offset = [s2, s2inv]
elif sd == "necw":
offset = [s2inv, s2]
elif sd == "ecw":
offset = [-s2inv, s2]
elif sd == "secw":
offset = [-s2, s2inv]
elif sd == "scw":
offset = [-s2, -s2inv]
elif sd == "swcw":
offset = [-s2inv, -s2]
elif sd == "wcw":
offset = [s2inv, -s2]
elif sd == "nwcw":
offset = [s2, -s2inv]
elif sd == "nccw":
offset = [-s2, s2inv]
elif sd == "nwccw":
offset = [-s2inv, s2]
elif sd == "wccw":
offset = [s2inv, s2]
elif sd == "swccw":
offset = [s2, s2inv]
elif sd == "sccw":
offset = [s2, -s2inv]
elif sd == "seccw":
offset = [s2inv, -s2]
elif sd == "eccw":
offset = [-s2inv, -s2]
elif sd == "neccw":
offset = [-s2, -s2inv]
path += " ".join(str(x) for x in offset)
self.attrs["d"] += path
return self
def arc(self, sweep: str) -> Path:
x = AR
y = AR
if sweep[0] == "e" or sweep[1] == "w":
x *= -1
if sweep[0] == "s" or sweep[1] == "n":
y *= -1
cw = 1 if sweep in ("ne", "es", "sw", "wn") else 0
self.attrs["d"] += f"a{AR} {AR} 0 0 {cw} {x} {y}"
return self
def addTo(self, parent: DiagramItem) -> Path:
parent.children.append(self)
return self
def writeSvg(self, write: WriterF) -> None:
write("<path")
for name, value in sorted(self.attrs.items()):
write(f' {name}="{escapeAttr(value)}"')
write(" />")
def format(self) -> Path:
self.attrs["d"] += "h.5"
return self
def textDiagram(self) -> TextDiagram:
return TextDiagram(0, 0, [])
def __repr__(self) -> str:
return f"Path({repr(self.x)}, {repr(self.y)})"
def wrapString(value: Node) -> DiagramItem:
return value if isinstance(value, DiagramItem) else Terminal(value)
DEFAULT_STYLE = """\
svg.railroad-diagram {
background-color:hsl(30,20%,95%);
}
svg.railroad-diagram path {
stroke-width:3;
stroke:black;
fill:rgba(0,0,0,0);
}
svg.railroad-diagram text {
font:bold 14px monospace;
text-anchor:middle;
}
svg.railroad-diagram text.label{
text-anchor:start;
}
svg.railroad-diagram text.comment{
font:italic 12px monospace;
}
svg.railroad-diagram rect{
stroke-width:3;
stroke:black;
fill:hsl(120,100%,90%);
}
svg.railroad-diagram rect.group-box {
stroke: gray;
stroke-dasharray: 10 5;
fill: none;
}
"""
class Style:
def __init__(self, css: str):
self.css = css
def __repr__(self) -> str:
return f"Style({repr(self.css)})"
def addTo(self, parent: DiagramItem) -> Style:
parent.children.append(self)
return self
def format(self) -> Style:
return self
def textDiagram(self) -> TextDiagram:
return TextDiagram(0, 0, [])
def writeSvg(self, write: WriterF) -> None:
# Write included stylesheet as CDATA. See https:#developer.mozilla.org/en-US/docs/Web/SVG/Element/style
cdata = "/* <![CDATA[ */\n{css}\n/* ]]> */\n".format(css=self.css)
write("<style>{cdata}</style>".format(cdata=cdata))
class Diagram(DiagramMultiContainer):
def __init__(self, *items: Node, **kwargs: str):
# Accepts a type=[simple|complex] kwarg
DiagramMultiContainer.__init__(
self,
"svg",
list(items),
{
"class": DIAGRAM_CLASS,
},
)
self.type = kwargs.get("type", "simple")
if items and not isinstance(items[0], Start):
self.items.insert(0, Start(self.type))
if items and not isinstance(items[-1], End):
self.items.append(End(self.type))
self.up = 0
self.down = 0
self.height = 0
self.width = 0
for item in self.items:
if isinstance(item, Style):
continue
self.width += item.width + (20 if item.needsSpace else 0)
self.up = max(self.up, item.up - self.height)
self.height += item.height
self.down = max(self.down - item.height, item.down)
if self.items[0].needsSpace:
self.width -= 10
if self.items[-1].needsSpace:
self.width -= 10
self.formatted = False
def __repr__(self) -> str:
items = ", ".join(map(repr, self.items[1:-1]))
pieces = [] if not items else [items]
if self.type != "simple":
pieces.append(f"type={repr(self.type)}")
return f'Diagram({", ".join(pieces)})'
def format(
self,
paddingTop: float = 20,
paddingRight: Opt[float] = None,
paddingBottom: Opt[float] = None,
paddingLeft: Opt[float] = None,
) -> Diagram:
if paddingRight is None:
paddingRight = paddingTop
if paddingBottom is None:
paddingBottom = paddingTop
if paddingLeft is None:
paddingLeft = paddingRight
assert paddingRight is not None
assert paddingBottom is not None
assert paddingLeft is not None
x = paddingLeft
y = paddingTop + self.up
g = DiagramItem("g")
if STROKE_ODD_PIXEL_LENGTH:
g.attrs["transform"] = "translate(.5 .5)"
for item in self.items:
if item.needsSpace:
Path(x, y).h(10).addTo(g)
x += 10
item.format(x, y, item.width).addTo(g)
x += item.width
y += item.height
if item.needsSpace:
Path(x, y).h(10).addTo(g)
x += 10
self.attrs["width"] = str(self.width + paddingLeft + paddingRight)
self.attrs["height"] = str(
self.up + self.height + self.down + paddingTop + paddingBottom
)
self.attrs["viewBox"] = f"0 0 {self.attrs['width']} {self.attrs['height']}"
g.addTo(self)
self.formatted = True
return self
def textDiagram(self) -> TextDiagram:
(separator, ) = TextDiagram._getParts(["separator"])
diagramTD = self.items[0].textDiagram()
for item in self.items[1:]:
itemTD = item.textDiagram()
if item.needsSpace:
itemTD = itemTD.expand(1, 1, 0, 0)
diagramTD = diagramTD.appendRight(itemTD, separator)
return diagramTD
def writeSvg(self, write: WriterF) -> None:
if not self.formatted:
self.format()
return DiagramItem.writeSvg(self, write)
def writeText(self, write: WriterF) -> None:
output = self.textDiagram()
output = "\n".join(output.lines) + "\n"
if ESCAPE_HTML:
output = output.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
write(output)
def writeStandalone(self, write: WriterF, css: str | None = None) -> None:
if not self.formatted:
self.format()
if css is None:
css = DEFAULT_STYLE
Style(css).addTo(self)
self.attrs["xmlns"] = "http://www.w3.org/2000/svg"
self.attrs['xmlns:xlink'] = "http://www.w3.org/1999/xlink"
DiagramItem.writeSvg(self, write)
self.children.pop()
del self.attrs["xmlns"]
del self.attrs["xmlns:xlink"]
class Sequence(DiagramMultiContainer):
def __init__(self, *items: Node):
DiagramMultiContainer.__init__(self, "g", items)
self.needsSpace = True
self.up = 0
self.down = 0
self.height = 0
self.width = 0
for item in self.items:
self.width += item.width + (20 if item.needsSpace else 0)
self.up = max(self.up, item.up - self.height)
self.height += item.height
self.down = max(self.down - item.height, item.down)
if self.items[0].needsSpace:
self.width -= 10
if self.items[-1].needsSpace:
self.width -= 10
addDebug(self)
def __repr__(self) -> str:
items = ", ".join(repr(item) for item in self.items)
return f"Sequence({items})"
def format(self, x: float, y: float, width: float) -> Sequence:
leftGap, rightGap = determineGaps(width, self.width)
Path(x, y).h(leftGap).addTo(self)
Path(x + leftGap + self.width, y + self.height).h(rightGap).addTo(self)
x += leftGap
for i, item in enumerate(self.items):
if item.needsSpace and i > 0:
Path(x, y).h(10).addTo(self)
x += 10
item.format(x, y, item.width).addTo(self)
x += item.width
y += item.height
if item.needsSpace and i < len(self.items) - 1:
Path(x, y).h(10).addTo(self)
x += 10
return self
def textDiagram(self) -> TextDiagram:
(separator, ) = TextDiagram._getParts(["separator"])
diagramTD = TextDiagram(0, 0, [""])
for item in self.items:
itemTD = item.textDiagram()
if item.needsSpace:
itemTD = itemTD.expand(1, 1, 0, 0)
diagramTD = diagramTD.appendRight(itemTD, separator)
return diagramTD
class Stack(DiagramMultiContainer):
def __init__(self, *items: Node):
DiagramMultiContainer.__init__(self, "g", items)
self.needsSpace = True
self.width = max(
item.width + (20 if item.needsSpace else 0) for item in self.items
)
# pretty sure that space calc is totes wrong
if len(self.items) > 1:
self.width += AR * 2
self.up = self.items[0].up
self.down = self.items[-1].down
self.height = 0
last = len(self.items) - 1
for i, item in enumerate(self.items):
self.height += item.height
if i > 0:
self.height += max(AR * 2, item.up + VS)
if i < last:
self.height += max(AR * 2, item.down + VS)
addDebug(self)
def __repr__(self) -> str:
items = ", ".join(repr(item) for item in self.items)
return f"Stack({items})"
def format(self, x: float, y: float, width: float) -> Stack:
leftGap, rightGap = determineGaps(width, self.width)
Path(x, y).h(leftGap).addTo(self)
x += leftGap
xInitial = x
if len(self.items) > 1:
Path(x, y).h(AR).addTo(self)
x += AR
innerWidth = self.width - AR * 2
else:
innerWidth = self.width
for i, item in enumerate(self.items):
item.format(x, y, innerWidth).addTo(self)
x += innerWidth
y += item.height
if i != len(self.items) - 1:
(
Path(x, y)
.arc("ne")
.down(max(0, item.down + VS - AR * 2))
.arc("es")
.left(innerWidth)
.arc("nw")
.down(max(0, self.items[i + 1].up + VS - AR * 2))
.arc("ws")
.addTo(self)
)
y += max(item.down + VS, AR * 2) + max(
self.items[i + 1].up + VS, AR * 2
)
x = xInitial + AR
if len(self.items) > 1:
Path(x, y).h(AR).addTo(self)
x += AR
Path(x, y).h(rightGap).addTo(self)
return self
def textDiagram(self) -> TextDiagram:
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"])
# Format all the child items, so we can know the maximum width.
itemTDs = []
for item in self.items:
itemTDs.append(item.textDiagram())
maxWidth = max([itemTD.width for itemTD in itemTDs])
leftLines = []
rightLines = []
separatorTD = TextDiagram(0, 0, [line * maxWidth])
diagramTD = None # Top item will replace it.
for itemNum, itemTD in enumerate(itemTDs):
if itemNum == 0:
# The top item enters directly from its left.
leftLines += [line * 2]
leftLines += [" " * 2] * (itemTD.height - itemTD.entry - 1)
else:
# All items below the top enter from a snake-line from the previous item's exit.
# Here, we resume that line, already having descended from above on the right.
diagramTD = diagramTD.appendBelow(separatorTD, [])
leftLines += [corner_top_left + line]
leftLines += [line_vertical + " "] * (itemTD.entry)
leftLines += [corner_bot_left + line]
leftLines += [" " * 2] * (itemTD.height - itemTD.entry - 1)
rightLines += [" " * 2] * (itemTD.exit)
if itemNum < len(itemTDs) - 1:
# All items above the bottom exit via a snake-line to the next item's entry.
# Here, we start that line on the right.
rightLines += [line + corner_top_right]
rightLines += [" " + line_vertical] * (itemTD.height - itemTD.exit - 1)
rightLines += [line + corner_bot_right]
else:
# The bottom item exits directly to its right.
rightLines += [line * 2]
leftPad, rightPad = TextDiagram._gaps(maxWidth, itemTD.width)
itemTD = itemTD.expand(leftPad, rightPad, 0, 0)
if itemNum == 0:
diagramTD = itemTD
else:
diagramTD = diagramTD.appendBelow(itemTD, [])
leftTD = TextDiagram(0, 0, leftLines)
diagramTD = leftTD.appendRight(diagramTD, "")
rightTD = TextDiagram(0, len(rightLines) - 1, rightLines)
diagramTD = diagramTD.appendRight(rightTD, "")
return diagramTD
class OptionalSequence(DiagramMultiContainer):
def __new__(cls, *items: Node) -> Any:
if len(items) <= 1:
return Sequence(*items)
else:
return super(OptionalSequence, cls).__new__(cls)
def __init__(self, *items: Node):
DiagramMultiContainer.__init__(self, "g", items)
self.needsSpace = False
self.width = 0
self.up = 0
self.height = sum(item.height for item in self.items)
self.down = self.items[0].down
heightSoFar: float = 0
for i, item in enumerate(self.items):
self.up = max(self.up, max(AR * 2, item.up + VS) - heightSoFar)
heightSoFar += item.height
if i > 0:
self.down = (
max(
self.height + self.down,
heightSoFar + max(AR * 2, item.down + VS),
)
- self.height
)
itemWidth = item.width + (10 if item.needsSpace else 0)
if i == 0:
self.width += AR + max(itemWidth, AR)
else:
self.width += AR * 2 + max(itemWidth, AR) + AR
addDebug(self)
def __repr__(self) -> str:
items = ", ".join(repr(item) for item in self.items)
return f"OptionalSequence({items})"
def format(self, x: float, y: float, width: float) -> OptionalSequence:
leftGap, rightGap = determineGaps(width, self.width)
Path(x, y).right(leftGap).addTo(self)
Path(x + leftGap + self.width, y + self.height).right(rightGap).addTo(self)
x += leftGap
upperLineY = y - self.up
last = len(self.items) - 1
for i, item in enumerate(self.items):
itemSpace = 10 if item.needsSpace else 0
itemWidth = item.width + itemSpace
if i == 0:
# Upper skip
(
Path(x, y)
.arc("se")
.up(y - upperLineY - AR * 2)
.arc("wn")
.right(itemWidth - AR)
.arc("ne")
.down(y + item.height - upperLineY - AR * 2)
.arc("ws")
.addTo(self)
)
# Straight line
(Path(x, y).right(itemSpace + AR).addTo(self))
item.format(x + itemSpace + AR, y, item.width).addTo(self)
x += itemWidth + AR
y += item.height
elif i < last:
# Upper skip
(
Path(x, upperLineY)
.right(AR * 2 + max(itemWidth, AR) + AR)
.arc("ne")
.down(y - upperLineY + item.height - AR * 2)
.arc("ws")
.addTo(self)
)
# Straight line
(Path(x, y).right(AR * 2).addTo(self))
item.format(x + AR * 2, y, item.width).addTo(self)
(
Path(x + item.width + AR * 2, y + item.height)
.right(itemSpace + AR)
.addTo(self)
)
# Lower skip
(
Path(x, y)
.arc("ne")
.down(item.height + max(item.down + VS, AR * 2) - AR * 2)
.arc("ws")
.right(itemWidth - AR)
.arc("se")
.up(item.down + VS - AR * 2)
.arc("wn")
.addTo(self)
)
x += AR * 2 + max(itemWidth, AR) + AR
y += item.height
else:
# Straight line
(Path(x, y).right(AR * 2).addTo(self))
item.format(x + AR * 2, y, item.width).addTo(self)
(
Path(x + AR * 2 + item.width, y + item.height)
.right(itemSpace + AR)
.addTo(self)
)
# Lower skip
(
Path(x, y)
.arc("ne")
.down(item.height + max(item.down + VS, AR * 2) - AR * 2)
.arc("ws")
.right(itemWidth - AR)
.arc("se")
.up(item.down + VS - AR * 2)
.arc("wn")
.addTo(self)
)
return self
def textDiagram(self) -> TextDiagram:
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"])
# Format all the child items, so we can know the maximum entry.
itemTDs = []
for item in self.items:
itemTDs.append(item.textDiagram())
# diagramEntry: distance from top to lowest entry, aka distance from top to diagram entry, aka final diagram entry and exit.
diagramEntry = max([itemTD.entry for itemTD in itemTDs])
# SOILHeight: distance from top to lowest entry before rightmost item, aka distance from skip-over-items line to rightmost entry, aka SOIL height.
SOILHeight = max([itemTD.entry for itemTD in itemTDs[:-1]])
# topToSOIL: distance from top to skip-over-items line.
topToSOIL = diagramEntry - SOILHeight
# The diagram starts with a line from its entry up to the skip-over-items line:
lines = [" " * 2] * topToSOIL
lines += [roundcorner_top_left + line]
lines += [line_vertical + " "] * SOILHeight
lines += [roundcorner_bot_right + line]
diagramTD = TextDiagram(len(lines) - 1, len(lines) - 1, lines)
for itemNum, itemTD in enumerate(itemTDs):
if itemNum > 0:
# All items except the leftmost start with a line from their entry down to their skip-under-item line,
# with a joining-line across at the skip-over-items line:
lines = []
lines += [" " * 2] * topToSOIL
lines += [line * 2]
lines += [" " * 2] * (diagramTD.exit - topToSOIL - 1)
lines += [line + roundcorner_top_right]
lines += [" " + line_vertical] * (itemTD.height - itemTD.entry - 1)
lines += [" " + roundcorner_bot_left]
skipDownTD = TextDiagram(diagramTD.exit, diagramTD.exit, lines)
diagramTD = diagramTD.appendRight(skipDownTD, "")
# All items except the leftmost next have a line from skip-over-items line down to their entry,
# with joining-lines at their entry and at their skip-under-item line:
lines = []
lines += [" " * 2] * topToSOIL
# All such items except the rightmost also have a continuation of the skip-over-items line:
lineToNextItem = line if itemNum < len(itemTDs) - 1 else " "
lines += [line + roundcorner_top_right + lineToNextItem]
lines += [" " + line_vertical + " "] * (diagramTD.exit - topToSOIL - 1)
lines += [line + roundcorner_bot_left + line]
lines += [" " * 3] * (itemTD.height - itemTD.entry - 1)
lines += [line * 3]
entryTD = TextDiagram(diagramTD.exit, diagramTD.exit, lines)
diagramTD = diagramTD.appendRight(entryTD, "")
partTD = TextDiagram(0, 0, [])
if itemNum < len(itemTDs) - 1:
# All items except the rightmost have a segment of the skip-over-items line at the top,
# followed by enough blank lines to push their entry down to the previous item's exit:
lines = []
lines += [line * itemTD.width]
lines += [" " * itemTD.width] * (SOILHeight - itemTD.entry)
SOILSegment = TextDiagram(0, 0, lines)
partTD = partTD.appendBelow(SOILSegment, [])
partTD = partTD.appendBelow(itemTD, [], moveEntry=True, moveExit=True)
if itemNum > 0:
# All items except the leftmost have their skip-under-item line at the bottom.
SUILSegment = TextDiagram(0, 0, [line * itemTD.width])
partTD = partTD.appendBelow(SUILSegment, [])
diagramTD = diagramTD.appendRight(partTD, "")
if 0 < itemNum:
# All items except the leftmost have a line from their skip-under-item line to their exit:
lines = []
lines += [" " * 2] * topToSOIL
# All such items except the rightmost also have a joining-line across at the skip-over-items line:
skipOverChar = line if itemNum < len(itemTDs) - 1 else " "
lines += [skipOverChar * 2]
lines += [" " * 2] * (diagramTD.exit - topToSOIL - 1)
lines += [line + roundcorner_top_left]
lines += [" " + line_vertical] * (partTD.height - partTD.exit - 2)
lines += [line + roundcorner_bot_right]
skipUpTD = TextDiagram(diagramTD.exit, diagramTD.exit, lines)
diagramTD = diagramTD.appendRight(skipUpTD, "")
return diagramTD
class AlternatingSequence(DiagramMultiContainer):
def __new__(cls, *items: Node) -> AlternatingSequence:
if len(items) == 2:
return super(AlternatingSequence, cls).__new__(cls)
else:
raise Exception(
"AlternatingSequence takes exactly two arguments, but got {0} arguments.".format(
len(items)
)
)
def __init__(self, *items: Node):
DiagramMultiContainer.__init__(self, "g", items)
self.needsSpace = False
arc = AR
vert = VS
first = self.items[0]
second = self.items[1]
arcX = 1 / Math.sqrt(2) * arc * 2
arcY = (1 - 1 / Math.sqrt(2)) * arc * 2
crossY = max(arc, vert)
crossX = (crossY - arcY) + arcX
firstOut = max(
arc + arc, crossY / 2 + arc + arc, crossY / 2 + vert + first.down
)
self.up = firstOut + first.height + first.up
secondIn = max(arc + arc, crossY / 2 + arc + arc, crossY / 2 + vert + second.up)
self.down = secondIn + second.height + second.down
self.height = 0
firstWidth = (20 if first.needsSpace else 0) + first.width
secondWidth = (20 if second.needsSpace else 0) + second.width
self.width = 2 * arc + max(firstWidth, crossX, secondWidth) + 2 * arc
addDebug(self)
def __repr__(self) -> str:
items = ", ".join(repr(item) for item in self.items)
return f"AlternatingSequence({items})"
def format(self, x: float, y: float, width: float) -> AlternatingSequence:
arc = AR
gaps = determineGaps(width, self.width)
Path(x, y).right(gaps[0]).addTo(self)
x += gaps[0]
Path(x + self.width, y).right(gaps[1]).addTo(self)
# bounding box
# Path(x+gaps[0], y).up(self.up).right(self.width).down(self.up+self.down).left(self.width).up(self.down).addTo(self)
first = self.items[0]
second = self.items[1]
# top
firstIn = self.up - first.up
firstOut = self.up - first.up - first.height
Path(x, y).arc("se").up(firstIn - 2 * arc).arc("wn").addTo(self)
first.format(x + 2 * arc, y - firstIn, self.width - 4 * arc).addTo(self)
Path(x + self.width - 2 * arc, y - firstOut).arc("ne").down(
firstOut - 2 * arc
).arc("ws").addTo(self)
# bottom
secondIn = self.down - second.down - second.height
secondOut = self.down - second.down
Path(x, y).arc("ne").down(secondIn - 2 * arc).arc("ws").addTo(self)
second.format(x + 2 * arc, y + secondIn, self.width - 4 * arc).addTo(self)
Path(x + self.width - 2 * arc, y + secondOut).arc("se").up(
secondOut - 2 * arc
).arc("wn").addTo(self)
# crossover
arcX = 1 / Math.sqrt(2) * arc * 2
arcY = (1 - 1 / Math.sqrt(2)) * arc * 2
crossY = max(arc, VS)
crossX = (crossY - arcY) + arcX
crossBar = (self.width - 4 * arc - crossX) / 2
(
Path(x + arc, y - crossY / 2 - arc)
.arc("ws")
.right(crossBar)
.arc_8("n", "cw")
.l(crossX - arcX, crossY - arcY)
.arc_8("sw", "ccw")
.right(crossBar)
.arc("ne")
.addTo(self)
)
(
Path(x + arc, y + crossY / 2 + arc)
.arc("wn")
.right(crossBar)
.arc_8("s", "ccw")
.l(crossX - arcX, -(crossY - arcY))
.arc_8("nw", "cw")
.right(crossBar)
.arc("se")
.addTo(self)
)
return self
def textDiagram(self) -> TextDiagram:
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"])
firstTD = self.items[0].textDiagram()
secondTD = self.items[1].textDiagram()
maxWidth = TextDiagram._maxWidth(firstTD, secondTD)
leftWidth, rightWidth = TextDiagram._gaps(maxWidth, 0)
leftLines = []
rightLines = []
separator = []
leftSize, rightSize = TextDiagram._gaps(firstTD.width, 0)
diagramTD = firstTD.expand(leftWidth - leftSize, rightWidth - rightSize, 0, 0)
leftLines += [" " * 2] * (diagramTD.entry)
leftLines += [corner_top_left + line]
leftLines += [line_vertical + " "] * (diagramTD.height - diagramTD.entry - 1)
leftLines += [corner_bot_left + line]
rightLines += [" " * 2] * (diagramTD.entry)
rightLines += [line + corner_top_right]
rightLines += [" " + line_vertical] * (diagramTD.height - diagramTD.entry - 1)
rightLines += [line + corner_bot_right]
separator += [(line * (leftWidth - 1)) + corner_top_right + " " + corner_top_left + (line * (rightWidth - 2))]
separator += [(" " * (leftWidth - 1)) + " " + cross_diag + " " + (" " * (rightWidth - 2))]
separator += [(line * (leftWidth - 1)) + corner_bot_right + " " + corner_bot_left + (line * (rightWidth - 2))]
leftLines += [" " * 2]
rightLines += [" " * 2]
leftSize, rightSize = TextDiagram._gaps(secondTD.width, 0)
secondTD = secondTD.expand(leftWidth - leftSize, rightWidth - rightSize, 0, 0)
diagramTD = diagramTD.appendBelow(secondTD, separator, moveEntry=True, moveExit=True)
leftLines += [corner_top_left + line]
leftLines += [line_vertical + " "] * secondTD.entry
leftLines += [corner_bot_left + line]
rightLines += [line + corner_top_right]
rightLines += [" " + line_vertical] * secondTD.entry
rightLines += [line + corner_bot_right]
diagramTD = diagramTD.alter(entry=firstTD.height + (len(separator) // 2), exit=firstTD.height + (len(separator) // 2))
leftTD = TextDiagram(firstTD.height + (len(separator) // 2), firstTD.height + (len(separator) // 2), leftLines)
rightTD = TextDiagram(firstTD.height + (len(separator) // 2), firstTD.height + (len(separator) // 2), rightLines)
diagramTD = leftTD.appendRight(diagramTD, "").appendRight(rightTD, "")
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]), "")
return diagramTD
class Choice(DiagramMultiContainer):
def __init__(self, default: int, *items: Node):
DiagramMultiContainer.__init__(self, "g", items)
assert default < len(items)
self.default = default
self.width = AR * 4 + max(item.width for item in self.items)
# The size of the vertical separation between an item
# and the following item.
# The calcs are non-trivial and need to be done both here
# and in .format(), so no reason to do it twice.
self.separators: list[int] = [VS] * (len(items) - 1)
# If the entry or exit lines would be too close together
# to accommodate the arcs,
# bump up the vertical separation to compensate.
self.up = 0
for i in range(default - 1, -1, -1):
if i == default-1:
arcs = AR * 2
else:
arcs = AR
item = self.items[i]
lowerItem = self.items[i+1]
entryDelta = lowerItem.up + VS + item.down + item.height
exitDelta = lowerItem.height + lowerItem.up + VS + item.down
separator = VS
if exitDelta < arcs or entryDelta < arcs:
separator += max(arcs - entryDelta, arcs - exitDelta)
self.separators[i] = separator
self.up += lowerItem.up + separator + item.down + item.height
self.up += self.items[0].up
self.height = self.items[default].height
for i in range(default+1, len(self.items)):
if i == default+1:
arcs = AR * 2
else:
arcs = AR
item = self.items[i]
upperItem = self.items[i-1]
entryDelta = upperItem.height + upperItem.down + VS + item.up
exitDelta = upperItem.down + VS + item.up + item.height