svg-ultralight 0.39.1__py3-none-any.whl → 0.40.0__py3-none-any.whl

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.

Potentially problematic release.


This version of svg-ultralight might be problematic. Click here for more details.

@@ -14,6 +14,11 @@ from svg_ultralight.bounding_boxes.bound_helpers import (
14
14
  pad_bbox,
15
15
  parse_bound_element,
16
16
  )
17
+ from svg_ultralight.bounding_boxes.padded_text_initializers import (
18
+ pad_text,
19
+ pad_text_ft,
20
+ pad_text_mix,
21
+ )
17
22
  from svg_ultralight.bounding_boxes.supports_bounds import SupportsBounds
18
23
  from svg_ultralight.bounding_boxes.type_bound_collection import BoundCollection
19
24
  from svg_ultralight.bounding_boxes.type_bound_element import BoundElement
@@ -39,7 +44,6 @@ from svg_ultralight.query import (
39
44
  clear_svg_ultralight_cache,
40
45
  get_bounding_box,
41
46
  get_bounding_boxes,
42
- pad_text,
43
47
  )
44
48
  from svg_ultralight.root_elements import new_svg_root_around_bounds
45
49
  from svg_ultralight.string_conversion import (
@@ -87,6 +91,8 @@ __all__ = [
87
91
  "new_svg_root_around_bounds",
88
92
  "pad_bbox",
89
93
  "pad_text",
94
+ "pad_text_ft",
95
+ "pad_text_mix",
90
96
  "parse_bound_element",
91
97
  "transform_element",
92
98
  "update_element",
svg_ultralight/animate.py CHANGED
@@ -16,13 +16,13 @@ except ModuleNotFoundError as exc:
16
16
  from typing import TYPE_CHECKING
17
17
 
18
18
  if TYPE_CHECKING:
19
+ import os
19
20
  from collections.abc import Iterable
20
- from pathlib import Path
21
21
 
22
22
 
23
23
  def write_gif(
24
- gif: str | Path,
25
- pngs: Iterable[str] | Iterable[Path] | Iterable[str | Path],
24
+ gif: str | os.PathLike[str],
25
+ pngs: Iterable[str] | Iterable[os.PathLike[str]] | Iterable[str | os.PathLike[str]],
26
26
  duration: float = 100,
27
27
  loop: int = 0,
28
28
  ) -> None:
@@ -0,0 +1,186 @@
1
+ """Functions that create PaddedText instances.
2
+
3
+ Three variants:
4
+
5
+ - `pad_text`: uses Inkscape to measure text bounds
6
+
7
+ - `pad_text_ft`: uses fontTools to measure text bounds (faster, and you get line_gap)
8
+
9
+ - `pad_text_mix`: uses Inkscape and fontTools to give true ascent, descent, and
10
+ line_gap while correcting some of the layout differences between fontTools and
11
+ Inkscape.
12
+
13
+ :author: Shay Hill
14
+ :created: 2025-06-09
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from copy import deepcopy
20
+ from pathlib import Path
21
+ from typing import TYPE_CHECKING
22
+
23
+ from svg_ultralight.bounding_boxes.type_padded_text import PaddedText
24
+ from svg_ultralight.constructors import new_element, update_element
25
+ from svg_ultralight.font_tools.font_info import (
26
+ get_padded_text_info,
27
+ get_svg_font_attributes,
28
+ )
29
+ from svg_ultralight.font_tools.globs import DEFAULT_FONT_SIZE
30
+ from svg_ultralight.query import get_bounding_boxes
31
+ from svg_ultralight.string_conversion import (
32
+ encode_to_css_class_name,
33
+ format_attr_dict,
34
+ format_number,
35
+ )
36
+
37
+ if TYPE_CHECKING:
38
+ import os
39
+
40
+ from lxml.etree import (
41
+ _Element as EtreeElement, # pyright: ignore[reportPrivateUsage]
42
+ )
43
+
44
+ DEFAULT_Y_BOUNDS_REFERENCE = "{[|gjpqyf"
45
+
46
+
47
+ def pad_text(
48
+ inkscape: str | os.PathLike[str],
49
+ text_elem: EtreeElement,
50
+ y_bounds_reference: str | None = None,
51
+ *,
52
+ font: str | os.PathLike[str] | None = None,
53
+ ) -> PaddedText:
54
+ r"""Create a PaddedText instance from a text element.
55
+
56
+ :param inkscape: path to an inkscape executable on your local file system
57
+ IMPORTANT: path cannot end with ``.exe``.
58
+ Use something like ``"C:\\Program Files\\Inkscape\\inkscape"``
59
+ :param text_elem: an etree element with a text tag
60
+ :param y_bounds_reference: an optional string to use to determine the ascent and
61
+ capline of the font. The default is a good choice, which approaches or even
62
+ meets the ascent of descent of most fonts without using utf-8 characters. You
63
+ might want to use a letter like "M" or even "x" if you are using an all-caps
64
+ string and want to center between the capline and baseline or if you'd like
65
+ to center between the baseline and x-line.
66
+ :param font: optionally add a path to a font file to use for the text element.
67
+ This is going to conflict with any font-family, font-style, or other
68
+ font-related attributes *except* font-size. You likely want to use
69
+ `font_tools.new_padded_text` if you're going to pass a font path, but you can
70
+ use it here to compare results between `pad_text` and `new_padded_text`.
71
+ :return: a PaddedText instance
72
+ """
73
+ if y_bounds_reference is None:
74
+ y_bounds_reference = DEFAULT_Y_BOUNDS_REFERENCE
75
+ if font is not None:
76
+ _ = update_element(text_elem, **get_svg_font_attributes(font))
77
+ if "font-size" not in text_elem.attrib:
78
+ text_elem.attrib["font-size"] = format_number(DEFAULT_FONT_SIZE)
79
+ rmargin_ref = deepcopy(text_elem)
80
+ capline_ref = deepcopy(text_elem)
81
+ _ = rmargin_ref.attrib.pop("id", None)
82
+ _ = capline_ref.attrib.pop("id", None)
83
+ rmargin_ref.attrib["text-anchor"] = "end"
84
+ capline_ref.text = y_bounds_reference
85
+
86
+ bboxes = get_bounding_boxes(inkscape, text_elem, rmargin_ref, capline_ref)
87
+ bbox, rmargin_bbox, capline_bbox = bboxes
88
+
89
+ tpad = bbox.y - capline_bbox.y
90
+ rpad = -rmargin_bbox.x2
91
+ bpad = capline_bbox.y2 - bbox.y2
92
+ lpad = bbox.x
93
+ return PaddedText(text_elem, bbox, tpad, rpad, bpad, lpad)
94
+
95
+
96
+ def pad_text_ft(
97
+ font: str | os.PathLike[str],
98
+ text: str,
99
+ font_size: float = DEFAULT_FONT_SIZE,
100
+ ascent: float | None = None,
101
+ descent: float | None = None,
102
+ *,
103
+ y_bounds_reference: str | None = None,
104
+ **attributes: str | float,
105
+ ) -> PaddedText:
106
+ """Create a new PaddedText instance using fontTools.
107
+
108
+ :param font: path to a font file.
109
+ :param text: the text of the text element.
110
+ :param font_size: the font size to use.
111
+ :param ascent: the ascent of the font. If not provided, it will be calculated
112
+ from the font file.
113
+ :param descent: the descent of the font. If not provided, it will be calculated
114
+ from the font file.
115
+ :param y_bounds_reference: optional character or string to use as a reference
116
+ for the ascent and descent. If provided, the ascent and descent will be the y
117
+ extents of the capline reference. This argument is provided to mimic the
118
+ behavior of the query module's `pad_text` function. `pad_text` does no
119
+ inspect font files and relies on Inkscape to measure reference characters.
120
+ :param attributes: additional attributes to set on the text element. There is a
121
+ chance these will cause the font element to exceed the BoundingBox of the
122
+ PaddedText instance.
123
+ :return: a PaddedText instance with a line_gap defined.
124
+ """
125
+ attributes_ = format_attr_dict(**attributes)
126
+ attributes_["font-size"] = attributes_.get("font-size", format_number(font_size))
127
+ attributes_["class"] = encode_to_css_class_name(Path(font).name)
128
+
129
+ elem = new_element("text", text=text, **attributes_)
130
+ info = get_padded_text_info(
131
+ font, text, font_size, ascent, descent, y_bounds_reference=y_bounds_reference
132
+ )
133
+ return PaddedText(elem, info.bbox, *info.padding, info.line_gap)
134
+
135
+
136
+ def pad_text_mix(
137
+ inkscape: str | os.PathLike[str],
138
+ font: str | os.PathLike[str],
139
+ text: str,
140
+ font_size: float = DEFAULT_FONT_SIZE,
141
+ ascent: float | None = None,
142
+ descent: float | None = None,
143
+ *,
144
+ y_bounds_reference: str | None = None,
145
+ **attributes: str | float,
146
+ ) -> PaddedText:
147
+ """Use Inkscape text bounds and fill missing with fontTools.
148
+
149
+ :param font: path to a font file.
150
+ :param text: the text of the text element.
151
+ :param font_size: the font size to use.
152
+ :param ascent: the ascent of the font. If not provided, it will be calculated
153
+ from the font file.
154
+ :param descent: the descent of the font. If not provided, it will be calculated
155
+ from the font file.
156
+ :param y_bounds_reference: optional character or string to use as a reference
157
+ for the ascent and descent. If provided, the ascent and descent will be the y
158
+ extents of the capline reference. This argument is provided to mimic the
159
+ behavior of the query module's `pad_text` function. `pad_text` does no
160
+ inspect font files and relies on Inkscape to measure reference characters.
161
+ :param attributes: additional attributes to set on the text element. There is a
162
+ chance these will cause the font element to exceed the BoundingBox of the
163
+ PaddedText instance.
164
+ :return: a PaddedText instance with a line_gap defined.
165
+ """
166
+ elem = new_element("text", text=text, **attributes)
167
+ padded_inkscape = pad_text(inkscape, elem, y_bounds_reference, font=font)
168
+ padded_fonttools = pad_text_ft(
169
+ font,
170
+ text,
171
+ font_size,
172
+ ascent,
173
+ descent,
174
+ y_bounds_reference=y_bounds_reference,
175
+ **attributes,
176
+ )
177
+ bbox = padded_inkscape.unpadded_bbox
178
+ rpad = padded_inkscape.rpad
179
+ lpad = padded_inkscape.lpad
180
+ if y_bounds_reference is None:
181
+ tpad = padded_fonttools.tpad
182
+ bpad = padded_fonttools.bpad
183
+ else:
184
+ tpad = padded_inkscape.tpad
185
+ bpad = padded_inkscape.bpad
186
+ return PaddedText(elem, bbox, tpad, rpad, bpad, lpad, padded_fonttools.line_gap)
@@ -41,6 +41,18 @@ class HasBoundingBox(SupportsBounds):
41
41
  y2 = y + self.bbox.base_height
42
42
  return (x, y), (x2, y), (x2, y2), (x, y2)
43
43
 
44
+ def values(self) -> tuple[float, float, float, float]:
45
+ """Get the values of the bounding box.
46
+
47
+ :return: x, y, width, height of the bounding box
48
+ """
49
+ return (
50
+ self.bbox.x,
51
+ self.bbox.y,
52
+ self.bbox.width,
53
+ self.bbox.height,
54
+ )
55
+
44
56
  def _get_transformed_corners(
45
57
  self,
46
58
  ) -> tuple[
@@ -66,6 +66,8 @@ from __future__ import annotations
66
66
 
67
67
  from typing import TYPE_CHECKING
68
68
 
69
+ from paragraphs import par
70
+
69
71
  from svg_ultralight.bounding_boxes.type_bound_element import BoundElement
70
72
  from svg_ultralight.bounding_boxes.type_bounding_box import BoundingBox
71
73
  from svg_ultralight.transformations import new_transformation_matrix, transform_element
@@ -77,6 +79,14 @@ if TYPE_CHECKING:
77
79
 
78
80
  _Matrix = tuple[float, float, float, float, float, float]
79
81
 
82
+ _no_line_gap_msg = par(
83
+ """No line_gap defined. Line gap is an inherent font attribute defined within a
84
+ font file. If this PaddedText instance was created with `pad_text` from reference
85
+ elements, a line_gap was not defined. Reading line_gap from the font file
86
+ requires creating a PaddedText instance with `pad_text_ft` or `pad_text_mixed`.
87
+ You can set an arbitrary line_gap after init with `instance.line_gap = value`."""
88
+ )
89
+
80
90
 
81
91
  class PaddedText(BoundElement):
82
92
  """A line of text with a bounding box and padding."""
@@ -89,6 +99,7 @@ class PaddedText(BoundElement):
89
99
  rpad: float,
90
100
  bpad: float,
91
101
  lpad: float,
102
+ line_gap: float | None = None,
92
103
  ) -> None:
93
104
  """Initialize a PaddedText instance.
94
105
 
@@ -105,6 +116,7 @@ class PaddedText(BoundElement):
105
116
  self.rpad = rpad
106
117
  self.base_bpad = bpad
107
118
  self.lpad = lpad
119
+ self._line_gap = line_gap
108
120
 
109
121
  @property
110
122
  def bbox(self) -> BoundingBox:
@@ -153,6 +165,32 @@ class PaddedText(BoundElement):
153
165
  self.unpadded_bbox.transform(tmat)
154
166
  _ = transform_element(self.elem, tmat)
155
167
 
168
+ @property
169
+ def line_gap(self) -> float:
170
+ """The line gap between this line of text and the next.
171
+
172
+ :return: The line gap between this line of text and the next.
173
+ """
174
+ if self._line_gap is None:
175
+ raise AttributeError(_no_line_gap_msg)
176
+ return self._line_gap
177
+
178
+ @line_gap.setter
179
+ def line_gap(self, value: float) -> None:
180
+ """Set the line gap between this line of text and the next.
181
+
182
+ :param value: The new line gap.
183
+ """
184
+ self._line_gap = value
185
+
186
+ @property
187
+ def leading(self) -> float:
188
+ """The leading of this line of text.
189
+
190
+ :return: The line gap plus the height of this line of text.
191
+ """
192
+ return self.height + self.line_gap
193
+
156
194
  @property
157
195
  def tpad(self) -> float:
158
196
  """The top padding of this line of text.
@@ -0,0 +1,5 @@
1
+ """Mark font_tools as a package.
2
+
3
+ :author: Shay Hill
4
+ :created: 2025-06-04
5
+ """
@@ -0,0 +1,284 @@
1
+ """Compare results between Inkscape and fontTools.
2
+
3
+ Function `check_font_tools_alignment` will let you know if it's relatively safe to
4
+ use `pad_text_mix` or `pad_text_ft`, which improve `pad_text` by assigning `line_gap`
5
+ values to the resulting PaddedText instance and by aligning with the actual descent
6
+ and ascent of a font instead of by attempting to infer these from a referenve string.
7
+
8
+ See Enum `FontBboxError` for the possible error codes and their meanings returned by
9
+ `check_font`.
10
+
11
+ You can use `draw_comparison` to debug or explore differences between fontTools and
12
+ Inkscape.
13
+
14
+ :author: Shay Hill
15
+ :created: 2025-06-08
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import enum
21
+ import itertools as it
22
+ import string
23
+ import sys
24
+ from pathlib import Path
25
+ from typing import TYPE_CHECKING
26
+
27
+ from svg_ultralight import new_bbox_rect, new_svg_root_around_bounds, pad_bbox
28
+ from svg_ultralight.bounding_boxes.padded_text_initializers import (
29
+ DEFAULT_Y_BOUNDS_REFERENCE,
30
+ pad_text,
31
+ pad_text_ft,
32
+ )
33
+ from svg_ultralight.constructors import new_element
34
+ from svg_ultralight.font_tools.font_css import add_svg_font_class
35
+ from svg_ultralight.font_tools.font_info import get_svg_font_attributes
36
+ from svg_ultralight.main import write_svg
37
+
38
+ if TYPE_CHECKING:
39
+ import os
40
+ from collections.abc import Iterator
41
+
42
+ from svg_ultralight.bounding_boxes.type_bounding_box import BoundingBox
43
+
44
+
45
+ class FontBboxError(enum.Enum):
46
+ """Classify the type of error between Inkscape and fontTools bounding boxes.
47
+
48
+ INIT: Use `pad_text`.
49
+
50
+ FontTools failed to run. This can happen with fonts that, inentionally or
51
+ not, do not have the required tables or character sets to build a bounding box
52
+ around the TEXT_TEXT. You can only use the `pad_text` PaddedText constructor.
53
+ This font may work with other or ascii-only text.
54
+
55
+ ELEM_Y: Use `pad_text` or `pad_text_mix` with cautions.
56
+
57
+ The y coordinate of the element bounding box is off by more than 1% of
58
+ the height. This error matters, because the y coordinates are used by
59
+ `pad_bbox_ft` and `pad_bbox_mix`. You can use either of these functions with a
60
+ y_bounds_reference element and accept some potential error in `line_gap` or
61
+ explicitly pass `ascent` and `descent` values to `pad_text_ft` or `pad_text_mix`.
62
+
63
+ SAFE_ELEM_X: Use `pad_text_mix`.
64
+
65
+ The y bounds are accurate, but the x coordinate of the element
66
+ bounding box is off by more than 1%. This is called "safe" because it is not used
67
+ by pad_bbox_mix, but you cannot use `pad_text_ft` without expecting BoundingBox
68
+ inaccuracies.
69
+
70
+ LINE_Y: Use `pad_text` or `pad_text_mix` with caution.
71
+
72
+ All of the above match, but the y coordinate of the line bounding box
73
+ (the padded bounding box) is off by more than 1% of the height. This error
74
+ matters as does ELEM_Y, but it does not exist for any font on my system. Fonts
75
+ without ELEM_Y errors should not have LINE_Y errors.
76
+
77
+ SAFE_LINE_X: Use `pad_text_mix`.
78
+
79
+ All of the above match, but the x coordinate of the line bounding
80
+ box (the padded bounding box) is off by more than 1%. This is safe or unsafe as
81
+ SAFE_ELEM_X, but also does not exist for any font on my system.
82
+
83
+ NO_ERROR: Use `pad_text_ft`.
84
+
85
+ No errors were found. The bounding boxes match within 1% of the height.
86
+ You can use `pad_text_ft` to get the same result as `pad_text` or `pad_text_mix`
87
+ without the delay caused by an Inkscape call.
88
+ """
89
+
90
+ INIT = enum.auto()
91
+ ELEM_Y = enum.auto()
92
+ SAFE_ELEM_X = enum.auto()
93
+ LINE_Y = enum.auto()
94
+ SAFE_LINE_X = enum.auto()
95
+ NO_ERROR = enum.auto()
96
+
97
+
98
+ # ===================================================================================
99
+ # Produce some commonly used Western UTF-8 characters for test text.
100
+ # ===================================================================================
101
+
102
+
103
+ def _get_western_utf8() -> str:
104
+ """Return a string of the commonly used Western UTF-8 character set."""
105
+ western = " ".join(
106
+ [
107
+ string.ascii_lowercase,
108
+ string.ascii_uppercase,
109
+ string.digits,
110
+ string.punctuation,
111
+ "áÁéÉíÍóÓúÚñÑäÄëËïÏöÖüÜçÇàÀèÈìÌòÒùÙâÂêÊîÎôÔûÛãÃõÕåÅæÆøØœŒßÿŸ",
112
+ ]
113
+ )
114
+ return western + " "
115
+
116
+
117
+ DEFAULT_TEST_TEXT = _get_western_utf8()
118
+
119
+
120
+ def _format_bbox_error(
121
+ bbox_a: BoundingBox, bbox_b: BoundingBox
122
+ ) -> tuple[int, int, int, int]:
123
+ """Return the difference between two bounding boxes as a percentage of height."""
124
+ width = bbox_a.width
125
+ height = bbox_a.height
126
+ diff = (
127
+ bbox_b.x - bbox_a.x,
128
+ bbox_b.y - bbox_a.y,
129
+ bbox_b.width - bbox_a.width,
130
+ bbox_b.height - bbox_a.height,
131
+ )
132
+ scaled_diff = (x / y for x, y in zip(diff, (height, height, width, height)))
133
+ dx, dy, dw, dh = (int(x * 100) for x in scaled_diff)
134
+ return dx, dy, dw, dh
135
+
136
+
137
+ def check_font_tools_alignment(
138
+ inkscape: str | os.PathLike[str],
139
+ font: str | os.PathLike[str],
140
+ text: str | None = None,
141
+ ) -> tuple[FontBboxError, tuple[int, int, int, int] | None]:
142
+ """Return an error code and the difference b/t Inkscape and fontTools bboxes.
143
+
144
+ :param inkscape: path to an Inkscape executable
145
+ :param font_path: path to the font file
146
+ :return: a tuple of the error code and the percentage difference between the
147
+ bounding boxes as a tuple of (dx, dy, dw, dh) or (error, None) if there was
148
+ an error initializing fontTools.
149
+ """
150
+ if text is None:
151
+ text = DEFAULT_TEST_TEXT
152
+ try:
153
+ svg_attribs = get_svg_font_attributes(font)
154
+ text_elem = new_element("text", **svg_attribs, text=text)
155
+ rslt_pt = pad_text(inkscape, text_elem)
156
+ rslt_ft = pad_text_ft(
157
+ font,
158
+ text,
159
+ y_bounds_reference=DEFAULT_Y_BOUNDS_REFERENCE,
160
+ )
161
+ except Exception:
162
+ return FontBboxError.INIT, None
163
+
164
+ error = _format_bbox_error(rslt_pt.unpadded_bbox, rslt_ft.unpadded_bbox)
165
+ if error[1] or error[3]:
166
+ return FontBboxError.ELEM_Y, error
167
+ if error[0] or error[2]:
168
+ return FontBboxError.SAFE_ELEM_X, error
169
+
170
+ error = _format_bbox_error(rslt_pt.bbox, rslt_ft.bbox)
171
+ if error[1] or error[3]:
172
+ return FontBboxError.LINE_Y, error
173
+ if error[0] or error[2]:
174
+ return FontBboxError.SAFE_LINE_X, error
175
+
176
+ return FontBboxError.NO_ERROR, None
177
+
178
+
179
+ def draw_comparison(
180
+ inkscape: str | os.PathLike[str],
181
+ output: str | os.PathLike[str],
182
+ font: str | os.PathLike[str],
183
+ text: str | None = None,
184
+ ) -> None:
185
+ """Draw a font in Inkscape and fontTools.
186
+
187
+ :param inkscape: path to an Inkscape executable
188
+ :param output: path to the output SVG file
189
+ :param font: path to the font file
190
+ :param text: the text to render. If None, the font name will be used.
191
+ :effect: Writes an SVG file to the output path.
192
+
193
+ Compare the rendering and bounding boxes of a font in Inkscape and fontTools. The
194
+ bounding boxes drawn will always be accurate, but some fonts will not render the
195
+ Inkscape version in a browser. Conversely, Inskcape will not render the fontTools
196
+ version in Inkscape, because Inkscape does not read locally linked fonts. It
197
+ usually works, and it a good place to start if you'd like to compare fontTools
198
+ and Inkscape results.
199
+ """
200
+ if text is None:
201
+ text = Path(font).stem
202
+ font_size = 12
203
+ font_attributes = get_svg_font_attributes(font)
204
+ text_elem = new_element("text", text=text, **font_attributes, font_size=font_size)
205
+ padded_pt = pad_text(inkscape, text_elem)
206
+ padded_ft = pad_text_ft(
207
+ font,
208
+ text,
209
+ font_size,
210
+ y_bounds_reference=DEFAULT_Y_BOUNDS_REFERENCE,
211
+ fill="none",
212
+ stroke="orange",
213
+ stroke_width=0.05,
214
+ )
215
+
216
+ root = new_svg_root_around_bounds(pad_bbox(padded_pt.bbox, 10))
217
+ _ = add_svg_font_class(root, font)
218
+ root.append(
219
+ new_bbox_rect(
220
+ padded_pt.unpadded_bbox, fill="none", stroke_width=0.07, stroke="red"
221
+ )
222
+ )
223
+ root.append(
224
+ new_bbox_rect(
225
+ padded_ft.unpadded_bbox, fill="none", stroke_width=0.05, stroke="blue"
226
+ )
227
+ )
228
+ root.append(padded_pt.elem)
229
+ root.append(padded_ft.elem)
230
+ _ = sys.stdout.write(f"{Path(font).stem} comparison drawn at {output}.\n")
231
+ _ = write_svg(Path(output), root)
232
+
233
+
234
+ def _iter_fonts(*fonts_dirs: Path) -> Iterator[Path]:
235
+ """Yield a path to each ttf and otf file in the given directories.
236
+
237
+ :param fonts_dir: directory to search for ttf and otf files, multiple ok
238
+ :yield: paths to ttf and otf files in the given directories
239
+
240
+ A helper function for _test_every_font_on_my_system.
241
+ """
242
+ if not fonts_dirs:
243
+ return
244
+ head, *tail = fonts_dirs
245
+ ttf_files = head.glob("*.[tt][tt][ff]")
246
+ otf_files = head.glob("*.[oO][tT][fF]")
247
+ yield from it.chain(ttf_files, otf_files)
248
+ yield from _iter_fonts(*tail)
249
+
250
+
251
+ def _test_every_font_on_my_system(
252
+ inkscape: str | os.PathLike[str],
253
+ font_dirs: list[Path],
254
+ text: str | None = None,
255
+ ) -> None:
256
+ """Test every font on my system."""
257
+ if not Path(inkscape).with_suffix(".exe").exists():
258
+ _ = sys.stdout.write(f"Inkscape not found at {inkscape}\n")
259
+ return
260
+ font_dirs = [x for x in font_dirs if x.exists()]
261
+ if not font_dirs:
262
+ _ = sys.stdout.write("No font directories found.\n")
263
+ return
264
+
265
+ counts = dict.fromkeys(FontBboxError, 0)
266
+ for font_path in _iter_fonts(*font_dirs):
267
+ error, diff = check_font_tools_alignment(inkscape, font_path, text)
268
+ counts[error] += 1
269
+ if error is not FontBboxError.NO_ERROR:
270
+ _ = sys.stdout.write(f"Error with {font_path.name}: {error.name} {diff}\n")
271
+ for k, v in counts.items():
272
+ _ = sys.stdout.write(f"{k.name}: {v}\n")
273
+
274
+
275
+ if __name__ == "__main__":
276
+ _INKSCAPE = Path(r"C:\Program Files\Inkscape\bin\inkscape")
277
+ _FONT_DIRS = [
278
+ Path(r"C:\Windows\Fonts"),
279
+ Path(r"C:\Users\shaya\AppData\Local\Microsoft\Windows\Fonts"),
280
+ ]
281
+ _test_every_font_on_my_system(_INKSCAPE, _FONT_DIRS)
282
+
283
+ font = Path(r"C:\Windows\Fonts\arial.ttf")
284
+ draw_comparison(_INKSCAPE, "temp.svg", font)
@@ -0,0 +1,82 @@
1
+ """Link local fonts as css in an svg file.
2
+
3
+ :author: Shay Hill
4
+ :created: 2025-06-04
5
+ """
6
+
7
+ # pyright: reportUnknownMemberType = false
8
+ # pyright: reportAttributeAccessIssue = false
9
+ # pyright: reportUnknownArgumentType = false
10
+ # pyright: reportUnknownVariableType = false
11
+ # pyright: reportUnknownParameterType = false
12
+ # pyright: reportMissingTypeStubs = false
13
+
14
+ from __future__ import annotations
15
+
16
+ from pathlib import Path
17
+ from typing import TYPE_CHECKING
18
+
19
+ import cssutils
20
+
21
+ from svg_ultralight.constructors import new_element
22
+ from svg_ultralight.string_conversion import encode_to_css_class_name
23
+
24
+ if TYPE_CHECKING:
25
+ import os
26
+
27
+ from lxml.etree import (
28
+ _Element as EtreeElement, # pyright: ignore[reportPrivateUsage]
29
+ )
30
+
31
+
32
+ def _get_class_names_from_stylesheet(
33
+ stylesheet: cssutils.css.CSSStyleSheet,
34
+ ) -> list[str]:
35
+ """Extract all class names from a given CSS stylesheet.
36
+
37
+ :param stylesheet: A cssutils.css.CSSStyleSheet object.
38
+ :return: A list of class names (without the leading dot).
39
+ """
40
+ class_names: list[str] = []
41
+ for rule in stylesheet.cssRules:
42
+ if rule.type == rule.STYLE_RULE:
43
+ selectors = (s.strip() for s in rule.selectorText.split(","))
44
+ class_names.extend(s[1:] for s in selectors if s.startswith("."))
45
+ return class_names
46
+
47
+
48
+ def add_svg_font_class(root: EtreeElement, font: str | os.PathLike[str]) -> str:
49
+ """Add a css class for the font to the root element.
50
+
51
+ :param root: The root element of the SVG document.
52
+ :param font: Path to the font file.
53
+ :return: The class name for the font, e.g., "bahnschrift_2e_ttf"
54
+ """
55
+ assert Path(font).exists()
56
+ family_name = encode_to_css_class_name(Path(font).stem)
57
+ class_name = encode_to_css_class_name(Path(font).name)
58
+ style = root.find("style")
59
+ if style is None:
60
+ style = new_element("style", type="text/css")
61
+ root.insert(0, style)
62
+ css = style.text or ""
63
+
64
+ stylesheet = cssutils.parseString(css)
65
+ existing_class_names = _get_class_names_from_stylesheet(stylesheet)
66
+ if class_name in existing_class_names:
67
+ return class_name
68
+
69
+ font_face_rule = cssutils.css.CSSFontFaceRule()
70
+ font_face_rule.style = cssutils.css.CSSStyleDeclaration()
71
+ font_face_rule.style["font-family"] = f'"{family_name}"'
72
+ font_face_rule.style["src"] = rf"url('{Path(font).as_posix()}')"
73
+ stylesheet.add(font_face_rule)
74
+
75
+ style_rule = cssutils.css.CSSStyleRule(selectorText=f".{class_name}")
76
+ style_rule.style = cssutils.css.CSSStyleDeclaration()
77
+ style_rule.style["font-family"] = f'"{family_name}"'
78
+ stylesheet.add(style_rule)
79
+
80
+ style.text = stylesheet.cssText.decode("utf-8")
81
+
82
+ return class_name