8000 minor refactoring: make things that don't need to be lists into sets,… · dragoncoder047/schemascii@7b1fc28 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7b1fc28

Browse files
minor refactoring: make things that don't need to be lists into sets, move XMLClass to svg_utils file
1 parent 82baa42 commit 7b1fc28

13 files changed

+140
-126
lines changed

schemascii/__main__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ def cli_main():
2828
ap.add_argument(
2929
"-V", "--version", action="version",
3030
version="%(prog)s " + schemascii.__version__)
31-
ap.add_argument("-i", "--in", help="File to process. (default: stdin)",
32-
dest="in_file", default="-")
31+
ap.add_argument("in_file", help="File to process. (default: stdin)",
32+
default="-")
3333
ap.add_argument(
3434
"-o",
3535
"--out",

schemascii/annoline.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2 8000 1,7 +21,7 @@ class AnnotationLine(_dc.DataConsumer,
2121
css_class = "annotation annotation-line"
2222

2323
directions: typing.ClassVar[
24-
defaultdict[str, defaultdict[complex, list[complex]]]] = defaultdict(
24+
defaultdict[str, defaultdict[complex, set[complex]]]] = defaultdict(
2525
lambda: None, {
2626
# allow jumps over actual wires
2727
"-": _utils.IDENTITY,
@@ -31,25 +31,25 @@ class AnnotationLine(_dc.DataConsumer,
3131
":": _utils.IDENTITY,
3232
"~": _utils.IDENTITY,
3333
".": {
34-
-1: [1j, 1],
35-
1j: [],
36-
-1j: [-1, 1],
37-
1: [1j, -1]
34+
-1: {1j, 1},
35+
1j: set(),
36+
-1j: {-1, 1},
37+
1: {1j, -1}
3838
},
3939
"'": {
40-
-1: [-1j, 1],
41-
-1j: [],
42-
1j: [-1, 1],
43-
1: [-1j, -1]
40+
-1: {-1j, 1},
41+
-1j: set(),
42+
1j: {-1, 1},
43+
1: {-1j, -1}
4444
}
4545
})
4646
start_dirs: typing.ClassVar[
47-
defaultdict[str, list[complex]]] = defaultdict(
47+
defaultdict[str, set[complex]]] = defaultdict(
4848
lambda: None, {
4949
"~": _utils.LEFT_RIGHT,
5050
":": _utils.UP_DOWN,
51-
".": (-1, 1, -1j),
52-
"'": (-1, 1, 1j),
51+
".": {-1, 1, -1j},
52+
"'": {-1, 1, 1j},
5353
})
5454

5555
# the sole member
@@ -59,7 +59,7 @@ class AnnotationLine(_dc.DataConsumer,
5959
def get_from_grid(cls, grid: _grid.Grid, start: complex) -> AnnotationLine:
6060
"""Return an AnnotationLine that starts at the specified point."""
6161
points = _utils.flood_walk(
62-
grid, [start], cls.start_dirs, cls.directions, set())
62+
grid, {start}, cls.start_dirs, cls.directions, set())
6363
return cls(points)
6464

6565
@classmethod

schemascii/annotation.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
import schemascii.data_consumer as _dc
88
import schemascii.grid as _grid
9-
import schemascii.utils as _utils
9+
import schemascii.svg_utils as _svg
1010

1111
ANNOTATION_RE = re.compile(r"\[([^\]]+)\]")
1212

@@ -37,7 +37,7 @@ def find_all(cls, grid: _grid.Grid) -> list[Annotation]:
3737
return out
3838

3939
def render(self, scale, font, **options) -> str:
40-
return _utils.XML.text(
40+
return _svg.XML.text(
4141
html.escape(self.content),
4242
x=self.position.real * scale,
4343
y=self.position.imag * scale,

schemascii/component.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def from_rd(cls, rd: _rd.RefDes, grid: _grid.Grid) -> Component:
6565

6666
# add in the RD's bounds and find the main blob
6767
blobs.append(_utils.flood_walk(
68-
grid, list(_utils.iterate_line(rd.left, rd.right)),
68+
grid, set(_utils.iterate_line(rd.left, rd.right)),
6969
start_orth, cont_orth, seen))
7070
# now find all of the auxillary blobs
7171
for perimeter_pt in _utils.perimeter(blobs[0]):
@@ -75,7 +75,7 @@ def from_rd(cls, rd: _rd.RefDes, grid: _grid.Grid) -> Component:
7575
and grid.get(poss_aux_blob_pt) == "#"):
7676
# we found another blob
7777
blobs.append(_utils.flood_walk(
78-
grid, [poss_aux_blob_pt], start_moore,
78+
grid, {poss_aux_blob_pt}, start_moore,
7979
cont_moore, seen))
8080
# find all of the terminals
8181
terminals: list[_utils.Terminal] = []
@@ -146,7 +146,7 @@ def css_class(self) -> str:
146146
return f"component {self.rd.letter}"
147147

148148
@classmethod
149-
def process_nets(self, nets: list[_net.Net]):
149+
def process_nets(self, nets: list[_net.Net]) -> None:
150150
"""Hook method called to do stuff with the nets that this
151151
component type connects to. By default it does nothing.
152152
@@ -165,7 +165,7 @@ def get_terminals(
165165
found, or there were multiple terminals with the requested flag
166166
(ambiguous).
167167
"""
168-
out = []
168+
out: list[_utils.Terminal] = []
169169
for flag in flags_names:
170170
matching_terminals = [t for t in self.terminals if t.flag == flag]
171171
if len(matching_terminals) > 1:

schemascii/components/inductor.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import schemascii.components as _c
44
import schemascii.data_consumer as _dc
55
import schemascii.utils as _utils
6+
import schemascii.svg_utils as _svg
67

78

89
class Inductor(_c.PolarizedTwoTerminalComponent, _c.SimpleComponent,
@@ -29,9 +30,8 @@ def render(self, **options) -> str:
2930
for _ in range(int(length)):
3031
data += f"a1 1 0 01 {-d.real} {d.imag}"
3132
return (
32-
_utils.XML.path(d=data, stroke=options["stroke"],
33-
fill="transparent",
34-
stroke__width=options["stroke_width"])
33+
_svg.path(data, "transparent", options["stroke_width"],
34+
options["stroke"])
3535
+ self.format_id_text(
3636
_utils.make_text_point(t1, t2, **options), **options))
3737

schemascii/data_consumer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import schemascii.data as _data
99
import schemascii.errors as _errors
10-
import schemascii.utils as _utils
10+
import schemascii.svg_utils as _svg
1111

1212
T = typing.TypeVar("T")
1313
_NOT_SET = object()
@@ -136,7 +136,7 @@ def to_xml_string(self, data: _data.Data) -> str:
136136
# render
137137
result = self.render(**values, data=data)
138138
if self.css_class:
139-
result = _utils.XML.g(result, class_=self.css_class)
139+
result = _svg.group(result, class_=self.css_class)
140140
return result
141141

142142
@abc.abstractmethod

schemascii/drawing.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,16 @@
33
import typing
44
from dataclasses import dataclass
55

6-
import schemascii.data_consumer as _dc
76
import schemascii.annoline as _annoline
87
import schemascii.annotation as _a
98
import schemascii.component as _component
109
import schemascii.data as _data
10+
import schemascii.data_consumer as _dc
1111
import schemascii.errors as _errors
1212
import schemascii.grid as _grid
1313
import schemascii.net as _net
1414
import schemascii.refdes as _rd
15-
import schemascii.utils as _utils
15+
import schemascii.svg_utils as _svg
1616

1717

1818
@dataclass
@@ -54,8 +54,8 @@ def from_file(cls,
5454
marker_pos = lines.index(data_marker)
5555
except ValueError as e:
5656
raise _errors.DiagramSyntaxError(
57-
"data-marker must be present in a drawing! "
58-
f"(current data-marker is: {data_marker!r})") from e
57+
"data_marker must be present in a drawing! "
58+
f"(current data_marker is: {data_marker!r})") from e
5959
drawing_area = "\n".join(lines[:marker_pos])
6060
data_area = "\n".join(lines[marker_pos+1:])
6161
# find everything
@@ -85,19 +85,19 @@ def to_xml_string(
8585

8686
def render(self, data, scale: float, padding: float, **options) -> str:
8787
# render everything
88-
content = _utils.XML.g(
89-
_utils.XML.g(
88+
content = _svg.group(
89+
_svg.group(
9090
*(net.to_xml_string(data) for net in self.nets),
9191
class_="wires"),
92-
_utils.XML.g(
92+
_svg.group(
9393
*(comp.to_xml_string(data) for comp in self.components),
9494
class_="components"),
9595
class_="electrical")
96-
content += _utils.XML.g(
96+
content += _svg.group(
9797
*(line.to_xml_string(data) for line in self.annotation_lines),
9898
*(anno.to_xml_string(data) for anno in self.annotations),
9999
class_="annotations")
100-
return _utils.XML.svg(
100+
return _svg.group(
101101
content,
102102
width=self.grid.width * scale + padding * 2,
103103
height=self.grid.height * scale + padding * 2,

schemascii/svg_utils.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import typing
2+
3+
4+
def fix_number(n: float) -> str:
5+
"""If n is an integer, remove the trailing ".0".
6+
Otherwise round it to 2 digits, and return the stringified
7+
number.
8+
"""
9+
if n.is_integer():
10+
return str(int(n))
11+
n = round(n, 2)
12+
if n.is_integer():
13+
return str(in 10000 t(n))
14+
return str(n)
15+
16+
17+
class XMLClass:
18+
def __getattr__(self, tag: str) -> typing.Callable[..., str]:
19+
def mk_tag(*contents: str, **attrs: str | bool | float | int) -> str:
20+
out = f"<{tag}"
21+
for k, v in attrs.items():
22+
if v is False:
23+
continue
24+
if isinstance(v, float):
25+
v = fix_number(v)
26+
# XXX: this gets called on every XML level
27+
# XXX: which means that it will be called multiple times
28+
# XXX: unnecessarily
29+
# elif isinstance(v, str):
30+
# v = re.sub(r"\b\d+(\.\d+)\b",
31+
# lambda m: fix_number(float(m.group())), v)
32+
out += f' {k.removesuffix("_").replace("__", "-")}="{v}"'
33+
out = out + ">" + "".join(contents)
34+
return out + f"</{tag}>"
35+
36+
return mk_tag
37+
38+
39+
XML = XMLClass()
40+
del XMLClass
41+
42+
43+
def group(*items: str, class_: str | False = False) -> str:
44+
return XML.g(*items, class_=class_)
45+
46+
47+
def path(data: str,
48+
fill: str | False = False,
49+
stroke_width: float | False = False,
50+
stroke: str | False = False,
51+
class_: str | False = False) -> str:
52+
return XML.path(d=data, fill=fill, stroke__width=stroke_width,
53+
stroke=stroke, class_=class_)
54+
55+
56+
def circle(center: complex, radius: float, stroke: str | False = False,
57+
fill: str | False = False, class_: str | False = False) -> str:
58+
return XML.circle(cx=center.real, cy=center.imag, r=radius,
59+
stroke=stroke, fill=fill, class_=class_)

0 commit comments

Comments
 (0)
0