pyaltiumlib 0.7__tar.gz → 0.7.2__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 (58) hide show
  1. {pyaltiumlib-0.7/src/pyaltiumlib.egg-info → pyaltiumlib-0.7.2}/PKG-INFO +1 -1
  2. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/__init__.py +1 -2
  3. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/datatypes/binaryreader.py +5 -16
  4. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/datatypes/coordinate.py +14 -7
  5. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/datatypes/parametercollection.py +3 -5
  6. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/libcomponent.py +10 -15
  7. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/footprint.py +2 -0
  8. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/records/PCBArc.py +36 -12
  9. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/records/PCBComponentBody.py +0 -1
  10. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/records/PCBPad.py +13 -3
  11. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/records/PCBString.py +1 -1
  12. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/records/PCBVia.py +5 -4
  13. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/records/base.py +3 -83
  14. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/lib.py +2 -2
  15. pyaltiumlib-0.7.2/src/pyaltiumlib/schlib/records/base.py +81 -0
  16. pyaltiumlib-0.7.2/src/pyaltiumlib/svgrecord.py +90 -0
  17. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2/src/pyaltiumlib.egg-info}/PKG-INFO +1 -1
  18. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib.egg-info/SOURCES.txt +1 -0
  19. pyaltiumlib-0.7/src/pyaltiumlib/schlib/records/base.py +0 -160
  20. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/LICENSE.txt +0 -0
  21. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/README.md +0 -0
  22. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/setup.cfg +0 -0
  23. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/setup.py +0 -0
  24. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/base.py +0 -0
  25. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/datatypes/__init__.py +0 -0
  26. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/datatypes/mapping.py +0 -0
  27. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/datatypes/parametercolor.py +0 -0
  28. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/datatypes/parameterfont.py +0 -0
  29. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/datatypes/pcblayerdefinition.py +0 -0
  30. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/datatypes/pcbmapping.py +0 -0
  31. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/datatypes/schematicmapping.py +0 -0
  32. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/__init__.py +0 -0
  33. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/lib.py +0 -0
  34. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/records/PCBFill.py +0 -0
  35. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/records/PCBRegion.py +0 -0
  36. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/records/PCBTrack.py +0 -0
  37. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/pcblib/records/__init__.py +0 -0
  38. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/__init__.py +0 -0
  39. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchArc.py +0 -0
  40. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchBezier.py +0 -0
  41. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchComponent.py +0 -0
  42. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchDesignator.py +0 -0
  43. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchEllipse.py +0 -0
  44. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchEllipticalArc.py +0 -0
  45. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchImplementationList.py +0 -0
  46. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchLabel.py +0 -0
  47. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchLine.py +0 -0
  48. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchParameter.py +0 -0
  49. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchPin.py +0 -0
  50. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchPolygon.py +0 -0
  51. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchPolyline.py +0 -0
  52. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchRectangle.py +0 -0
  53. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/SchRoundRectangle.py +0 -0
  54. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/records/__init__.py +0 -0
  55. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib/schlib/symbol.py +0 -0
  56. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib.egg-info/dependency_links.txt +0 -0
  57. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/src/pyaltiumlib.egg-info/requires.txt +0 -0
  58. {pyaltiumlib-0.7 → pyaltiumlib-0.7.2}/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.7
3
+ Version: 0.7.2
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
@@ -7,7 +7,7 @@ AUTHOR_NAME = 'Chris Hoyer'
7
7
  AUTHOR_EMAIL = 'info@chrishoyer.de'
8
8
  CYEAR = '2024-2026'
9
9
 
10
- __version__ = "0.7"
10
+ __version__ = "0.7.2"
11
11
  __author__ = "Chris Hoyer <info@chrishoyer.de>"
12
12
 
13
13
  import os
@@ -20,7 +20,6 @@ from pyaltiumlib.pcblib.lib import PcbLib
20
20
  import logging
21
21
  logger = logging.getLogger(__name__)
22
22
 
23
- @staticmethod
24
23
  def read(filepath: str, libfile_obj = None) -> Union[SchLib, PcbLib]:
25
24
  """
26
25
  Reads an Altium library file and returns the corresponding library object.
@@ -1,4 +1,5 @@
1
1
  from pyaltiumlib.datatypes.coordinate import Coordinate, CoordinatePoint
2
+ import struct
2
3
 
3
4
  # Configure logging
4
5
  import logging
@@ -82,7 +83,7 @@ class BinaryReader:
82
83
  :return: The integer value.
83
84
  :rtype: int
84
85
  """
85
- return int.from_bytes(self.read_byte(), signed=signed)
86
+ return int.from_bytes(self.read_byte(), byteorder="little", signed=signed)
86
87
 
87
88
  def read_int16(self, signed=False):
88
89
  """
@@ -111,20 +112,7 @@ class BinaryReader:
111
112
  :return: The double value.
112
113
  :rtype: float
113
114
  """
114
- value = int.from_bytes(self.read(8), byteorder='little', signed=False)
115
- sign = (value >> 63) & 0x1
116
- exponent = (value >> 52) & 0x7FF
117
- mantissa = value & ((1 << 52) - 1)
118
-
119
- if exponent == 0x7FF:
120
- return float('inf') if mantissa == 0 else float('nan')
121
-
122
- if exponent == 0:
123
- result = (mantissa / (1 << 52)) * (2 ** (-1022))
124
- else:
125
- result = (1 + (mantissa / (1 << 52))) * (2 ** (exponent - 1023))
126
-
127
- return -result if sign == 1 else result
115
+ return struct.unpack('<d', self.read(8).ljust(8, b'\x00'))[0]
128
116
 
129
117
  def read_string_block(self, size_string=1):
130
118
  """
@@ -180,7 +168,8 @@ class BinaryReader:
180
168
 
181
169
  if self.offset + 2 > len(self.data):
182
170
  logger.warning("Not enough data to read.")
183
-
171
+ break
172
+
184
173
  unicode_char = self.read(2)
185
174
  if unicode_char == b'\x00\x00': # Null terminator
186
175
  break
@@ -69,7 +69,7 @@ class Coordinate:
69
69
  # ================== Math Functions =========================================
70
70
 
71
71
  def __abs__(self):
72
- return abs(int(self.value))
72
+ return abs(self.value)
73
73
 
74
74
  def __truediv__(self, other):
75
75
  if isinstance(other, (int, float)):
@@ -107,17 +107,24 @@ class Coordinate:
107
107
  return NotImplemented
108
108
 
109
109
  def __rtruediv__(self, other):
110
- return self.__div__(other)
111
-
110
+ return Coordinate(other) / self
111
+
112
112
  def __rmul__(self, other):
113
113
  return self.__mul__(other)
114
-
114
+
115
115
  def __radd__(self, other):
116
116
  return self.__add__(other)
117
-
117
+
118
118
  def __rsub__(self, other):
119
- return self.__sub__(other)
120
-
119
+ return Coordinate(other) - self
120
+
121
+ def __eq__(self, other):
122
+ if isinstance(other, Coordinate):
123
+ return self.value == other.value
124
+ elif isinstance(other, (int, float)):
125
+ return self.value == other
126
+ return NotImplemented
127
+
121
128
  def __lt__(self, other):
122
129
  if isinstance(other, Coordinate):
123
130
  return self.value < other.value
@@ -147,7 +147,7 @@ class ParameterCollection:
147
147
  if isinstance(value, str):
148
148
  return int(value)
149
149
 
150
- if isinstance(value, int, float):
150
+ if isinstance(value, (int, float)):
151
151
  return int(value)
152
152
  else:
153
153
  return default
@@ -169,10 +169,8 @@ class ParameterCollection:
169
169
  return
170
170
 
171
171
  if isinstance(data, bytes):
172
- try:
173
- decoded_data = data.decode('windows-1252')
174
- except UnicodeDecodeError as e:
175
- logger.error(f"Failed to decode data using Windows-1252 encoding: {e}")
172
+ # %UTF8% fields hold UTF-8 bytes that cp1252 cannot always decode
173
+ decoded_data = data.decode('windows-1252', errors='replace')
176
174
  else:
177
175
  decoded_data = data
178
176
 
@@ -40,7 +40,6 @@ class LibComponent:
40
40
  contained in the library.
41
41
  """
42
42
 
43
- self._BoundingBoxes = []
44
43
  self._graphic_layers = {}
45
44
 
46
45
  logger.debug(f"Reading Component '{self.Name}' from '{self.LibFile.FileName}'.")
@@ -83,17 +82,7 @@ class LibComponent:
83
82
 
84
83
  :param bool optional draw_designator: Draw designator elements
85
84
 
86
- :raises ImportError: If 'svgwrite' module is not installed.
87
- :raises ValueError: If 'graphic' is not the right instance.
88
- """
89
-
90
- try:
91
- import svgwrite
92
- except ImportError:
93
- logger.error("The 'svgwrite' module is not installed. Install it using 'pip install svgwrite'.")
94
-
95
- if not isinstance(graphic, svgwrite.Drawing):
96
- logger.error("The provided 'dwg' object is not an instance of 'svgwrite.Drawing'.")
85
+ """
97
86
 
98
87
  supressed_elements = []
99
88
  if not draw_designator: supressed_elements.append("SchDesignator")
@@ -102,6 +91,14 @@ class LibComponent:
102
91
  validObj = []
103
92
  for obj in self.Records:
104
93
  if hasattr(obj, 'draw_svg') and callable(getattr(obj, 'draw_svg')):
94
+
95
+ # The PCB .Designator string is a placeholder that Altium only resolves
96
+ # once the part is placed on a board; treat it like SchDesignator.
97
+ pcb_designator = type(obj).__name__ == "PcbString" and \
98
+ str(getattr(obj, "text", "")).strip().lower() == ".designator"
99
+ if pcb_designator and not draw_designator:
100
+ continue
101
+
105
102
  if obj.is_drawable and not any(x in type(obj).__name__ for x in supressed_elements):
106
103
  validObj.append(obj)
107
104
  else:
@@ -165,9 +162,7 @@ class LibComponent:
165
162
  for element in elements:
166
163
  bbox = element.get_bounding_box()
167
164
  if bbox is None:
168
- continue;
169
-
170
- self._BoundingBoxes.append(bbox)
165
+ continue
171
166
 
172
167
  point1 = bbox[0]
173
168
  point2 = bbox[1]
@@ -81,7 +81,9 @@ class PcbLibFootprint(LibComponent):
81
81
  self.Records.append( PcbComponentBody(self, olestream) )
82
82
 
83
83
  else:
84
+ # record length is unknown, so the rest of the stream can't be parsed
84
85
  logger.warning(f"Found unsupported RecordID={RecordID} in '{self.Name}'.")
86
+ break
85
87
 
86
88
  except Exception as e:
87
89
  logger.error(f"Failed to read data of '{self.Name}'. Exception: {e}")
@@ -2,6 +2,7 @@ from pyaltiumlib.pcblib.records.base import GenericPCBRecord
2
2
  from pyaltiumlib.datatypes import BinaryReader, Coordinate, CoordinatePoint
3
3
 
4
4
  from typing import Tuple
5
+ import math
5
6
 
6
7
  # Configure logging
7
8
  import logging
@@ -46,7 +47,6 @@ class PcbArc(GenericPCBRecord):
46
47
  # Drawing related
47
48
  # =============================================================================
48
49
 
49
-
50
50
  def get_bounding_box(self) -> Tuple[CoordinatePoint, CoordinatePoint]:
51
51
  """
52
52
  Generates and returns a bounding box for this record
@@ -54,17 +54,41 @@ class PcbArc(GenericPCBRecord):
54
54
  :return: List with two coordinate entries
55
55
  :rtype: tuple with :ref:`DataTypeCoordinatePoint`
56
56
  """
57
- start_x = self.location.x - self.radius
58
- start_y = self.location.y - self.radius
59
- end_x = self.location.x + self.radius
60
- end_y = self.location.y + self.radius
61
-
62
- min_x = min(self.location.x, start_x, end_x)
63
- max_x = max(self.location.x, start_x, end_x)
64
- min_y = min(self.location.y, start_y, end_y)
65
- max_y = max(self.location.y, start_y, end_y)
66
-
67
- return [CoordinatePoint(min_x, min_y), CoordinatePoint(max_x, max_y)]
57
+
58
+ def get_point(angle):
59
+ angle = math.radians(angle)
60
+
61
+ return CoordinatePoint(
62
+ self.location.x + self.radius * math.cos(angle),
63
+ self.location.y - self.radius * math.sin(angle)
64
+ )
65
+
66
+ start = self.angle_start % 360
67
+ end = self.angle_end % 360
68
+
69
+ points = [ get_point(start), get_point(end) ]
70
+
71
+ # Check whether an angle lies on the arc.
72
+ # The SVG implementation sweeps from start to end
73
+ # in increasing angle direction.
74
+ def angle_is_on_arc(angle):
75
+ if start <= end:
76
+ return start <= angle <= end
77
+ else:
78
+ # Arc crosses 0°
79
+ return angle >= start or angle <= end
80
+
81
+ # The extrema of a circle can only occur at these angles.
82
+ for angle in (0, 90, 180, 270):
83
+ if angle_is_on_arc(angle):
84
+ points.append(get_point(angle))
85
+
86
+ min_x = min(point.x for point in points)
87
+ max_x = max(point.x for point in points)
88
+ min_y = min(point.y for point in points)
89
+ max_y = max(point.y for point in points)
90
+
91
+ return [CoordinatePoint(min_x, min_y), CoordinatePoint(max_x, max_y)]
68
92
 
69
93
  def draw_svg(self, dwg, offset, zoom) -> None:
70
94
  """
@@ -19,7 +19,6 @@ class PcbComponentBody(GenericPCBRecord):
19
19
  super().__init__(parent)
20
20
 
21
21
  block = BinaryReader.from_stream( stream )
22
- BinaryReader.from_stream( stream ) # trailing block; advance stream past it
23
22
 
24
23
  if block.has_content():
25
24
  # No standard binary common header — layer is encoded as V7_LAYER=MECHANICAL{N}
@@ -136,8 +136,9 @@ class PcbPad(GenericPCBRecord):
136
136
  size_x = max(float(abs(self.size_top.x)), float(abs(self.size_middle.x)), float(abs(self.size_bottom.x)))
137
137
  size_y = max(float(abs(self.size_top.y)), float(abs(self.size_middle.y)), float(abs(self.size_bottom.y)))
138
138
 
139
- size_x = size_x + self.expansion_solder_mask if self.expansion_manual_solder_mask == 2 else size_x + 8
140
- size_y = size_y + self.expansion_solder_mask if self.expansion_manual_solder_mask == 2 else size_y + 8
139
+ # mask expansion is per side, so the outline grows by twice the value
140
+ size_x = size_x + self.expansion_solder_mask * 2 if self.expansion_manual_solder_mask == 2 else size_x + 8
141
+ size_y = size_y + self.expansion_solder_mask * 2 if self.expansion_manual_solder_mask == 2 else size_y + 8
141
142
 
142
143
  corners = [
143
144
  CoordinatePoint(self.location.x - size_x / 2, self.location.y - size_y / 2),
@@ -169,7 +170,7 @@ class PcbPad(GenericPCBRecord):
169
170
  # Masks
170
171
  # TODO: for other shapes, there seems to be something incorrect.... Sanity check for solder mask necessary?
171
172
  # TODO: What happens if expansion_manual_solder_mask is not 2 or 0?
172
- solder_mask = self.expansion_solder_mask if self.expansion_manual_solder_mask == 2 else Coordinate(8)
173
+ solder_mask = self.expansion_solder_mask * 2 if self.expansion_manual_solder_mask == 2 else Coordinate(8)
173
174
 
174
175
  # Draw Pads
175
176
  # TODO: For now only Bottom and/or Top are implemented
@@ -199,8 +200,17 @@ class PcbPad(GenericPCBRecord):
199
200
 
200
201
 
201
202
  center = (self.location.copy() * zoom) + offset
203
+ # Size the designator to fit inside the pad. The text is rotated with
204
+ # the pad, so its baseline runs along the pad x axis.
205
+ pad_size = self.size_bottom if self.layer == 32 else self.size_top
206
+ across = abs(float(pad_size.x)) * zoom
207
+ along = abs(float(pad_size.y)) * zoom
208
+ digits = max(len(self.designator), 1)
209
+ font_size = min(along * 0.8, across * 0.85 / (digits * 0.6))
210
+
202
211
  drawing_primitive = dwg.text(self.designator,
203
212
  insert = center.to_int_tuple(),
213
+ font_size = round(font_size, 1),
204
214
  fill = "white",
205
215
  dominant_baseline="central", text_anchor="middle",
206
216
  transform=f"rotate(-{self.rotation % 180} {center.x} {center.y})"
@@ -61,7 +61,7 @@ class PcbString(GenericPCBRecord):
61
61
 
62
62
  block.read_int32() # Unknown
63
63
 
64
- self.font_inverted_rect = block.read_byte()
64
+ self.font_inverted_rect = bool( block.read_int8() )
65
65
  self.font_inverted_rect_width = Coordinate.parse_bin(block.read(4))
66
66
  self.font_inverted_rect_height = Coordinate.parse_bin(block.read(4))
67
67
  self.font_inverted_rect_justification = PCBTextJustification( block.read_int8() )
@@ -72,11 +72,12 @@ class PcbVia(GenericPCBRecord):
72
72
  :rtype: tuple with :ref:`DataTypeCoordinatePoint`
73
73
  """
74
74
 
75
- size_x = self.diameter + self.expansion_solder_mask if self.expansion_manual_solder_mask == 2 else self.diameter + 8
76
- size_y = self.diameter + self.expansion_solder_mask if self.expansion_manual_solder_mask == 2 else self.diameter + 8
77
-
75
+ # mask expansion is per side, so the outline grows by twice the value
76
+ size_x = self.diameter + self.expansion_solder_mask * 2 if self.expansion_manual_solder_mask == 2 else self.diameter + 8
77
+ size_y = self.diameter + self.expansion_solder_mask * 2 if self.expansion_manual_solder_mask == 2 else self.diameter + 8
78
+
78
79
  return [ CoordinatePoint(self.location.x - size_x / 2, self.location.y - size_y / 2),
79
- CoordinatePoint(self.location.x - size_x / 2, self.location.y + size_y / 2) ]
80
+ CoordinatePoint(self.location.x + size_x / 2, self.location.y + size_y / 2) ]
80
81
 
81
82
 
82
83
  def draw_svg(self, dwg, offset, zoom) -> None:
@@ -1,11 +1,10 @@
1
- from pyaltiumlib.datatypes.coordinate import Coordinate, CoordinatePoint
2
- import math
1
+ from pyaltiumlib.svgrecord import SvgRecordMixin
3
2
 
4
3
  # Set up logging
5
4
  import logging
6
5
  logger = logging.getLogger(__name__)
7
6
 
8
- class GenericPCBRecord:
7
+ class GenericPCBRecord(SvgRecordMixin):
9
8
  """
10
9
  Base class for all PCB records in altium library.
11
10
  See also :ref:`PCBPrimitveHeader` for more details on PCB records.
@@ -78,45 +77,6 @@ class GenericPCBRecord:
78
77
  if 17 <= n <= 32:
79
78
  self.layer = 66 + n
80
79
 
81
- def get_svg_arc_path(self, center, radius_x, radius_y, angle_start, angle_end):
82
- """
83
- This function returns the svg path data for an arc.
84
-
85
- :param tuple center: The center coordinates of the arc
86
- :param int radius_x: The x-radius of the arc
87
- :param int radius_y: The y-radius of the arc
88
- :param float angle_start: The start angle of the arc
89
- :param float angle_end: The end angle of the arc.
90
-
91
- :return: corresponding svg path data for arc
92
- """
93
- def degrees_to_radians(degrees):
94
- return (degrees * math.pi / 180) % (2*math.pi)
95
-
96
- angle_start = degrees_to_radians(angle_start)
97
- angle_stop = degrees_to_radians(angle_end)
98
-
99
- if angle_start == angle_stop:
100
- angle_stop -= 0.001
101
-
102
- start_x = center[0] + radius_x * math.cos(-angle_start)
103
- start_y = center[1] + radius_y * math.sin(-angle_start)
104
- end_x = center[0] + radius_x * math.cos(-angle_stop)
105
- end_y = center[1] + radius_y * math.sin(-angle_stop)
106
-
107
- # Set large_arc_flag based on the angle difference
108
- large_arc_flag = 1 if (angle_stop - angle_start) % (2 * math.pi) > math.pi else 0
109
-
110
- # Set sweep_flag to 0 for counterclockwise
111
- sweep_flag = 0
112
-
113
- path_data = (
114
- f"M {start_x},{start_y} "
115
- f"A {radius_x},{radius_y} 0 {large_arc_flag},{sweep_flag} {end_x},{end_y}"
116
- )
117
- return path_data
118
-
119
-
120
80
  def get_svg_rounded_rect_path(self, start, size, layer_id, radius_percentage = 100):
121
81
  """
122
82
  This function returns the svg path data for a rounded rectangle.
@@ -163,44 +123,4 @@ class GenericPCBRecord:
163
123
  keepout_pattern.add(graphic.line(start=(0, 0), end=(size, size), stroke=layer.color.to_hex(), stroke_width=stroke))
164
124
  keepout_pattern.add(graphic.line(start=(0, size), end=(size, 0), stroke=layer.color.to_hex(), stroke_width=stroke))
165
125
 
166
- return "url(#keepout_pattern)"
167
-
168
- def draw_bounding_box(self, graphic, offset: CoordinatePoint, zoom: float) -> None:
169
- """
170
- This function is triggered when the :code:`draw_bbox` parameter is set in
171
- :py:mod:`pyaltiumlib.libcomponent.LibComponent.draw_svg`.
172
-
173
- Draws a bounding box using the values given by :code:`get_bounding_box`
174
- for each record
175
- """
176
- try:
177
- bbox = self.get_bounding_box()
178
- if bbox is None:
179
- logger.warning("No bounding box available for record")
180
- return
181
-
182
- start = (bbox[0] * zoom) + offset
183
- end = (bbox[1] * zoom) + offset
184
-
185
- lower_left_x = min(start.x, end.x)
186
- lower_left_y = min(start.y, end.y)
187
- insert = CoordinatePoint( Coordinate(lower_left_x), Coordinate(lower_left_y) )
188
-
189
- size = start - end
190
-
191
- # Validate dimensions
192
- if size.y == 0 or size.x == 0:
193
- logger.error(f"Invalid bounding box dimensions: {size}")
194
-
195
- # Add rectangle to SVG
196
- graphic.add(
197
- graphic.rect(
198
- insert=insert.to_int_tuple(),
199
- size=[abs(x) for x in size.to_int_tuple()],
200
- fill="none",
201
- stroke="black",
202
- stroke_width=1
203
- )
204
- )
205
- except Exception as e:
206
- logger.error(f"Failed to draw bounding box: {str(e)}")
126
+ return "url(#keepout_pattern)"
@@ -60,7 +60,7 @@ class SchLib(GenericLibFile):
60
60
  logger.warning(f"File '{self.FilePath}' can not be identified as schematic binary library!")
61
61
 
62
62
  # Extract Fonts (1....FontCount)
63
- self._FontCount = int( self._FileHeader.get("fontidcount"), 0)
63
+ self._FontCount = int( self._FileHeader.get("fontidcount", 0) )
64
64
  logger.debug(f"Start extracting {self._FontCount} fonts(s) from '{self.FileName}'.")
65
65
 
66
66
  for index in range(self._FontCount + 1):
@@ -81,7 +81,7 @@ class SchLib(GenericLibFile):
81
81
  def _ReadSchematicLibraryData(self):
82
82
 
83
83
  # Extract and Read Components (0....CompCount)
84
- self.ComponentCount = int( self._FileHeader.get("compcount"), 0)
84
+ self.ComponentCount = int( self._FileHeader.get("compcount", 0) )
85
85
  logger.info(f"Start extracting {self.ComponentCount} component(s) from '{self.FileName}'.")
86
86
 
87
87
  for index in range(self.ComponentCount):
@@ -0,0 +1,81 @@
1
+ from pyaltiumlib.datatypes import ParameterColor
2
+ from pyaltiumlib.datatypes.coordinate import Coordinate, CoordinatePoint
3
+ from pyaltiumlib.svgrecord import SvgRecordMixin
4
+
5
+ from typing import Dict, Any
6
+
7
+ # Configure logging
8
+ import logging
9
+ logger = logging.getLogger(__name__)
10
+
11
+ class GenericSchRecord(SvgRecordMixin):
12
+ """
13
+ Base class for all schematic records in altium library.
14
+ See also :ref:`SchRecord` and :ref:`SchCommonParameter` for more
15
+ details on schematic records.
16
+
17
+ :param Dict data: Dictionary containing raw record data
18
+ :param class parent: Parent symbol object
19
+ """
20
+
21
+ def __init__(self, data: Dict[str, Any], parent: [Any] = None):
22
+ self.Symbol = parent
23
+ self.rawdata = data
24
+ self.is_drawable = False
25
+
26
+ # Parse record metadata
27
+ self.record = int(self.rawdata.get('record', 0))
28
+ self.is_not_accessible = self.rawdata.get_bool('isnotaccessible', False)
29
+ self.graphically_locked = self.rawdata.get_bool('graphicallylocked', False)
30
+
31
+ # Parse ownership information
32
+ self.owner_index = int(self.rawdata.get('ownerindex', 0))
33
+ self.owner_part_id = self.rawdata.get('ownerpartid', '0') == '1'
34
+ self.owner_part_display_mode = int(self.rawdata.get('ownerpartdisplaymode', 0))
35
+ self.unique_id = self.rawdata.get('uniqueid', '')
36
+
37
+ # Parse location and colors
38
+ self.location = CoordinatePoint(
39
+ Coordinate.parse_dpx("location.x", self.rawdata),
40
+ Coordinate.parse_dpx("location.y", self.rawdata, scale=-1.0)
41
+ )
42
+ self.color = ParameterColor(self.rawdata.get('color', 0))
43
+ self.areacolor = ParameterColor(self.rawdata.get('areacolor', 0))
44
+
45
+ # Default spacing values
46
+ self.spacing_label_name = 4.0
47
+ self.spacing_label_designator = 1.0
48
+
49
+ def __repr__(self) -> str:
50
+ """
51
+ :return: A string representation of the record object
52
+ :rtype: str
53
+ """
54
+ return f"{self.__class__.__name__}"
55
+
56
+ def get_svg_stroke_dasharray(self) -> str:
57
+ """
58
+ This function returns the svg attribute :code:`stroke-dasharray` for the given
59
+ linestyle.
60
+
61
+ For more information on how `stroke-dasharray` works, visit the
62
+ `MDN Web Docs for stroke-dasharray <https://developer.mozilla.org/de/docs/Web/SVG/Attribute/stroke-dasharray>`_.
63
+
64
+ :return: corresponding svg attribute :code:`stroke-dasharray`
65
+ :rtype: str
66
+ """
67
+ if not hasattr(self, 'linestyle') and not hasattr(self, 'linestyle_ext'):
68
+ logger.error("Object must have either 'linestyle' or 'linestyle_ext' attribute")
69
+
70
+ # Determine line style
71
+ style_value = getattr(self, 'linestyle', getattr(self, 'linestyle_ext')).to_int()
72
+
73
+ if style_value == 1: # Dotted
74
+ return "4,10"
75
+ elif style_value == 2: # Dashed
76
+ return "1,10"
77
+ elif style_value == 3: # Dash-dotted
78
+ return "1,10,4,10"
79
+ else: # Solid
80
+ return "none"
81
+
@@ -0,0 +1,90 @@
1
+ from pyaltiumlib.datatypes.coordinate import Coordinate, CoordinatePoint
2
+ import math
3
+
4
+ # Set up logging
5
+ import logging
6
+ logger = logging.getLogger(__name__)
7
+
8
+ class SvgRecordMixin:
9
+ """
10
+ SVG drawing helpers shared by schematic and PCB records.
11
+ """
12
+
13
+ def get_svg_arc_path(self, center, radius_x, radius_y, angle_start, angle_end) -> str:
14
+ """
15
+ This function returns the svg path data for an arc.
16
+
17
+ :param tuple center: The center coordinates of the arc
18
+ :param int radius_x: The x-radius of the arc
19
+ :param int radius_y: The y-radius of the arc
20
+ :param float angle_start: The start angle of the arc
21
+ :param float angle_end: The end angle of the arc.
22
+
23
+ :return: corresponding svg path data for arc
24
+ :rtype: str
25
+ """
26
+ def degrees_to_radians(degrees):
27
+ return (degrees * math.pi / 180) % (2*math.pi)
28
+
29
+ angle_start = degrees_to_radians(angle_start)
30
+ angle_stop = degrees_to_radians(angle_end)
31
+
32
+ if angle_start == angle_stop:
33
+ angle_stop -= 0.001
34
+
35
+ start_x = center[0] + radius_x * math.cos(-angle_start)
36
+ start_y = center[1] + radius_y * math.sin(-angle_start)
37
+ end_x = center[0] + radius_x * math.cos(-angle_stop)
38
+ end_y = center[1] + radius_y * math.sin(-angle_stop)
39
+
40
+ # Set large_arc_flag based on the angle difference
41
+ large_arc_flag = 1 if (angle_stop - angle_start) % (2 * math.pi) > math.pi else 0
42
+
43
+ # Set sweep_flag to 0 for counterclockwise
44
+ sweep_flag = 0
45
+
46
+ path_data = (
47
+ f"M {start_x},{start_y} "
48
+ f"A {radius_x},{radius_y} 0 {large_arc_flag},{sweep_flag} {end_x},{end_y}"
49
+ )
50
+ return path_data
51
+
52
+ def draw_bounding_box(self, graphic, offset: CoordinatePoint, zoom: float) -> None:
53
+ """
54
+ This function is triggered when the :code:`draw_bbox` parameter is set in
55
+ :py:mod:`pyaltiumlib.libcomponent.LibComponent.draw_svg`.
56
+
57
+ Draws a bounding box using the values given by :code:`get_bounding_box`
58
+ for each record
59
+ """
60
+ try:
61
+ bbox = self.get_bounding_box()
62
+ if bbox is None:
63
+ logger.warning("No bounding box available for record")
64
+ return
65
+
66
+ start = (bbox[0] * zoom) + offset
67
+ end = (bbox[1] * zoom) + offset
68
+
69
+ lower_left_x = min(start.x, end.x)
70
+ lower_left_y = min(start.y, end.y)
71
+ insert = CoordinatePoint( Coordinate(lower_left_x), Coordinate(lower_left_y) )
72
+
73
+ size = start - end
74
+
75
+ # zero width/height is normal for straight lines
76
+ if size.y == 0 or size.x == 0:
77
+ logger.debug(f"Flat bounding box: {size}")
78
+
79
+ # Add rectangle to SVG
80
+ graphic.add(
81
+ graphic.rect(
82
+ insert=insert.to_int_tuple(),
83
+ size=[abs(x) for x in size.to_int_tuple()],
84
+ fill="none",
85
+ stroke="black",
86
+ stroke_width=1
87
+ )
88
+ )
89
+ except Exception as e:
90
+ logger.error(f"Failed to draw bounding box: {str(e)}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyaltiumlib
3
- Version: 0.7
3
+ Version: 0.7.2
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
@@ -4,6 +4,7 @@ setup.py
4
4
  src/pyaltiumlib/__init__.py
5
5
  src/pyaltiumlib/base.py
6
6
  src/pyaltiumlib/libcomponent.py
7
+ src/pyaltiumlib/svgrecord.py
7
8
  src/pyaltiumlib.egg-info/PKG-INFO
8
9
  src/pyaltiumlib.egg-info/SOURCES.txt
9
10
  src/pyaltiumlib.egg-info/dependency_links.txt
@@ -1,160 +0,0 @@
1
- from pyaltiumlib.datatypes import ParameterColor
2
- from pyaltiumlib.datatypes.coordinate import Coordinate, CoordinatePoint
3
-
4
- from typing import Dict, Any
5
- import math
6
-
7
- # Configure logging
8
- import logging
9
- logger = logging.getLogger(__name__)
10
-
11
- class GenericSchRecord:
12
- """
13
- Base class for all schematic records in altium library.
14
- See also :ref:`SchRecord` and :ref:`SchCommonParameter` for more
15
- details on schematic records.
16
-
17
- :param Dict data: Dictionary containing raw record data
18
- :param class parent: Parent symbol object
19
- """
20
-
21
- def __init__(self, data: Dict[str, Any], parent: [Any] = None):
22
- self.Symbol = parent
23
- self.rawdata = data
24
- self.is_drawable = False
25
-
26
- # Parse record metadata
27
- self.record = int(self.rawdata.get('record', 0))
28
- self.is_not_accessible = self.rawdata.get_bool('isnotaccessible', False)
29
- self.graphically_locked = self.rawdata.get_bool('graphicallylocked', False)
30
-
31
- # Parse ownership information
32
- self.owner_index = int(self.rawdata.get('ownerindex', 0))
33
- self.owner_part_id = self.rawdata.get('ownerpartid', '0') == '1'
34
- self.owner_part_display_mode = int(self.rawdata.get('ownerpartdisplaymode', 0))
35
- self.unique_id = self.rawdata.get('uniqueid', '')
36
-
37
- # Parse location and colors
38
- self.location = CoordinatePoint(
39
- Coordinate.parse_dpx("location.x", self.rawdata),
40
- Coordinate.parse_dpx("location.y", self.rawdata, scale=-1.0)
41
- )
42
- self.color = ParameterColor(self.rawdata.get('color', 0))
43
- self.areacolor = ParameterColor(self.rawdata.get('areacolor', 0))
44
-
45
- # Default spacing values
46
- self.spacing_label_name = 4.0
47
- self.spacing_label_designator = 1.0
48
-
49
- def __repr__(self) -> str:
50
- """
51
- :return: A string representation of the record object
52
- :rtype: str
53
- """
54
- return f"{self.__class__.__name__}"
55
-
56
- def get_svg_stroke_dasharray(self) -> str:
57
- """
58
- This function returns the svg attribute :code:`stroke-dasharray` for the given
59
- linestyle.
60
-
61
- For more information on how `stroke-dasharray` works, visit the
62
- `MDN Web Docs for stroke-dasharray <https://developer.mozilla.org/de/docs/Web/SVG/Attribute/stroke-dasharray>`_.
63
-
64
- :return: corresponding svg attribute :code:`stroke-dasharray`
65
- :rtype: str
66
- """
67
- if not hasattr(self, 'linestyle') and not hasattr(self, 'linestyle_ext'):
68
- logger.error("Object must have either 'linestyle' or 'linestyle_ext' attribute")
69
-
70
- # Determine line style
71
- style_value = getattr(self, 'linestyle', getattr(self, 'linestyle_ext')).to_int()
72
-
73
- if style_value == 1: # Dotted
74
- return "4,10"
75
- elif style_value == 2: # Dashed
76
- return "1,10"
77
- elif style_value == 3: # Dash-dotted
78
- return "1,10,4,10"
79
- else: # Solid
80
- return "none"
81
-
82
- def get_svg_arc_path(self, center, radius_x, radius_y, angle_start, angle_end) -> str:
83
- """
84
- This function returns the svg path data for an arc.
85
-
86
- :param tuple center: The center coordinates of the arc
87
- :param int radius_x: The x-radius of the arc
88
- :param int radius_y: The y-radius of the arc
89
- :param float angle_start: The start angle of the arc
90
- :param float angle_end: The end angle of the arc.
91
-
92
- :return: corresponding svg path data for arc
93
- :rtype: str
94
- """
95
- def degrees_to_radians(degrees):
96
- return (degrees * math.pi / 180) % (2*math.pi)
97
-
98
- angle_start = degrees_to_radians(angle_start)
99
- angle_stop = degrees_to_radians(angle_end)
100
-
101
- if angle_start == angle_stop:
102
- angle_stop -= 0.001
103
-
104
- start_x = center[0] + radius_x * math.cos(-angle_start)
105
- start_y = center[1] + radius_y * math.sin(-angle_start)
106
- end_x = center[0] + radius_x * math.cos(-angle_stop)
107
- end_y = center[1] + radius_y * math.sin(-angle_stop)
108
-
109
- # Set large_arc_flag based on the angle difference
110
- large_arc_flag = 1 if (angle_stop - angle_start) % (2 * math.pi) > math.pi else 0
111
-
112
- # Set sweep_flag to 0 for counterclockwise
113
- sweep_flag = 0
114
-
115
- path_data = (
116
- f"M {start_x},{start_y} "
117
- f"A {radius_x},{radius_y} 0 {large_arc_flag},{sweep_flag} {end_x},{end_y}"
118
- )
119
- return path_data
120
-
121
- def draw_bounding_box(self, graphic, offset: CoordinatePoint, zoom: float) -> None:
122
- """
123
- This function is triggered when the :code:`draw_bbox` parameter is set in
124
- :py:mod:`pyaltiumlib.libcomponent.LibComponent.draw_svg`.
125
-
126
- Draws a bounding box using the values given by :code:`get_bounding_box`
127
- for each record
128
- """
129
- try:
130
- bbox = self.get_bounding_box()
131
- if bbox is None:
132
- logger.warning("No bounding box available for record")
133
- return
134
-
135
- start = (bbox[0] * zoom) + offset
136
- end = (bbox[1] * zoom) + offset
137
-
138
- lower_left_x = min(start.x, end.x)
139
- lower_left_y = min(start.x, end.y)
140
- insert = CoordinatePoint( Coordinate(lower_left_x), Coordinate(lower_left_y) )
141
-
142
- size = start - end
143
-
144
- # Validate dimensions
145
- if size.y == 0 or size.x == 0:
146
- logger.error(f"Invalid bounding box dimensions: {size}")
147
-
148
- # Add rectangle to SVG
149
- graphic.add(
150
- graphic.rect(
151
- insert=insert.to_int_tuple(),
152
- size=[abs(x) for x in size.to_int_tuple()],
153
- fill="none",
154
- stroke="black",
155
- stroke_width=1
156
- )
157
- )
158
- except Exception as e:
159
- logger.error(f"Failed to draw bounding box: {str(e)}")
160
-
File without changes
File without changes
File without changes
File without changes