pyaltiumlib 0.6.2__tar.gz → 0.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. {pyaltiumlib-0.6.2/src/pyaltiumlib.egg-info → pyaltiumlib-0.7}/PKG-INFO +1 -1
  2. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/__init__.py +2 -2
  3. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/datatypes/__init__.py +4 -2
  4. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/datatypes/mapping.py +15 -1
  5. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/datatypes/pcblayerdefinition.py +18 -0
  6. pyaltiumlib-0.7/src/pyaltiumlib/datatypes/pcbmapping.py +129 -0
  7. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/libcomponent.py +24 -1
  8. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/pcblib/footprint.py +20 -14
  9. pyaltiumlib-0.7/src/pyaltiumlib/pcblib/lib.py +165 -0
  10. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/pcblib/records/PCBArc.py +2 -1
  11. pyaltiumlib-0.7/src/pyaltiumlib/pcblib/records/PCBComponentBody.py +41 -0
  12. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/pcblib/records/PCBFill.py +2 -1
  13. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/pcblib/records/PCBPad.py +23 -14
  14. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/pcblib/records/PCBRegion.py +1 -1
  15. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/pcblib/records/PCBString.py +2 -0
  16. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/pcblib/records/PCBTrack.py +2 -1
  17. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/pcblib/records/base.py +17 -2
  18. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7/src/pyaltiumlib.egg-info}/PKG-INFO +1 -1
  19. pyaltiumlib-0.6.2/src/pyaltiumlib/datatypes/pcbmapping.py +0 -75
  20. pyaltiumlib-0.6.2/src/pyaltiumlib/pcblib/lib.py +0 -79
  21. pyaltiumlib-0.6.2/src/pyaltiumlib/pcblib/records/PCBComponentBody.py +0 -24
  22. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/LICENSE.txt +0 -0
  23. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/README.md +0 -0
  24. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/setup.cfg +0 -0
  25. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/setup.py +0 -0
  26. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/base.py +0 -0
  27. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/datatypes/binaryreader.py +0 -0
  28. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/datatypes/coordinate.py +0 -0
  29. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/datatypes/parametercollection.py +0 -0
  30. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/datatypes/parametercolor.py +0 -0
  31. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/datatypes/parameterfont.py +0 -0
  32. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/datatypes/schematicmapping.py +0 -0
  33. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/pcblib/__init__.py +0 -0
  34. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/pcblib/records/PCBVia.py +0 -0
  35. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/pcblib/records/__init__.py +0 -0
  36. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/__init__.py +0 -0
  37. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/lib.py +0 -0
  38. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchArc.py +0 -0
  39. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchBezier.py +0 -0
  40. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchComponent.py +0 -0
  41. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchDesignator.py +0 -0
  42. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchEllipse.py +0 -0
  43. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchEllipticalArc.py +0 -0
  44. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchImplementationList.py +0 -0
  45. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchLabel.py +0 -0
  46. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchLine.py +0 -0
  47. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchParameter.py +0 -0
  48. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchPin.py +0 -0
  49. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchPolygon.py +0 -0
  50. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchPolyline.py +0 -0
  51. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchRectangle.py +0 -0
  52. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/SchRoundRectangle.py +0 -0
  53. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/__init__.py +0 -0
  54. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/records/base.py +0 -0
  55. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib/schlib/symbol.py +0 -0
  56. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib.egg-info/SOURCES.txt +0 -0
  57. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib.egg-info/dependency_links.txt +0 -0
  58. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib.egg-info/requires.txt +0 -0
  59. {pyaltiumlib-0.6.2 → pyaltiumlib-0.7}/src/pyaltiumlib.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyaltiumlib
3
- Version: 0.6.2
3
+ Version: 0.7
4
4
  Summary: PyAltiumLib is a tool to read Altium Designer library files.
5
5
  Home-page: https://github.com/ChrisHoyer/pyAltiumLib.git
6
6
  Author: Chris Hoyer
@@ -5,9 +5,9 @@ implemented in Python.
5
5
 
6
6
  AUTHOR_NAME = 'Chris Hoyer'
7
7
  AUTHOR_EMAIL = 'info@chrishoyer.de'
8
- CYEAR = '2024-2025'
8
+ CYEAR = '2024-2026'
9
9
 
10
- __version__ = "0.6.2"
10
+ __version__ = "0.7"
11
11
  __author__ = "Chris Hoyer <info@chrishoyer.de>"
12
12
 
13
13
  import os
@@ -19,8 +19,9 @@ from .schematicmapping import (
19
19
 
20
20
  # PCB related
21
21
  from .pcblayerdefinition import PCBLayerDefinition
22
- from .pcbmapping import ( PCBPadShape, PCBHoleShape, PCBStackMode,
23
- PCBTextJustification, PCBStrokeFont, PCBTextKind
22
+ from .pcbmapping import ( PCBPadShape, PCBHoleShape, PCBStackMode,
23
+ PCBTextJustification, PCBStrokeFont, PCBTextKind,
24
+ PCBLayerKind
24
25
  )
25
26
 
26
27
 
@@ -46,4 +47,5 @@ __all__ = [
46
47
  "PCBTextJustification",
47
48
  "PCBStrokeFont",
48
49
  "PCBTextKind",
50
+ "PCBLayerKind",
49
51
  ]
@@ -32,8 +32,22 @@ class MappingBase:
32
32
  def to_int(self):
33
33
  """
34
34
  Returns the integer value of the mapped object.
35
-
35
+
36
36
  :return: The integer representation.
37
37
  :rtype: int
38
38
  """
39
39
  return self.value
40
+
41
+ @classmethod
42
+ def from_name(cls, name: str):
43
+ """
44
+ Construct an instance by name string instead of integer value.
45
+
46
+ :param str name: The name string as it appears in the mapping.
47
+ :return: An instance of the class, or None if not found.
48
+ """
49
+ for value, mapped in cls._map.items():
50
+ n = mapped if isinstance(mapped, str) else mapped.get("name", "")
51
+ if n == name:
52
+ return cls(value)
53
+ logger.error(f"Failed to find name '{name}' in {cls.__name__}")
@@ -9,6 +9,7 @@ class PCBLayerDefinition:
9
9
  self.svg_layer = name.replace(' ', '_')
10
10
  self.drawing_order = drawing_order
11
11
  self.color = ParameterColor(color)
12
+ self.layer_type = 0
12
13
 
13
14
  def __repr__(self):
14
15
  return f"{self.id}, {self.name}, {self.color.to_hex()}"
@@ -103,6 +104,23 @@ class PCBLayerDefinition:
103
104
  (80, "Visible Grid 2", 100, 9467537),
104
105
  (81, "Pad Holes", 1, 9473792),
105
106
  (82, "Via Holes", 1, 24961),
107
+ # Mechanical 17-32 use IDs 83-98; IDs 73-82 are occupied by non-mechanical layers
108
+ (83, "Mechanical 17", 14, 16711935),
109
+ (84, "Mechanical 18", 14, 8388736),
110
+ (85, "Mechanical 19", 14, 32768),
111
+ (86, "Mechanical 20", 14, 8421376),
112
+ (87, "Mechanical 21", 14, 16711935),
113
+ (88, "Mechanical 22", 14, 8388736),
114
+ (89, "Mechanical 23", 14, 32768),
115
+ (90, "Mechanical 24", 14, 8421376),
116
+ (91, "Mechanical 25", 14, 16711935),
117
+ (92, "Mechanical 26", 14, 8388736),
118
+ (93, "Mechanical 27", 14, 32768),
119
+ (94, "Mechanical 28", 14, 8421376),
120
+ (95, "Mechanical 29", 14, 16711935),
121
+ (96, "Mechanical 30", 14, 8388736),
122
+ (97, "Mechanical 31", 14, 32768),
123
+ (98, "Mechanical 32", 14, 8421376),
106
124
  ]
107
125
 
108
126
 
@@ -0,0 +1,129 @@
1
+ from .mapping import MappingBase
2
+
3
+ class PCBLayerKind(MappingBase):
4
+ _map = {
5
+ 0x00: "Unspecified",
6
+ 0x01: "TopAssembly",
7
+ 0x02: "BottomAssembly",
8
+ 0x03: "AssemblyNotes",
9
+ 0x04: "BoardOutline",
10
+ 0x05: "TopConformalCoating",
11
+ 0x06: "BottomConformalCoating",
12
+ 0x07: "TopComponentCenter",
13
+ 0x08: "BottomComponentCenter",
14
+ 0x09: "TopComponentOutline",
15
+ 0x0A: "BottomComponentOutline",
16
+ 0x0B: "TopCourtyard",
17
+ 0x0C: "BottomCourtyard",
18
+ 0x0D: "TopDesignator",
19
+ 0x0E: "BottomDesignator",
20
+ 0x13: "TopGlue",
21
+ 0x14: "BottomGlue",
22
+ 0x17: "TopComponentValue",
23
+ 0x18: "BottomComponentValue",
24
+ 0x19: "VCutScoring",
25
+ 0x1A: "Top3DBody",
26
+ 0x1B: "Bottom3DBody",
27
+ 0x1C: "RoutingToolPaths",
28
+ }
29
+
30
+ # Values are in BGR (0xBBGGRR) — ParameterColor stores blue in the high byte.
31
+ # Comments show the resulting screen colour as #RRGGBB.
32
+ _colors = {
33
+ 0x01: 0xC09020, # TopAssembly — #2090C0 blue
34
+ 0x02: 0xC0C020, # BottomAssembly — #20C0C0 teal
35
+ 0x03: 0x80FFFF, # AssemblyNotes — #FFFF80 light yellow
36
+ 0x04: 0x00C0E0, # BoardOutline — #E0C000 yellow
37
+ 0x05: 0x80FF80, # TopConformalCoating — #80FF80 light green
38
+ 0x06: 0x008000, # BottomConformalCoating — #008000 green
39
+ 0x07: 0xFF00FF, # TopComponentCenter — #FF00FF magenta
40
+ 0x08: 0xFF80FF, # BottomComponentCenter — #FF80FF lighter magenta
41
+ 0x09: 0xC0C000, # TopComponentOutline — #00C0C0 cyan
42
+ 0x0A: 0x808000, # BottomComponentOutline — #008080 dark cyan
43
+ 0x0B: 0x00CCFF, # TopCourtyard — #FFCC00 amber
44
+ 0x0C: 0x60E0FF, # BottomCourtyard — #FFE060 lighter amber
45
+ 0x0D: 0xFFFFFF, # TopDesignator — #FFFFFF white
46
+ 0x0E: 0xC0C0C0, # BottomDesignator — #C0C0C0 light grey
47
+ 0x13: 0x0000C0, # TopGlue — #C00000 red
48
+ 0x14: 0x000080, # BottomGlue — #800000 dark red
49
+ 0x17: 0xFFFFFF, # TopComponentValue — #FFFFFF white
50
+ 0x18: 0xC0C0C0, # BottomComponentValue — #C0C0C0 light grey
51
+ 0x19: 0xFFFF00, # VCutScoring — #00FFFF cyan
52
+ 0x1A: 0x808080, # Top3DBody — #808080 grey
53
+ 0x1B: 0x404040, # Bottom3DBody — #404040 dark grey
54
+ 0x1C: 0x0080FF, # RoutingToolPaths — #FF8000 orange
55
+ }
56
+
57
+ class PCBPadShape(MappingBase):
58
+ _map = {
59
+ 0: "None",
60
+ 1: "Round",
61
+ 2: "Rectangular",
62
+ 3: "Octagonal",
63
+ 9: "Rounded Rectangle"
64
+ }
65
+
66
+ class PCBHoleShape(MappingBase):
67
+ _map = {
68
+ -1: "None",
69
+ 0: "Round",
70
+ 1: "Square",
71
+ 2: "Slot",
72
+ }
73
+
74
+ class PCBStackMode(MappingBase):
75
+ _map = {
76
+ 0: "Simple",
77
+ 1: "TopMiddleBottom",
78
+ 2: "FullStack",
79
+ }
80
+
81
+ class PCBStrokeFont(MappingBase):
82
+ _map = {
83
+ 0: "Default",
84
+ 1: "SansSerif",
85
+ 2: "Serif",
86
+ }
87
+
88
+ class PCBTextKind(MappingBase):
89
+ _map = {
90
+ 0: {"name": "Stroke", "default_font": "UHF"},
91
+ 1: {"name": "TrueType", "default_font": "Arial"},
92
+ 2: {"name": "BarCode", "default_font": "Arial"},
93
+ }
94
+
95
+ def get_name(self):
96
+ return self._map[self.value]["name"]
97
+
98
+ def get_font(self):
99
+ return self._map[self.value]["default_font"]
100
+
101
+ def __eq__(self, other):
102
+ if not isinstance(other, PCBTextKind):
103
+ return False
104
+ return (
105
+ self.get_name() == other.get_name()
106
+ and self.get_font() == other.get_font()
107
+ )
108
+
109
+ class PCBTextJustification(MappingBase):
110
+ _map = {
111
+ 1: {"name": "BottomRight", "vertical": "text-after-edge", "horizontal": "start"},
112
+ 2: {"name": "MiddleRight", "vertical": "central", "horizontal": "start"},
113
+ 3: {"name": "TopRight", "vertical": "text-before-edge", "horizontal": "start"},
114
+ 4: {"name": "BottomCenter", "vertical": "text-after-edge", "horizontal": "middle"},
115
+ 5: {"name": "MiddleCenter", "vertical": "central", "horizontal": "middle"},
116
+ 6: {"name": "TopCenter", "vertical": "text-before-edge", "horizontal": "middle"},
117
+ 7: {"name": "BottomLeft", "vertical": "text-after-edge", "horizontal": "end"},
118
+ 8: {"name": "MiddleLeft", "vertical": "central", "horizontal": "end"},
119
+ 9: {"name": "TopLeft", "vertical": "text-before-edge", "horizontal": "end"},
120
+ }
121
+
122
+ def get_name(self):
123
+ return self._map[self.value]["name"]
124
+
125
+ def get_vertical(self):
126
+ return self._map[self.value]["vertical"]
127
+
128
+ def get_horizontal(self):
129
+ return self._map[self.value]["horizontal"]
@@ -70,7 +70,8 @@ class LibComponent:
70
70
 
71
71
 
72
72
  def draw_svg(self, graphic, size_x: float, size_y: float,
73
- draw_bbox: bool = False, draw_designator: bool = False) -> None:
73
+ draw_bbox: bool = False, draw_designator: bool = False,
74
+ layer_kinds=None) -> None:
74
75
  """
75
76
  Draw all drawable and initialized records the component to an svg drawing.
76
77
  All records are autoscaled to fit the given drawing object size.
@@ -125,8 +126,30 @@ class LibComponent:
125
126
  for obj in validObj:
126
127
  obj.draw_bounding_box( graphic, offset, zoom)
127
128
 
129
+ # Build layer lookup for kind-based filtering
130
+ layer_map = {}
131
+ if hasattr(self, 'LibFile') and hasattr(self.LibFile, 'Layers'):
132
+ layer_map = {l.id: l for l in self.LibFile.Layers}
133
+
134
+ if layer_kinds is not None:
135
+ from pyaltiumlib.datatypes import PCBLayerKind
136
+ kind_values = set()
137
+ for k in layer_kinds:
138
+ if isinstance(k, str):
139
+ resolved = PCBLayerKind.from_name(k)
140
+ if resolved is not None:
141
+ kind_values.add(resolved.value)
142
+ elif hasattr(k, 'value'):
143
+ kind_values.add(k.value)
144
+ else:
145
+ kind_values.add(int(k))
146
+
128
147
  # Draw Primitives
129
148
  for obj in validObj:
149
+ if layer_kinds is not None and hasattr(obj, 'layer'):
150
+ lyr = layer_map.get(obj.layer)
151
+ if lyr and lyr.layer_type != 0 and lyr.layer_type.value not in kind_values:
152
+ continue
130
153
  obj.draw_svg( graphic, offset, zoom)
131
154
 
132
155
 
@@ -85,19 +85,25 @@ class PcbLibFootprint(LibComponent):
85
85
 
86
86
  except Exception as e:
87
87
  logger.error(f"Failed to read data of '{self.Name}'. Exception: {e}")
88
- raise
88
+ raise
89
89
 
90
+ # =============================================================================
91
+ # Public API
92
+ # =============================================================================
90
93
 
91
-
92
-
93
-
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
94
+ def get_records(self, *, kind=None, name=None, id=None):
95
+ """Return all records on the layer matching the given criterion.
96
+
97
+ Accepts the same keyword arguments as :py:meth:`PcbLib.get_layer`.
98
+ Exactly one must be supplied. Returns an empty list if the layer is
99
+ not found or has no records on it.
100
+
101
+ :param str kind: Layer kind name, e.g. ``"TopCourtyard"``
102
+ :param str name: Layer name, e.g. ``"Mechanical 21"``
103
+ :param int id: Internal layer ID
104
+ :rtype: list
105
+ """
106
+ layer = self.LibFile.get_layer(kind=kind, name=name, id=id)
107
+ if layer is None:
108
+ return []
109
+ return [r for r in self.Records if hasattr(r, 'layer') and r.layer == layer.id]
@@ -0,0 +1,165 @@
1
+ from pyaltiumlib.base import GenericLibFile
2
+ from pyaltiumlib.datatypes import BinaryReader, ParameterCollection, ParameterColor, PCBLayerDefinition, PCBLayerKind
3
+ from pyaltiumlib.pcblib.footprint import PcbLibFootprint
4
+
5
+ # Set up logging
6
+ import logging
7
+ logger = logging.getLogger(__name__)
8
+
9
+ class PcbLib(GenericLibFile):
10
+ """
11
+ PCB class for handling Altium Designer PCB library files.
12
+ During initialization the library file will be read.
13
+
14
+ :param string filepath: The path to the .PcbLib library file
15
+ :param io.BytesIO oleobj: A file-like object containing the altium library file binary stream
16
+
17
+ :raises FileNotFoundError: If file is not a supported file.
18
+ :raises ValueError: If library data or header can not be read
19
+ """
20
+
21
+ def __init__(self, filepath, oleobj):
22
+ super().__init__(filepath, oleobj)
23
+
24
+ self.LibType = "PCB"
25
+
26
+ self.Layers = PCBLayerDefinition.LoadDefaultLayers()
27
+ """
28
+ Collection with default PCB Layer Definition
29
+ """
30
+
31
+ self._ReadPCBLibrary()
32
+
33
+ self.OleObj.close()
34
+ logger.info(f"Reading and extracting of '{self.FileName}' done.")
35
+
36
+ # =============================================================================
37
+ # Internal content reading related functions
38
+ # =============================================================================
39
+
40
+
41
+ def _ReadPCBLibrary(self):
42
+ try:
43
+ self._ReadPCBFileHeader()
44
+ self._ReadPCBLibraryData()
45
+ self._ReadLayerKindMapping()
46
+
47
+ except Exception as e:
48
+ logger.error(f"Failed to read library: {e}")
49
+ raise
50
+
51
+ def _ReadPCBFileHeader(self):
52
+
53
+ # Fileheader is different from usual string block concept
54
+ fileheader_stream = self._OpenStream("", "FileHeader")
55
+ length_block = fileheader_stream.read(4)
56
+ length_string = fileheader_stream.read(1)
57
+
58
+ if int.from_bytes(length_block, "little") == int.from_bytes(length_string, "little"):
59
+ self.LibHeader = fileheader_stream.read( int.from_bytes(length_string, "little") )
60
+ self.LibHeader = self.LibHeader.decode("UTF-8")
61
+
62
+ logger.debug(f" Fileheader of library file '{self.FileName}' is '{self.LibHeader}'.")
63
+ if "PCB" in self.LibHeader and "Binary Library File" in self.LibHeader:
64
+ logger.info(f"File '{self.FileName}' identified as pcb binary library file.")
65
+ else:
66
+ logger.warning(f"File '{self.FilePath}' can not be identified as pcb binary library!")
67
+
68
+
69
+ def _ReadPCBLibraryData(self):
70
+
71
+ # Parse Library Data File
72
+ LibDataStream = self._OpenStream("Library", "Data")
73
+ self._FileHeader = ParameterCollection.from_block( LibDataStream )
74
+
75
+ self.ComponentCount = int.from_bytes( LibDataStream.read(4), "little")
76
+ logger.info(f"Start extracting {self.ComponentCount} component(s) from '{self.FileName}'.")
77
+
78
+ for lib_ref in [BinaryReader.from_stream( LibDataStream ).read_string_block() for index in range(self.ComponentCount)]:
79
+ self.Parts.append( PcbLibFootprint( self, lib_ref ) )
80
+
81
+
82
+ def _ReadLayerKindMapping(self):
83
+ try:
84
+ stream = self.OleObj.openstream("Library/LayerKindMapping/Data")
85
+ except Exception:
86
+ logger.debug("No LayerKindMapping stream — skipping mechanical layer type extraction.")
87
+ return
88
+
89
+ raw = stream.read()
90
+ if len(raw) < 20:
91
+ return
92
+
93
+ # Binary format:
94
+ # 0: uint32 version block size (= 8)
95
+ # 4: 8 bytes UTF-16LE version string "1.0\0"
96
+ # 12: 4 bytes unknown
97
+ # 16: uint32 entry count
98
+ # 20: count * (uint32 layer_id, uint32 kind)
99
+ version_size = int.from_bytes(raw[0:4], 'little')
100
+ offset = 4 + version_size + 4 # skip version block + unknown bytes
101
+ count = int.from_bytes(raw[offset:offset + 4], 'little')
102
+ offset += 4
103
+
104
+ MECH_BASE = 0x04000000
105
+ layer_by_id = {layer.id: layer for layer in self.Layers}
106
+
107
+ for _ in range(count):
108
+ if offset + 8 > len(raw):
109
+ break
110
+ layer_id = int.from_bytes(raw[offset:offset + 4], 'little')
111
+ kind = int.from_bytes(raw[offset + 4:offset + 8], 'little')
112
+ offset += 8
113
+
114
+ if layer_id & 0xFF000000 == MECH_BASE:
115
+ mech_num = layer_id & 0xFF
116
+ if not (17 <= mech_num <= 32):
117
+ logger.debug(f"LayerKindMapping: unexpected extended mech number {mech_num}, skipping")
118
+ continue
119
+ # IDs 73-82 are occupied (Drill Drawing, Multi-Layer, etc.),
120
+ # so Mech 17-32 map to IDs 83-98: 66 + mech_num
121
+ layer_id = 66 + mech_num
122
+
123
+ if layer_id in layer_by_id:
124
+ if kind in PCBLayerKind._map:
125
+ layer_by_id[layer_id].layer_type = PCBLayerKind(kind)
126
+ if kind in PCBLayerKind._colors:
127
+ layer_by_id[layer_id].color = ParameterColor(PCBLayerKind._colors[kind])
128
+ else:
129
+ logger.debug(f"LayerKindMapping: unknown kind {kind:#04x} for layer {layer_id}")
130
+ else:
131
+ logger.debug(f"LayerKindMapping: no layer for id {layer_id}")
132
+
133
+ # =============================================================================
134
+ # Public API
135
+ # =============================================================================
136
+
137
+ def get_layer(self, *, kind=None, name=None, id=None):
138
+ """Return the layer matching the given criterion, or None if not found.
139
+
140
+ Exactly one keyword argument must be supplied.
141
+
142
+ :param str kind: Layer kind name, e.g. ``"TopCourtyard"``
143
+ :param str name: Layer name, e.g. ``"Mechanical 21"``
144
+ :param int id: Internal layer ID. Note: Mech 17–32 have IDs 83–98 (not 73–88),
145
+ because 73–82 are occupied by Drill Drawing, Multi-Layer, etc.
146
+ :rtype: PCBLayerDefinition or None
147
+ :raises ValueError: If not exactly one keyword argument is supplied
148
+ """
149
+ provided = sum(x is not None for x in (kind, name, id))
150
+ if provided != 1:
151
+ raise ValueError("Exactly one of kind=, name=, or id= must be supplied")
152
+
153
+ if id is not None:
154
+ return next((l for l in self.Layers if l.id == id), None)
155
+ if name is not None:
156
+ return next((l for l in self.Layers if l.name == name), None)
157
+ # kind
158
+ target = PCBLayerKind.from_name(kind)
159
+ if target is None:
160
+ return None
161
+ return next(
162
+ (l for l in self.Layers if l.layer_type != 0 and l.layer_type.value == target.value),
163
+ None
164
+ )
165
+
@@ -34,7 +34,8 @@ class PcbArc(GenericPCBRecord):
34
34
  self.angle_start = block.read_double()
35
35
  self.angle_end = block.read_double()
36
36
  self.linewidth = Coordinate.parse_bin(block.read(4))
37
-
37
+ self._apply_extended_layer(block.data[block.offset:])
38
+
38
39
  if self.layer > 0: self.is_drawable = True
39
40
 
40
41
  except Exception as e:
@@ -0,0 +1,41 @@
1
+ from pyaltiumlib.pcblib.records.base import GenericPCBRecord
2
+ from pyaltiumlib.datatypes import BinaryReader
3
+
4
+
5
+ # Configure logging
6
+ import logging
7
+ logger = logging.getLogger(__name__)
8
+
9
+ class PcbComponentBody(GenericPCBRecord):
10
+ """
11
+ Implementation of a pcb record
12
+ See also :ref:`PCBPrimitive12` details on this PCB records. This record can be drawn.
13
+
14
+ :param class parent: Parent symbol object
15
+ :param Dict data: Dictionary containing raw record data
16
+ """
17
+ def __init__(self, parent, stream):
18
+
19
+ super().__init__(parent)
20
+
21
+ block = BinaryReader.from_stream( stream )
22
+ BinaryReader.from_stream( stream ) # trailing block; advance stream past it
23
+
24
+ if block.has_content():
25
+ # No standard binary common header — layer is encoded as V7_LAYER=MECHANICAL{N}
26
+ # in the pipe-delimited text section of the block.
27
+ idx = block.data.find(b'V7_LAYER=')
28
+ if idx >= 0:
29
+ end = block.data.find(b'|', idx)
30
+ if end < 0:
31
+ end = len(block.data)
32
+ value = block.data[idx+9:end].decode('latin-1', errors='replace').strip()
33
+ if value.upper().startswith('MECHANICAL'):
34
+ try:
35
+ n = int(value[10:])
36
+ # Mech 1-16 → layer IDs 57-72 (56+N); Mech 17-32 → IDs 83-98 (66+N)
37
+ self.layer = (56 + n) if n <= 16 else (66 + n)
38
+ except ValueError:
39
+ logger.debug(f"PcbComponentBody: could not parse layer from V7_LAYER={value}")
40
+
41
+
@@ -26,7 +26,8 @@ class PcbFill(GenericPCBRecord):
26
26
  self.corner1 = block.read_bin_coord()
27
27
  self.corner2 = block.read_bin_coord()
28
28
  self.rotation = block.read_double()
29
-
29
+ self._apply_extended_layer(block.data[block.offset:])
30
+
30
31
  if self.layer > 0: self.is_drawable = True
31
32
 
32
33
  except Exception as e:
@@ -282,29 +282,38 @@ class PcbPad(GenericPCBRecord):
282
282
  )
283
283
 
284
284
  elif shape.to_int() == 3:
285
-
286
- edge_length = min(size.y, size.x) / 2
287
- diagonal_offset = int(edge_length / 2)
288
-
285
+
286
+ w = size.x
287
+ h = size.y
288
+ chamfer = min(w, h) / 4
289
+
289
290
  vertices = [
290
- (int(center.x - diagonal_offset), int(center.y - edge_length)),
291
- (int(center.x + diagonal_offset), int(center.y - edge_length)),
292
- (int(center.x + edge_length), int(center.y - diagonal_offset)),
293
- (int(center.x + edge_length), int(center.y + diagonal_offset)),
294
- (int(center.x + diagonal_offset), int(center.y + edge_length)),
295
- (int(center.x - diagonal_offset), int(center.y + edge_length)),
296
- (int(center.x - edge_length), int(center.y + diagonal_offset)),
297
- (int(center.x - edge_length), int(center.y - diagonal_offset)),
291
+ (int(center.x - w/2 + chamfer), int(center.y - h/2)),
292
+ (int(center.x + w/2 - chamfer), int(center.y - h/2)),
293
+ (int(center.x + w/2), int(center.y - h/2 + chamfer)),
294
+ (int(center.x + w/2), int(center.y + h/2 - chamfer)),
295
+ (int(center.x + w/2 - chamfer), int(center.y + h/2)),
296
+ (int(center.x - w/2 + chamfer), int(center.y + h/2)),
297
+ (int(center.x - w/2), int(center.y + h/2 - chamfer)),
298
+ (int(center.x - w/2), int(center.y - h/2 + chamfer)),
298
299
  ]
299
-
300
+
300
301
  drawing_primitive = dwg.polygon(points = vertices,
301
302
  fill = layer.color.to_hex(),
302
303
  transform=f"rotate(-{self.rotation} {center.x} {center.y})"
303
304
  )
304
305
 
305
306
 
307
+ elif shape.to_int() == 9:
308
+ path = self.get_svg_rounded_rect_path(start, size, plot_layer,
309
+ self.corner_radius_percentage[ref_layer-1] if self.corner_radius_percentage else 25)
310
+ drawing_primitive = dwg.path(d=path,
311
+ fill=layer.color.to_hex(),
312
+ transform=f"rotate(-{self.rotation} {center.x} {center.y})"
313
+ )
314
+
306
315
  else:
307
- print(f"Unknown pad shape: {shape}")
316
+ logger.warning(f"Unknown pad shape: {shape}")
308
317
 
309
318
  self.Footprint._graphic_layers[plot_layer].add( drawing_primitive )
310
319
 
@@ -28,7 +28,7 @@ class PcbRegion(GenericPCBRecord):
28
28
  block.read_byte() # Unknown
29
29
 
30
30
  self.parameter = ParameterCollection( block.read_string_block(size_string = 4))
31
-
31
+
32
32
  self.num_vertices = block.read_int32()
33
33
  self.vertices = [ block.read_bin_coord( double=True ) for i in range(self.num_vertices)]
34
34
 
@@ -68,6 +68,8 @@ class PcbString(GenericPCBRecord):
68
68
  self.font_inverted_rect_text_offset = block.read_int32()
69
69
 
70
70
 
71
+ self._apply_extended_layer(block.data[block.offset:])
72
+
71
73
  if string.has_content():
72
74
  self.text = string.read_string_block()
73
75
 
@@ -28,7 +28,8 @@ class PcbTrack(GenericPCBRecord):
28
28
  self.start = block.read_bin_coord()
29
29
  self.end = block.read_bin_coord()
30
30
  self.linewidth = Coordinate.parse_bin(block.read(4))
31
-
31
+ self._apply_extended_layer(block.data[block.offset:])
32
+
32
33
  if self.layer > 0: self.is_drawable = True
33
34
 
34
35
  except Exception as e:
@@ -36,7 +36,7 @@ class GenericPCBRecord:
36
36
  logger.error("PCB reecord common parameters array length is not 13!")
37
37
 
38
38
  self.layer = byte_array[0]
39
-
39
+
40
40
  self.unlocked = bool( byte_array[1] & 0x04 )
41
41
  self.tenting_top = bool( byte_array[1] & 0x20 )
42
42
  self.tenting_bottom = bool( byte_array[1] & 0x40 )
@@ -63,6 +63,21 @@ class GenericPCBRecord:
63
63
  return None
64
64
 
65
65
 
66
+ def _apply_extended_layer(self, remaining: bytes):
67
+ """Override self.layer for Mech 17–32 records.
68
+
69
+ Binary records on extended mechanical layers store 72 (Mech 16) in the
70
+ common header. The true layer N appears as a single byte immediately
71
+ before the marker \\x00\\x02\\x01 in the trailing bytes of the block.
72
+ """
73
+ if self.layer != 72:
74
+ return
75
+ idx = remaining.find(b'\x00\x02\x01')
76
+ if idx > 0:
77
+ n = remaining[idx - 1]
78
+ if 17 <= n <= 32:
79
+ self.layer = 66 + n
80
+
66
81
  def get_svg_arc_path(self, center, radius_x, radius_y, angle_start, angle_end):
67
82
  """
68
83
  This function returns the svg path data for an arc.
@@ -168,7 +183,7 @@ class GenericPCBRecord:
168
183
  end = (bbox[1] * zoom) + offset
169
184
 
170
185
  lower_left_x = min(start.x, end.x)
171
- lower_left_y = min(start.x, end.y)
186
+ lower_left_y = min(start.y, end.y)
172
187
  insert = CoordinatePoint( Coordinate(lower_left_x), Coordinate(lower_left_y) )
173
188
 
174
189
  size = start - end
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyaltiumlib
3
- Version: 0.6.2
3
+ Version: 0.7
4
4
  Summary: PyAltiumLib is a tool to read Altium Designer library files.
5
5
  Home-page: https://github.com/ChrisHoyer/pyAltiumLib.git
6
6
  Author: Chris Hoyer
@@ -1,75 +0,0 @@
1
- from .mapping import MappingBase
2
-
3
- class PCBPadShape(MappingBase):
4
- _map = {
5
- 0: "None",
6
- 1: "Round",
7
- 2: "Rectangular",
8
- 3: "Octagonal",
9
- 9: "Rounded Rectangle"
10
- }
11
-
12
- class PCBHoleShape(MappingBase):
13
- _map = {
14
- -1: "None",
15
- 0: "Round",
16
- 1: "Square",
17
- 2: "Slot",
18
- }
19
-
20
- class PCBStackMode(MappingBase):
21
- _map = {
22
- 0: "Simple",
23
- 1: "TopMiddleBottom",
24
- 2: "FullStack",
25
- }
26
-
27
- class PCBStrokeFont(MappingBase):
28
- _map = {
29
- 0: "Default",
30
- 1: "SansSerif",
31
- 2: "Serif",
32
- }
33
-
34
- class PCBTextKind(MappingBase):
35
- _map = {
36
- 0: {"name": "Stroke", "default_font": "UHF"},
37
- 1: {"name": "TrueType", "default_font": "Arial"},
38
- 2: {"name": "BarCode", "default_font": "Arial"},
39
- }
40
-
41
- def get_name(self):
42
- return self._map[self.value]["name"]
43
-
44
- def get_font(self):
45
- return self._map[self.value]["default_font"]
46
-
47
- def __eq__(self, other):
48
- if not isinstance(other, PCBTextKind):
49
- return False
50
- return (
51
- self.get_name() == other.get_name()
52
- and self.get_font() == other.get_font()
53
- )
54
-
55
- class PCBTextJustification(MappingBase):
56
- _map = {
57
- 1: {"name": "BottomRight", "vertical": "text-after-edge", "horizontal": "start"},
58
- 2: {"name": "MiddleRight", "vertical": "central", "horizontal": "start"},
59
- 3: {"name": "TopRight", "vertical": "text-before-edge", "horizontal": "start"},
60
- 4: {"name": "BottomCenter", "vertical": "text-after-edge", "horizontal": "middle"},
61
- 5: {"name": "MiddleCenter", "vertical": "central", "horizontal": "middle"},
62
- 6: {"name": "TopCenter", "vertical": "text-before-edge", "horizontal": "middle"},
63
- 7: {"name": "BottomLeft", "vertical": "text-after-edge", "horizontal": "end"},
64
- 8: {"name": "MiddleLeft", "vertical": "central", "horizontal": "end"},
65
- 9: {"name": "TopLeft", "vertical": "text-before-edge", "horizontal": "end"},
66
- }
67
-
68
- def get_name(self):
69
- return self._map[self.value]["name"]
70
-
71
- def get_vertical(self):
72
- return self._map[self.value]["vertical"]
73
-
74
- def get_horizontal(self):
75
- return self._map[self.value]["horizontal"]
@@ -1,79 +0,0 @@
1
- from pyaltiumlib.base import GenericLibFile
2
- from pyaltiumlib.datatypes import BinaryReader, ParameterCollection, PCBLayerDefinition
3
- from pyaltiumlib.pcblib.footprint import PcbLibFootprint
4
-
5
- # Set up logging
6
- import logging
7
- logger = logging.getLogger(__name__)
8
-
9
- class PcbLib(GenericLibFile):
10
- """
11
- PCB class for handling Altium Designer PCB library files.
12
- During initialization the library file will be read.
13
-
14
- :param string filepath: The path to the .PcbLib library file
15
- :param io.BytesIO oleobj: A file-like object containing the altium library file binary stream
16
-
17
- :raises FileNotFoundError: If file is not a supported file.
18
- :raises ValueError: If library data or header can not be read
19
- """
20
-
21
- def __init__(self, filepath, oleobj):
22
- super().__init__(filepath, oleobj)
23
-
24
- self.LibType = "PCB"
25
-
26
- self.Layers = PCBLayerDefinition.LoadDefaultLayers()
27
- """
28
- Collection with default PCB Layer Definition
29
- """
30
-
31
- self._ReadPCBLibrary()
32
-
33
- self.OleObj.close()
34
- logger.info(f"Reading and extracting of '{self.FileName}' done.")
35
-
36
- # =============================================================================
37
- # Internal content reading related functions
38
- # =============================================================================
39
-
40
-
41
- def _ReadPCBLibrary(self):
42
- try:
43
- self._ReadPCBFileHeader()
44
- self._ReadPCBLibraryData()
45
-
46
- except Exception as e:
47
- logger.error(f"Failed to read library: {e}")
48
- raise
49
-
50
- def _ReadPCBFileHeader(self):
51
-
52
- # Fileheader is different from usual string block concept
53
- fileheader_stream = self._OpenStream("", "FileHeader")
54
- length_block = fileheader_stream.read(4)
55
- length_string = fileheader_stream.read(1)
56
-
57
- if int.from_bytes(length_block, "little") == int.from_bytes(length_string, "little"):
58
- self.LibHeader = fileheader_stream.read( int.from_bytes(length_string, "little") )
59
- self.LibHeader = self.LibHeader.decode("UTF-8")
60
-
61
- logger.debug(f" Fileheader of library file '{self.FileName}' is '{self.LibHeader}'.")
62
- if "PCB" in self.LibHeader and "Binary Library File" in self.LibHeader:
63
- logger.info(f"File '{self.FileName}' identified as pcb binary library file.")
64
- else:
65
- logger.warning(f"File '{self.FilePath}' can not be identified as pcb binary library!")
66
-
67
-
68
- def _ReadPCBLibraryData(self):
69
-
70
- # Parse Library Data File
71
- LibDataStream = self._OpenStream("Library", "Data")
72
- self._FileHeader = ParameterCollection.from_block( LibDataStream )
73
-
74
- self.ComponentCount = int.from_bytes( LibDataStream.read(4), "little")
75
- logger.info(f"Start extracting {self.ComponentCount} component(s) from '{self.FileName}'.")
76
-
77
- for lib_ref in [BinaryReader.from_stream( LibDataStream ).read_string_block() for index in range(self.ComponentCount)]:
78
- self.Parts.append( PcbLibFootprint( self, lib_ref ) )
79
-
@@ -1,24 +0,0 @@
1
- from pyaltiumlib.pcblib.records.base import GenericPCBRecord
2
- from pyaltiumlib.datatypes import BinaryReader
3
-
4
-
5
- # Configure logging
6
- import logging
7
- logger = logging.getLogger(__name__)
8
-
9
- class PcbComponentBody(GenericPCBRecord):
10
- """
11
- Implementation of a pcb record
12
- See also :ref:`PCBPrimitive12` details on this PCB records. This record can be drawn.
13
-
14
- :param class parent: Parent symbol object
15
- :param Dict data: Dictionary containing raw record data
16
- """
17
- def __init__(self, parent, stream):
18
-
19
- super().__init__(parent)
20
-
21
- block = BinaryReader.from_stream( stream )
22
- string = BinaryReader.from_stream( stream )
23
-
24
-
File without changes
File without changes
File without changes
File without changes