-
Notifications
You must be signed in to change notification settings - Fork 46
/
altium.py
executable file
·1609 lines (1430 loc) · 56.6 KB
/
altium.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
#! /usr/bin/env python3
import struct
from warnings import warn
import zlib
from pathlib import PureWindowsPath, Path
import os
from io import BytesIO
from math import atan2, sin, cos, radians, degrees, hypot
from olefile import OleFileIO
class Object:
'''Base class for Altium schematic objects'''
def __init__(self, *, properties=None):
self.properties = properties
self.children = list()
def __repr__(self):
if self.properties is not None:
properties = "properties=<{}>".format(self.properties)
else:
properties = ""
return "{}({})".format(type(self).__name__, properties)
def read(file):
"""Parses an Altium ".SchDoc" schematic file and returns a Sheet object
"""
ole = OleFileIO(file)
stream = ole.openstream("FileHeader")
records = iter_records(stream)
records = (parse_properties(stream, record) for record in records)
header = next(records)
parse_header(header)
header.check_unknown()
sheet = Object(properties=next(records))
objects = [sheet]
for properties in records:
obj = Object(properties=properties)
objects[obj.properties.get_int("OWNERINDEX")].children.append(obj)
objects.append(obj)
if ole.exists("Additional"):
stream = ole.openstream("Additional")
records = iter_records(stream)
records = (parse_properties(stream, record) for record in records)
header = next(records)
parse_header(header)
header.check_unknown()
for properties in records:
obj = Object(properties=properties)
owner = obj.properties.get_int("OWNERINDEX")
objects[owner].children.append(obj)
objects.append(obj)
storage_stream = ole.openstream("Storage")
records = iter_records(storage_stream)
header = parse_properties(storage_stream, next(records))
header.check("HEADER", b"Icon storage")
header.get_int("WEIGHT")
header.check_unknown()
storage_files = dict()
for [type, length] in records:
if type != 1:
warn("Unexpected record type {} in Storage".format(type))
continue
header = storage_stream.read(1)
if header != b"\xD0":
warn("Unexpected Storage record header byte " + repr(header))
continue
[length] = storage_stream.read(1)
filename = storage_stream.read(length)
pos = storage_stream.tell()
if storage_files.setdefault(filename, pos) != pos:
warn("Duplicate Storage record for " + repr(filename))
streams = set(map(tuple, ole.listdir()))
streams -= {("FileHeader",), ("Additional",), ("Storage",)}
if streams:
warn("Extra OLE file streams: " + ", ".join(map("/".join, streams)))
return (sheet, storage_stream, storage_files)
def iter_records(stream):
"""Finds object records from a stream in an Altium ".SchDoc" file
"""
while True:
length = stream.read(2)
if not length:
break
(length,) = struct.unpack("<H", length)
byte = stream.read(1)
if byte != b"\x00":
warn("Expected 0x00 byte after record length")
[type] = stream.read(1)
if type > 1:
warn("Unexpected record type " + format(type))
end = stream.tell() + length
yield (type, length)
if stream.tell() > end:
warn("Read past end of record")
stream.seek(end)
def parse_properties(stream, header):
[type, length] = header
if type != 0:
warn("Expected properties record, not type " + format(type))
return None
properties = stream.read(length - 1)
obj = Properties()
seen = dict()
for property in properties.split(b"|"):
if not property:
# Most (but not all) property lists are
# prefixed with a pipe "|",
# so ignore an empty property before the prefix
continue
(name, value) = property.split(b"=", 1)
name = name.decode("ascii")
existing = seen.get(name)
if existing not in (None, value):
msg = "Conflicting duplicate: {!r}, was {!r}"
warn(msg.format(property, existing))
obj[name.upper()] = value
seen[name] = value
if stream.read(1) != b"\x00":
warn("Properties record not null-terminated")
return obj
class Properties:
'''Holds the |NAME=value properties of a schematic object'''
def __init__(self):
self._properties = dict()
self._known = set() # Help determine unknown properties
def __setitem__(self, name, value):
self._properties[name] = value
def __str__(self):
'''Return a string listing all the properties'''
properties = sorted(self._properties.items())
return "".join("|{}={!r}".format(p, v) for (p, v) in properties)
def __getitem__(self, property):
self._known.add(property)
return self._properties[property]
def get(self, property, default=None):
self._known.add(property)
return self._properties.get(property, default)
def check(self, name, *values):
'''Check that a property is set to an expected value'''
value = self.get(name)
if value not in values:
msg = "Unhandled property |{}={!r}; expected {}"
msg = msg.format(name, value, ", ".join(map(repr, values)))
warn(msg, stacklevel=2)
def check_unknown(self):
'''Warn if there are properties that weren't queried'''
unhandled = self._properties.keys() - self._known
if unhandled:
unhandled = ", ".join(sorted(unhandled))
warn("{} unhandled in {}".format(unhandled, self), stacklevel=2)
def get_int(self, property):
return int(self.get(property, 0))
def get_bool(self, property):
value = self.get(property, b"F")
return {b"F": False, b"T": True}[value]
def get_real(self, property):
return float(self.get(property, 0))
def parse_header(obj):
obj.check("HEADER",
b"Protel for Windows - Schematic Capture Binary File Version 5.0")
obj.get_int("WEIGHT")
obj.check("MINORVERSION", None, b"2")
obj.get("UNIQUEID")
def get_sheet_style(sheet):
'''Returns the size of the sheet: (name, (width, height))'''
STYLES = {
SheetStyle.A4: ("A4", (1150, 760)),
SheetStyle.A3: ("A3", (1550, 1110)),
SheetStyle.A2: ("A2", (2230, 1570)),
SheetStyle.A1: ("A1", (3150, 2230)),
SheetStyle.A0: ("A0", (4460, 3150)),
SheetStyle.A: ("A", (950, 750)),
SheetStyle.B: ("B", (1500, 950)),
SheetStyle.C: ("C", (2000, 1500)),
SheetStyle.D: ("D", (3200, 2000)),
SheetStyle.E: ("E", (4200, 3200)),
SheetStyle.LETTER: ("Letter", (1100, 850)),
SheetStyle.LEGAL: ("Legal", (1400, 850)),
SheetStyle.TABLOID: ("Tabloid", (1700, 1100)),
SheetStyle.ORCAD_A: ("OrCAD A", (990, 790)),
SheetStyle.ORCAD_B: ("OrCAD B", (1540, 990)),
SheetStyle.ORCAD_C: ("OrCAD C", (2060, 1560)),
SheetStyle.ORCAD_D: ("OrCAD D", (3260, 2060)),
SheetStyle.ORCAD_E: ("OrCAD E", (4280, 3280)),
}
[sheetstyle, size] = STYLES[sheet.get_int("SHEETSTYLE")]
if sheet.get_bool("USECUSTOMSHEET"):
size = tuple(sheet.get_int("CUSTOM" + "XY"[x]) for x in range(2))
if sheet.get_int("WORKSPACEORIENTATION"):
[height, width] = size
size = (width, height)
return (sheetstyle, size)
# Sizes and locations are in 1/100" = 10 mil = 0.254 mm units
INCH_SIZE = 100
UNIT_MILS = 10
UNIT_MM = 0.254
FRAC_DENOM = int(100e3) # _FRAC properties are in 1/100,000 units
def iter_fonts(sheet):
'''Yield a dictionary for each font defined for a sheet
Dictionary keys:
id: Positive integer
line: Font's line spacing
family: Typeface name
italic, bold, underline: Boolean values
'''
for i in range(sheet.get_int("FONTIDCOUNT")):
id = 1 + i
n = format(id)
yield dict(
id=id,
line=sheet.get_int("SIZE" + n),
family=sheet["FONTNAME" + n].decode("ascii"),
italic=sheet.get_bool("ITALIC" + n),
bold=sheet.get_bool("BOLD" + n),
underline=sheet.get_bool("UNDERLINE" + n),
)
sheet.get("ROTATION{}".format(1 + i))
def get_int_frac(obj, property):
'''Return full value of a field with separate integer and fraction'''
value = obj.get_int(property)
value += obj.get_int(property + "_FRAC") / FRAC_DENOM
return value
def get_int_frac1(obj, property):
'''Return full value of field with separate x10 integer and fraction
In contrast to all other elements, DISTANCEFROMTOP uses x10 coordinates.
'''
value = obj.get_int(property)*10
value += obj.get_int(property + "_FRAC1") / FRAC_DENOM
return value
def get_utf8(obj, property):
text = obj[property]
try:
text = text.decode("windows-1252")
except UnicodeDecodeError as err:
warn(err)
text = text.decode("windows-1252", "backslashreplace")
utf8 = obj.get("%UTF8%" + property)
if utf8 is None:
return text
utf8 = utf8.decode("utf-8")
subst = utf8.translate({
ord("\N{GREEK SMALL LETTER MU}"): "\N{MICRO SIGN}",
0x00A6: "\N{LATIN CAPITAL LETTER Z WITH CARON}",
})
if text != subst:
warn("UTF-8 and CP-1252 text differ in " + format(obj))
return utf8
def get_location(obj):
'''Return location property co-ordinates as a tuple'''
return tuple(get_int_frac(obj, "LOCATION." + x) for x in "XY")
def display_part(objects, obj):
'''Determine if obj is in the component's current part and display mode
'''
part = obj.get("OWNERPARTID")
owner = objects.properties
mode = obj.get_int("OWNERPARTDISPLAYMODE")
return ((part == b"-1" or part == owner.get("CURRENTPARTID")) and
mode == owner.get_int("DISPLAYMODE"))
def get_line_width(obj):
return [0.4, 1, 2, 4][obj.get_int("LINEWIDTH")]
class Record:
"""Schematic object record types"""
HEADER = 0
COMPONENT = 1
PIN = 2
LABEL = 4
BEZIER = 5
POLYLINE = 6
POLYGON = 7
ELLIPSE = 8
ROUND_RECTANGLE = 10
ELLIPTICAL_ARC = 11
ARC = 12
LINE = 13
RECTANGLE = 14
SHEET_SYMBOL = 15
SHEET_ENTRY = 16
POWER_PORT = 17
PORT = 18
NO_ERC = 22
NET_LABEL = 25
BUS = 26
WIRE = 27
TEXT_FRAME = 28
JUNCTION = 29
IMAGE = 30
SHEET = 31
SHEET_NAME = 32
SHEET_FILE_NAME = 33
DESIGNATOR = 34
BUS_ENTRY = 37
TEMPLATE = 39
PARAMETER = 41
WARNING_SIGN = 43
IMPLEMENTATION_LIST = 44
IMPLEMENTATION = 45
class PinElectrical:
"""Signal types for a pin"""
INPUT = 0
IO = 1
OUTPUT = 2
OPEN_COLLECTOR = 3
PASSIVE = 4
HI_Z = 5
OPEN_EMITTER = 6
POWER = 7
class PowerObjectStyle:
"""Symbols for remote connections to common rails"""
ARROW = 1
BAR = 2
GND = 4
class ParameterReadOnlyState:
NAME = 1
class SheetStyle:
"""Preset sheet sizes"""
A4 = 0
A3 = 1
A2 = 2
A1 = 3
A0 = 4
A = 5
B = 6
C = 7
D = 8
E = 9
LETTER = 10
LEGAL = 11
TABLOID = 12
ORCAD_A = 13
ORCAD_B = 14
ORCAD_C = 15
ORCAD_D = 16
ORCAD_E = 17
class LineShape:
'''Start and end shapes for polylines'''
NONE = 0
THIN_ARROW = 1
SOLID_ARROW = 2
THIN_TAIL = 3
SOLID_TAIL = 4
CIRCLE = 5
SQUARE = 6
class LineShapeSize:
'''Size of start and end shapes for polylines'''
XSMALL = 0
SMALL = 1
MEDIUM = 2
LARGE = 3
import vector
import os
import os.path
from datetime import datetime
import contextlib
from importlib import import_module
from inspect import getdoc
from argparse import ArgumentParser
from warnings import warn
def main():
parser = ArgumentParser(description=getdoc(render))
parser.add_argument("file")
parser.add_argument("--renderer", choices={"svg", "tk"}, default="svg",
help=render.__init__.__annotations__["Renderer"])
args = parser.parse_args()
renderer = import_module("." + args.renderer, "vector")
render(args.file, renderer.Renderer)
def _setitem(dict, key):
def decorator(func):
dict[key] = func
return func
return decorator
def gnd(renderer):
renderer.hline(10)
renderer.vline(-7, +7, offset=(10, 0), width=1.5)
renderer.vline(-4, +4, offset=(13, 0), width=1.5)
renderer.vline(-1, +1, offset=(16, 0), width=1.5)
def rail(renderer):
renderer.hline(10)
renderer.vline(-7, +7, offset=(10, 0), width=1.5)
def arrowconn(renderer):
neck = arrow_neck(**render.arrowhead)
renderer.hline(10 - neck)
draw_arrow(renderer, neck, render.arrowhead["outside"],
render.arrowhead["hang"], offset=(10, 0))
# Anatomy of arrow shapes:
# * point: Where the line would end without the arrow
# * shoulder: Part laterally furthest away from the shaft
# * neck: Where the full width of the shaft intersects the arrow
#
# shoulder __
# \ ---___
# --------+\ --
# neck| > >point
# --------+/ ___--
# /__---
#
# Arrow shapes are defined by:
# * inside: Flatness (run / rise) of the line from the shoulder to the neck
# * outside: Flatness of the line from the shoulder to the point
# * hang: Lateral distance from shoulder to edge of the shaft
#
# Types of shapes:
# * Dart, chevron, barbed, concave arrowhead; inside > outside > 0: ===)>
# * Triangular arrowhead; inside = 0 < outside: ===|>
# * Diamond, biconvex; inside < 0 < outside: ===<>
# * Triangular tail; inside < 0 = outside: ===<|
def arrow_neck(inside, outside, hang, *, thick=1):
r'''Distance to shaft junction from point'''
return hang * (outside - inside) + thick/2 * outside
def draw_arrow(renderer, neck, outside, hang, dir=(1, 0), *, thick=1, **kw):
barb = outside * (thick/2 + hang)
[dirx, diry] = dir
if diry or dirx <= 0:
kw.update(rotate=degrees(atan2(-diry, dirx)))
renderer.polygon((
(-neck, +thick/2),
(-barb, +thick/2 + hang),
(0, 0),
(-barb, -thick/2 - hang),
(-neck, -thick/2),
), fill=True, **kw)
def dchevron(renderer):
renderer.hline(5)
renderer.polyline(((8, +4), (5, 0), (8, -4)))
renderer.polyline(((11, +4), (8, 0), (11, -4)))
def nc(renderer):
renderer.line((+3, +3), (-3, -3), width=0.6)
renderer.line((-3, +3), (+3, -3), width=0.6)
def clock(renderer):
renderer.polyline(((0, +3), (-5, 0), (0, -3)), width=0.6)
class render:
"""Render an Altium ".SchDoc" schematic file"""
def __init__(self, filename,
Renderer: """By default, the schematic is converted to an SVG file,
written to the standard output. It may also be rendered using TK.
""",
):
with open(filename, "rb") as file:
[objects, self.storage_stream, self.storage_files] = read(file)
stat = os.stat(file.fileno())
self.files_used = set()
sheet = objects.properties
[sheetstyle, size] = get_sheet_style(sheet)
self.renderer = Renderer(size, "in", 1 / INCH_SIZE,
margin=0.3, line=1, down=-1, textbottom=True)
for font in iter_fonts(sheet):
name = font_name(font["id"])
# Not sure if line spacing to font em size fudge factor is
# specific to Times New Roman, or to Altium
fontsize = font["line"] * 0.875
self.renderer.addfont(name, fontsize, font["family"],
italic=font["italic"], bold=font["bold"],
underline=font["underline"],
)
self.renderer.setdefaultfont(font_name(sheet.get_int("SYSTEMFONT")))
self.renderer.start()
self.renderer.addobjects((gnd, rail, arrowconn, dchevron, nc, clock))
with self.renderer.view(offset=(0, size[1])) as base:
base.rectangle((size[0], -size[1]), outline=True, width=0.6,
fill=colour(sheet, "AREACOLOR"))
base.rectangle((20, -20), (size[0] - 20, 20 - size[1]),
width=0.6)
for axis in range(2):
for side in range(2):
for n in range(4):
translate = [None] * 2
translate[axis] = size[axis] / 4 * (n + 0.5)
translate[axis ^ 1] = 10
if side:
translate[axis ^ 1] += size[axis ^ 1] - 20
translate[1] *= -1
with base.view(offset=translate) as ref:
label = chr(ord("1A"[axis]) + n)
ref.text(label,
horiz=ref.CENTRE, vert=ref.CENTRE)
if n + 1 < 4:
x = size[axis] / 4 / 2
if axis:
ref.hline(-10, +10, offset=(0, -x),
width=0.6)
else:
ref.vline(-10, +10, offset=(x, 0),
width=0.6)
if not os.path.isabs(filename):
cwd = os.getcwd()
pwd = os.getenv("PWD")
if os.path.samefile(pwd, cwd):
cwd = pwd
filename = os.path.join(pwd, filename)
self.filename = filename
self.date = datetime.fromtimestamp(stat.st_mtime)
if sheet.get_bool("TITLEBLOCKON"):
with base.view(offset=(size[0] - 20, 20 - size[1])) as block:
points = ((-350, 0), (-350, 80), (-0, 80))
block.polyline(points, width=0.6)
block.hline(-350, 0, offset=(0, 50), width=0.6)
block.vline(-30, offset=(-300, 50), width=0.6)
block.vline(-30, offset=(-100, 50), width=0.6)
block.hline(-350, 0, offset=(0, 20), width=0.6)
block.hline(-350, 0, offset=(0, 10), width=0.6)
block.vline(20, 0, offset=(-150, 0), width=0.6)
block.text("Title", (-345, 70))
block.text("Size", (-345, 40))
block.text(sheetstyle, (-340, 30), vert=block.CENTRE)
block.text("Number", (-295, 40))
block.text("Revision", (-95, 40))
block.text("Date", (-345, 10))
d = format(self.date, "%x")
block.text(d, (-300, 10))
block.text("File", (-345, 0))
block.text(self.filename, (-300, 0))
block.text("Sheet", (-145, 10))
block.text("of", (-117, 10))
block.text("Drawn By:", (-145, 0))
self.check_sheet(sheet)
self.handle_children([objects])
unused = self.storage_files.keys() - self.files_used
if unused:
unused = ", ".join(map(repr, unused))
warn("Unreferenced embedded files: " + unused)
self.renderer.finish()
def check_sheet(self, obj):
assert obj.get_int("RECORD") == Record.SHEET
obj.check("BORDERON", b"T")
for property in (
"CUSTOMX", "CUSTOMY", "HOTSPOTGRIDSIZE", "SNAPGRIDSIZE",
):
obj[property]
obj.check("CUSTOMMARGINWIDTH", None, b"20")
obj.check("CUSTOMXZONES", None, b"6")
obj.check("CUSTOMYZONES", None, b"4")
obj.check("DISPLAY_UNIT", b"1", b"4")
obj.check("HOTSPOTGRIDON", b"T")
obj.check("ISBOC", b"T")
obj.check("SHEETNUMBERSPACESIZE", b"4")
obj.check("SNAPGRIDON", b"T")
obj.check("USEMBCS", b"T")
obj.check("VISIBLEGRIDON", b"T")
obj.check("VISIBLEGRIDSIZE", b"10")
obj.get_bool("SHOWTEMPLATEGRAPHICS")
obj.get("TEMPLATEFILENAME")
obj.check_unknown()
def handle_children(self, owners):
for child in owners[-1].children:
obj = child.properties
record = obj.get_int("RECORD")
handler = self.handlers.get(record)
if handler:
handler(self, owners, obj)
obj.check_unknown()
else:
warn("Unhandled record type: {}".format(obj))
owners.append(child)
self.handle_children(owners)
owners.pop()
arrowhead = dict(inside=2/3, outside=7/3, hang=2.5)
arrowtail = dict(inside=-7/2.5, outside=0, hang=2)
diamond = dict(inside=-5/2.5, outside=+5/2.5, hang=2)
pinmarkers = {
PinElectrical.INPUT: arrowhead,
PinElectrical.IO: diamond,
PinElectrical.OUTPUT: arrowtail,
PinElectrical.PASSIVE: None,
PinElectrical.HI_Z: None,
PinElectrical.POWER: None,
}
connmarkers = {
PowerObjectStyle.ARROW: (arrowconn, 12),
PowerObjectStyle.BAR: (rail, 12),
PowerObjectStyle.GND: (gnd, 20),
}
# Mapping of record type numbers to handler method names. The handlers
# should read all recognized properties from the "obj" dictionary, so
# that unhandled properties can be detected.
handlers = dict()
@_setitem(handlers, Record.LINE)
def handle_line(self, owners, obj):
obj.get_int("INDEXINSHEET")
obj.check("ISNOTACCESIBLE", b"T")
kw = dict(
colour=colour(obj),
width=get_line_width(obj),
a=get_location(obj),
b=tuple(obj.get_int("CORNER." + x) for x in "XY"),
)
if display_part(owners[-1], obj):
self.renderer.line(**kw)
@_setitem(handlers, Record.POLYLINE)
def handle_polyline(self, owners, obj):
obj.get_int("INDEXINSHEET")
obj.get_bool("ISNOTACCESIBLE")
linewidth = get_line_width(obj)
points = list()
for i in range(obj.get_int("LOCATIONCOUNT")):
location = (get_int_frac(obj, "{}{}".format(x, 1 + i))
for x in "XY")
points.append(tuple(location))
kw = dict(points=points)
col = colour(obj)
scale = {
LineShapeSize.XSMALL: 1,
LineShapeSize.SMALL: 2.5,
LineShapeSize.MEDIUM: 5,
LineShapeSize.LARGE: 10,
}
scale = scale[obj.get_int("LINESHAPESIZE")]
arrows = {
LineShape.NONE: None,
LineShape.SOLID_ARROW: self.arrowhead,
LineShape.SOLID_TAIL: self.arrowtail,
LineShape.THIN_ARROW: LineShape.THIN_ARROW,
LineShape.THIN_TAIL: LineShape.THIN_TAIL,
LineShape.SQUARE: LineShape.SQUARE,
LineShape.CIRCLE: LineShape.CIRCLE,
}
start_shape = obj.get_int("STARTLINESHAPE")
try:
start_shape = arrows[start_shape]
except LookupError:
warn("Unhandled STARTLINESHAPE=" + format(start_shape))
start_shape = None
end_shape = obj.get_int("ENDLINESHAPE")
try:
end_shape = arrows[end_shape]
except LookupError:
warn("Unhandled ENDLINESHAPE=" + format(end_shape))
end_shape = None
if display_part(owners[-1], obj):
start = points[0]
end = points[-1]
start_dir = tuple(a - b for [a, b] in zip(start, points[1]))
end_dir = tuple(b - a for [b, a] in zip(end, points[-2]))
start_hang = scale * 2
if isinstance(start_shape, dict):
start_hang = start_shape["hang"] * scale
start_neck = arrow_neck(start_shape["inside"],
start_shape["outside"], start_hang, thick=linewidth)
elif start_shape == LineShape.THIN_ARROW:
start_neck = (hypot(1, 3/2) + 3/2/2) * linewidth
else:
start_neck = 0
mag = hypot(*start_dir)
start_point = start
start = (
start_point[0] - start_neck * start_dir[0]/mag,
start_point[1] - start_neck * start_dir[1]/mag,
)
end_hang = scale * 2
if isinstance(end_shape, dict):
end_hang = end_shape["hang"] * scale
end_neck = arrow_neck(end_shape["inside"],
end_shape["outside"], end_hang, thick=linewidth)
elif end_shape == LineShape.THIN_ARROW:
end_neck = (hypot(1, 3/2) + 3/2/2) * linewidth
else:
end_neck = 0
mag = hypot(*end_dir)
end_point = end
end = (
end_point[0] - end_neck * end_dir[0]/mag,
end_point[1] - end_neck * end_dir[1]/mag,
)
points[0] = start
points[-1] = end
with contextlib.ExitStack() as stack:
view = self.renderer
if start_shape or end_shape:
view = stack.enter_context(view.view(colour=col))
else:
kw.update(colour=col)
if linewidth != 1:
kw.update(width=linewidth)
view.polyline(**kw)
def draw(shape, point, neck, dir, hang):
r = scale * 1.5 + linewidth / 2
[run, rise] = dir
rotate = degrees(atan2(rise, run))
if isinstance(shape, dict):
draw_arrow(view, neck, shape["outside"],
hang, dir, offset=point,
thick=linewidth)
elif shape == LineShape.THIN_ARROW:
hang += linewidth / 2
flat = hypot(1, 3/2) * linewidth
view.polygon((
(-neck, +linewidth/2),
(-hang * 3/2 - flat, +hang),
(-hang * 3/2, +hang),
(0, 0),
(-hang * 3/2, -hang),
(-hang * 3/2 - flat, -hang),
(-neck, -linewidth/2),
), fill=True, offset=point, rotate=rotate)
elif shape == LineShape.THIN_TAIL:
hang += linewidth / 2
flat = hypot(1, 3/2) * linewidth
view.polygon((
(-flat, 0),
(hang * 3/2 - flat, +hang),
(+hang * 3/2, +hang),
(0, 0),
(+hang * 3/2, -hang),
(hang * 3/2 - flat, -hang),
), fill=True, offset=point, rotate=rotate)
elif shape == LineShape.SQUARE:
view.rectangle((-r, -r), (+r, +r), offset=point,
fill=True, rotate=rotate)
elif shape == LineShape.CIRCLE:
view.ellipse((r, r), point, fill=True)
draw(start_shape, start_point,
start_neck, start_dir, start_hang)
draw(end_shape, end_point, end_neck, end_dir, end_hang)
@_setitem(handlers, Record.ARC)
@_setitem(handlers, Record.ELLIPTICAL_ARC)
def handle_arc(self, owners, obj):
obj.get_int("INDEXINSHEET")
obj.check("ISNOTACCESIBLE", b"T")
width = get_line_width(obj)
r = get_int_frac(obj, "RADIUS")
if obj.get_int("RECORD") == Record.ELLIPTICAL_ARC:
r2 = get_int_frac(obj, "SECONDARYRADIUS")
else:
r2 = r
start = obj.get_real("STARTANGLE")
end = obj.get_real("ENDANGLE")
location = get_location(obj)
col = colour(obj)
if display_part(owners[-1], obj):
if end == start: # Full circle rather than a zero-length arc
start = 0
end = 360
if r2 != r:
start = radians(start)
start = degrees(atan2(r * sin(start), r2 * cos(start)))
end = radians(end)
end = degrees(atan2(r * sin(end), r2 * cos(end)))
kw = dict()
if width != 1:
kw.update(width=width)
self.renderer.arc((r, r2), start, end, location,
colour=col, **kw)
@_setitem(handlers, Record.BEZIER)
def handle_bezier(self, owners, obj):
obj.get_bool("ISNOTACCESIBLE")
obj.get_int("OWNERPARTID")
obj.check("LOCATIONCOUNT", b"4")
obj.get_int("INDEXINSHEET")
kw = dict(colour=colour(obj))
points = list()
for n in range(4):
n = format(1 + n)
points.append(tuple(obj.get_int(x + n) for x in "XY"))
width = get_line_width(obj)
if width != 1:
kw.update(width=width)
self.renderer.cubicbezier(*points, **kw)
@_setitem(handlers, Record.RECTANGLE)
@_setitem(handlers, Record.ROUND_RECTANGLE)
def handle_rectangle(self, owners, obj):
obj.get_int("INDEXINSHEET")
obj.get_bool("ISNOTACCESIBLE")
kw = dict(
width=get_line_width(obj),
outline=colour(obj),
)
fill = colour(obj, "AREACOLOR")
transparent = obj.get_bool("TRANSPARENT")
if obj.get_bool("ISSOLID") and not transparent:
kw.update(fill=fill)
a = get_location(obj)
b = tuple(get_int_frac(obj, "CORNER." + x) for x in "XY")
if display_part(owners[-1], obj):
if obj.get_int("RECORD") == Record.ROUND_RECTANGLE:
r = list()
for x in "XY":
radius = get_int_frac(obj, "CORNER{}RADIUS".format(x))
r.append(int(radius))
self.renderer.roundrect(r, a, b, **kw)
else:
self.renderer.rectangle(a, b, **kw)
@_setitem(handlers, Record.LABEL)
def handle_label(self, owners, obj):
for property in ("INDEXINSHEET", "ISNOTACCESIBLE"):
obj.get(property)
obj.get_bool("GRAPHICALLYLOCKED")
kw = dict(
colour=colour(obj),
offset=get_location(obj),
font=font_name(obj.get_int("FONTID")),
)
text = obj.get("TEXT")
if display_part(owners[-1], obj):
just = obj.get_int("JUSTIFICATION")
orient = obj.get_int("ORIENTATION")
if just or orient:
[horiz, vert] = divmod(just, 3)
horiz -= 1
vert = 1 - vert
obj.check("ORIENTATION", None, b"2")
if orient == 2:
horiz = -horiz
vert = -vert
kw.update(horiz=horiz, vert=vert)
if text == b"=CurrentDate":
self.renderer.text(format(self.date, "%x"), **kw)
elif text == b"=CurrentTime":
self.renderer.text(format(self.date, "%X"), **kw)
elif text == b"=DocumentFullPathAndName":
self.renderer.text(self.filename, **kw)
elif text.startswith(b"="):
self.parameter(text[1:], owners, **kw)
else:
kw = dict()
if just or orient:
kw.update(horiz=horiz, vert=vert)
self.text(obj, **kw)
@_setitem(handlers, Record.POLYGON)
def handle_polygon(self, owners, obj):
obj.get_int("INDEXINSHEET")
obj.check("ISNOTACCESIBLE", b"T")
obj.get_bool("IGNOREONLOAD")
points = list()
count = obj.get_int("LOCATIONCOUNT")
for location in range(count):
location = format(1 + location)
point = tuple(get_int_frac(obj, x + location) for x in "XY")
points.append(point)
for location in range(obj.get_int("EXTRALOCATIONCOUNT")):
location = format(count + 1 + location)
point = (get_int_frac(obj, "E" + x + location) for x in "XY")
points.append(tuple(point))
fill = colour(obj, "AREACOLOR")
kw = dict(
outline=colour(obj),
width=get_line_width(obj),
)
if obj.get_bool("ISSOLID"):
kw.update(fill=fill)
if display_part(owners[-1], obj):
self.renderer.polygon(
points=points,
**kw)
@_setitem(handlers, Record.ELLIPSE)
def handle_ellipse(self, owners, obj):
obj["OWNERPARTID"]
obj.check("ISNOTACCESIBLE", b"T")
obj.get_int("INDEXINSHEET")
fill = colour(obj, "AREACOLOR")
kw = dict()
if obj.get_bool("ISSOLID"):
kw.update(fill=fill)
self.renderer.ellipse(
r=(get_int_frac(obj, "RADIUS"),
get_int_frac(obj, "SECONDARYRADIUS")),
width=get_line_width(obj),
outline=colour(obj),
offset=get_location(obj),
**kw)
@_setitem(handlers, Record.TEXT_FRAME)
def handle_text_frame(self, owners, obj):
obj.get("CLIPTORECT")
obj.check("ALIGNMENT", b"1")
obj.get_bool("ISSOLID")
obj.get_int("OWNERPARTID")
obj.check("WORDWRAP", b"T")
obj.get_int("INDEXINSHEET")
obj.get_int("TEXTMARGIN_FRAC")
obj.get_bool("ISNOTACCESIBLE")
obj.get_bool("SHOWBORDER")
location = get_location(obj)
[lhs, _] = location
cx = get_int_frac(obj, "CORNER.X")
cy = get_int_frac(obj, "CORNER.Y")
self.renderer.rectangle(location, (cx, cy),
fill=colour(obj, "AREACOLOR"),
)
self.renderer.text(
font=font_name(obj.get_int("FONTID")),
offset=(lhs, cy),
width=cx - lhs,
text=obj["TEXT"].decode("ascii").replace("~1", "\n"),
vert=self.renderer.TOP,
colour=colour(obj),
)
@_setitem(handlers, Record.IMAGE)
def handle_image(self, owners, obj):
obj.get_int("INDEXINSHEET")
obj.check("OWNERPARTID", b"-1")
obj.get_bool("KEEPASPECT")
location = get_location(obj)