fontlab-python-pens 1.0.8__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.
fontlab_pens/stroke.py ADDED
@@ -0,0 +1,420 @@
1
+ # this_file: src/fontlab_pens/stroke.py
2
+ """Validated stroke descriptions and capability-gated writes to FontLab elements.
3
+
4
+ Variants follow Proteus percentages: proportion and contrast are rounded to two
5
+ percentage decimal places, so finer input precision is intentionally not retained.
6
+ Native imports are lazy. Plans stage all shapes before touching live layers;
7
+ a native commit failure can still leave partial geometry, as with FlPointPen.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from collections.abc import Iterable, Mapping
14
+ from dataclasses import dataclass, replace
15
+ from decimal import Decimal
16
+ from enum import IntEnum
17
+ from types import MappingProxyType
18
+ from typing import Any
19
+
20
+ from fontlab_pens._native import layer_of
21
+ from fontlab_pens.base import PenError
22
+ from fontlab_pens.fontlab import FlPointPen, draw_points
23
+ from fontlab_pens.recording import RecordingPointPen
24
+
25
+ __all__ = [
26
+ "Cap",
27
+ "CapType",
28
+ "Join",
29
+ "StrokePlan",
30
+ "StrokeStyle",
31
+ "UnsupportedStroke",
32
+ "apply_plan",
33
+ "apply_stroke",
34
+ "compatibility",
35
+ "expand_stroke",
36
+ ]
37
+
38
+ _ISSUE = "https://github.com/Fontlab/fl/issues/8626"
39
+
40
+
41
+ class CapType(IntEnum):
42
+ """FontGate cap kinds, using their native numeric values."""
43
+
44
+ BUTT = 0
45
+ SQUARE = 1
46
+ ROUND = 2
47
+ HORIZONTAL = 3
48
+ VERTICAL = 4
49
+ FIXED = 5
50
+
51
+
52
+ class Join(IntEnum):
53
+ """Proteus join kinds, independent of Qt's enum values."""
54
+
55
+ BEVEL = 0
56
+ ROUND = 1
57
+ MITER = 2
58
+
59
+
60
+ def _finite(value: Any, field: str) -> float:
61
+ try:
62
+ result = float(value)
63
+ except (TypeError, ValueError, OverflowError) as error:
64
+ raise ValueError(f"{field} must be a finite float") from error
65
+ if not math.isfinite(result):
66
+ raise ValueError(f"{field} must be a finite float")
67
+ return result
68
+
69
+
70
+ def _enum(value: Any, enum: type[IntEnum], field: str) -> IntEnum:
71
+ try:
72
+ return enum(value)
73
+ except (ValueError, TypeError) as error:
74
+ raise ValueError(f"{field} must be a valid {enum.__name__}") from error
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class Cap:
79
+ """One immutable cap, with offsets/shaping/curvature in fractional units."""
80
+
81
+ type: CapType = CapType.BUTT
82
+ offset: float = 0.0
83
+ shaping: float = 0.0
84
+ rotation: float = 0.0
85
+ curvature: float = 0.554
86
+
87
+ def __post_init__(self) -> None:
88
+ object.__setattr__(self, "type", _enum(self.type, CapType, "type"))
89
+ for name in ("offset", "shaping", "rotation", "curvature"):
90
+ object.__setattr__(self, name, _finite(getattr(self, name), name))
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class StrokeStyle:
95
+ """A stroke in design units, independent of installed native capabilities."""
96
+
97
+ thickness: float
98
+ proportion: float = 0.5
99
+ contrast: float = 1.0
100
+ rotation: float = 0.0
101
+ join: Join = Join.MITER
102
+ miter_limit: float = 3.0
103
+ remove_overlap: bool = False
104
+ cap0: Cap = Cap()
105
+ cap1: Cap = Cap()
106
+
107
+ def __post_init__(self) -> None:
108
+ for name in ("thickness", "proportion", "contrast", "rotation", "miter_limit"):
109
+ object.__setattr__(self, name, _finite(getattr(self, name), name))
110
+ if self.thickness < 0:
111
+ raise ValueError("thickness must be >= 0")
112
+ if not 0 <= self.proportion <= 1:
113
+ raise ValueError("proportion must be between 0 and 1 inclusive")
114
+ if self.contrast < 0:
115
+ raise ValueError("contrast must be >= 0")
116
+ if self.miter_limit <= 0:
117
+ raise ValueError("miter_limit must be > 0")
118
+ object.__setattr__(self, "join", _enum(self.join, Join, "join"))
119
+ if not isinstance(self.remove_overlap, bool):
120
+ raise ValueError("remove_overlap must be a bool") # noqa: TRY004 - validation contract
121
+ if not isinstance(self.cap0, Cap) or not isinstance(self.cap1, Cap):
122
+ raise ValueError("cap0 and cap1 must be Cap values") # noqa: TRY004 - validation contract
123
+
124
+ def to_variant(self) -> dict[str, Any]:
125
+ """Return Proteus keys with defaults omitted and percentages scaled."""
126
+ result = {}
127
+ for name, default in (("proportion", 50), ("contrast", 100)):
128
+ value = _finite(round(getattr(self, name) * 100, 2), name)
129
+ if value != default:
130
+ result[name] = value
131
+ for name, default in (("rotation", 0), ("thickness", 0), ("miter_limit", 3.0)):
132
+ if (value := getattr(self, name)) != default:
133
+ result[name] = value
134
+ if self.remove_overlap:
135
+ result["remove_overlap"] = True
136
+ if self.join != Join.MITER:
137
+ result["join"] = self.join.name.lower()
138
+ for index, cap in enumerate((self.cap0, self.cap1)):
139
+ if cap.type != CapType.BUTT:
140
+ result[f"cap{index}"] = cap.type.name.lower()
141
+ for name, default in (("offset", 0), ("shaping", 0), ("curvature", 0.554)):
142
+ if (value := getattr(cap, name)) != default:
143
+ result[f"cap_{name}{index}"] = _finite(
144
+ Decimal(str(value)) * 100, f"cap_{name}{index}"
145
+ )
146
+ if cap.rotation:
147
+ result[f"cap_rotation{index}"] = cap.rotation
148
+ return result
149
+
150
+ @classmethod
151
+ def from_variant(cls, d: Mapping[str, Any]) -> StrokeStyle:
152
+ """Read Proteus keys; thickness takes precedence over its width alias."""
153
+ if not isinstance(d, Mapping):
154
+ raise ValueError("stroke variant must be a mapping") # noqa: TRY004 - validation contract
155
+ values = dict(d)
156
+ width = values.pop("width", 0.0)
157
+ kwargs = {"thickness": values.pop("thickness", width)}
158
+ for name, default in (("proportion", 50), ("contrast", 100)):
159
+ kwargs[name] = float(Decimal(str(_finite(values.pop(name, default), name))) / 100)
160
+ for name, default in (("rotation", 0), ("miter_limit", 3), ("remove_overlap", False)):
161
+ kwargs[name] = values.pop(name, default)
162
+ kwargs["join"] = _variant_enum(values.pop("join", "miter"), Join, "join")
163
+ for index in range(2):
164
+ cap = {"type": _variant_enum(values.pop(f"cap{index}", "butt"), CapType, f"cap{index}")}
165
+ for name, default in (("offset", 0), ("shaping", 0), ("curvature", 55.4)):
166
+ key = f"cap_{name}{index}"
167
+ cap[name] = float(Decimal(str(_finite(values.pop(key, default), key))) / 100)
168
+ cap["rotation"] = values.pop(f"cap_rotation{index}", 0)
169
+ kwargs[f"cap{index}"] = Cap(**cap)
170
+ if values:
171
+ raise ValueError(f"Unknown stroke variant keys: {', '.join(map(str, values))}")
172
+ return cls(**kwargs)
173
+
174
+ def with_(self, **changes: Any) -> StrokeStyle:
175
+ """Return a validated copy with the requested fields replaced."""
176
+ return replace(self, **changes)
177
+
178
+
179
+ def _variant_enum(value: Any, enum: type[IntEnum], field: str) -> IntEnum:
180
+ names = {member.name.lower(): member for member in enum}
181
+ if not isinstance(value, str) or value not in names:
182
+ raise ValueError(f"{field} must be one of {', '.join(names)}")
183
+ return names[value]
184
+
185
+
186
+ class UnsupportedStroke(PenError):
187
+ """Requested fields need a native API that this FontLab host lacks."""
188
+
189
+ def __init__(self, fields: Iterable[str], issue: str = _ISSUE) -> None:
190
+ self.fields = tuple(fields)
191
+ self.issue = issue
192
+ super().__init__(f"Unsupported stroke fields: {', '.join(self.fields)}; see {issue}")
193
+
194
+
195
+ def _load_native() -> Any:
196
+ from PythonQt.QtCore import Qt
197
+ from PythonQt.QtGui import QPen
198
+
199
+ from fontlab_pens.fontlab import _load_native as load_geometry
200
+
201
+ native = load_geometry()
202
+ native.QPen = QPen
203
+ native.Qt = Qt
204
+ return native
205
+
206
+
207
+ _VARIANT_FIELD = {
208
+ **{f"cap{i}": f"cap{i}" for i in (0, 1)},
209
+ **{
210
+ f"cap_{n}{i}": f"cap{i}"
211
+ for n in ("offset", "shaping", "curvature", "rotation")
212
+ for i in (0, 1)
213
+ },
214
+ }
215
+
216
+
217
+ def _shape(shape: Any) -> None:
218
+ if type(shape).__name__ != "flShape":
219
+ raise TypeError(
220
+ f"Expected flShape element, got {type(shape).__name__}; pass layer.shapes[i]"
221
+ )
222
+
223
+
224
+ def apply_stroke(shape: Any, style: StrokeStyle, *, native: Any = None) -> None:
225
+ """Apply supported fields, refusing unsupported values before any shape write.
226
+
227
+ This writes no history and sends no notification: use it on detached elements,
228
+ or wrap a live element's edit in the layer's history step (as apply_plan does).
229
+
230
+ FontLab ignores ``setPen`` on varicolored shapes, so their QPen stays unchanged.
231
+ """
232
+ _shape(shape)
233
+ if not isinstance(style, StrokeStyle):
234
+ raise TypeError("style must be a StrokeStyle")
235
+ parameters = "penParameters" in dir(type(shape))
236
+ variant = style.to_variant()
237
+ if not parameters:
238
+ # Compare scaled variant keys, so values to_variant treats as default pass.
239
+ fields = tuple(
240
+ dict.fromkeys(
241
+ _VARIANT_FIELD.get(key, key)
242
+ for key in variant
243
+ if key not in ("thickness", "join", "miter_limit")
244
+ )
245
+ )
246
+ if fields:
247
+ raise UnsupportedStroke(fields)
248
+ else:
249
+ # The native setter starts from the shape's old QPen and overrides only the
250
+ # keys sent, so send every pen-derived field explicitly. The integer join is
251
+ # also safe on builds whose join_code inverts name comparison (fl#8630).
252
+ variant["thickness"] = style.thickness
253
+ variant["join"] = int(style.join)
254
+ variant["miter_limit"] = style.miter_limit
255
+ variant.setdefault("cap0", style.cap0.type.name.lower())
256
+ variant.setdefault("cap1", style.cap1.type.name.lower())
257
+ native = _load_native() if native is None else native
258
+ pen = native.QPen(shape.pen)
259
+ pen.setWidthF(style.thickness)
260
+ # A fresh flShape has Qt.NoPen; FontLab exports thickness 0 for it. Thickness 0
261
+ # means no stroke, not Qt's cosmetic one-pixel pen.
262
+ if style.thickness == 0:
263
+ pen.setStyle(native.Qt.NoPen)
264
+ elif pen.style() == native.Qt.NoPen:
265
+ pen.setStyle(native.Qt.SolidLine)
266
+ pen.setJoinStyle(
267
+ {
268
+ Join.MITER: native.Qt.MiterJoin,
269
+ Join.ROUND: native.Qt.RoundJoin,
270
+ Join.BEVEL: native.Qt.BevelJoin,
271
+ }[style.join]
272
+ )
273
+ pen.setMiterLimit(style.miter_limit)
274
+ # The native setter validates and may raise; run it before the QPen write so a
275
+ # refusal leaves the shape unchanged.
276
+ if parameters:
277
+ shape.penParameters = variant
278
+ shape.pen = pen
279
+
280
+
281
+ def expand_stroke(shape: Any) -> None:
282
+ """Expand an element only when the host exposes the native operation."""
283
+ _shape(shape)
284
+ if "expandStroke" not in dir(type(shape)):
285
+ raise UnsupportedStroke(("expand",))
286
+ if shape.expandStroke() is False:
287
+ raise PenError("FontLab could not expand the stroke (no pen or failed makeStroke)")
288
+
289
+
290
+ @dataclass(frozen=True)
291
+ class StrokePlan:
292
+ """An immutable, ordered mapping from layer names to validated styles."""
293
+
294
+ styles: Mapping[str, StrokeStyle]
295
+
296
+ def __post_init__(self) -> None:
297
+ if not isinstance(self.styles, Mapping) or not self.styles:
298
+ raise ValueError("styles must be a non-empty mapping")
299
+ for name, style in self.styles.items():
300
+ if not isinstance(name, str) or not name:
301
+ raise ValueError("master names must be non-empty strings")
302
+ if not isinstance(style, StrokeStyle):
303
+ raise ValueError("each master style must be a StrokeStyle") # noqa: TRY004 - validation contract
304
+ object.__setattr__(self, "styles", MappingProxyType(dict(self.styles)))
305
+
306
+
307
+ def _open_recording(layer: Any) -> tuple[RecordingPointPen, int]:
308
+ recording = RecordingPointPen()
309
+ draw_points(layer, recording)
310
+ result = RecordingPointPen()
311
+ contour = []
312
+ count = 0
313
+ for entry in recording.value:
314
+ op, _, _ = entry
315
+ if op == "beginPath":
316
+ contour = [entry]
317
+ elif op == "addPoint":
318
+ contour.append(entry)
319
+ elif op == "endPath" and len(contour) > 1:
320
+ if contour[1][1][1] == "move":
321
+ result.value.extend([*contour, entry])
322
+ count += 1
323
+ contour = []
324
+ return result, count
325
+
326
+
327
+ def apply_plan(
328
+ glyph: Any,
329
+ plan: StrokePlan,
330
+ *,
331
+ source: str,
332
+ notify: str | None = "Apply stroke plan",
333
+ native: Any = None,
334
+ expand: bool = False,
335
+ ) -> dict[str, int]:
336
+ """Copy source open contours into one stroked element per named target layer.
337
+
338
+ All resolution and detached preparation precede live writes. History is
339
+ initialized before committing, and one notification finalizes attempted
340
+ writes even on failure. Native commits are not atomic; do not blindly retry.
341
+ """
342
+ if type(glyph).__name__ != "flGlyph":
343
+ raise TypeError(f"Expected flGlyph, got {type(glyph).__name__}")
344
+ if not isinstance(plan, StrokePlan):
345
+ raise TypeError("plan must be a StrokePlan")
346
+ source_layer = layer_of(glyph, source)
347
+ layers = [layer_of(glyph, name) for name in plan.styles]
348
+ for layer in layers:
349
+ if layer.autoLayer:
350
+ raise PenError("Cannot write into an automatic flLayer")
351
+ if layer.glyph is None:
352
+ raise PenError("Target flLayer must be attached to an flGlyph")
353
+ recording, count = _open_recording(source_layer)
354
+ if not count:
355
+ raise ValueError(f"Source layer {source!r} has no open contours")
356
+ native = _load_native() if native is None else native
357
+ shapes = []
358
+ for style in plan.styles.values():
359
+ shape = native.flShape()
360
+ with FlPointPen(shape, native=native) as pen:
361
+ recording.replay(pen)
362
+ apply_stroke(shape, style, native=native)
363
+ if expand:
364
+ expand_stroke(shape)
365
+ shapes.append(shape)
366
+ items = [*layers, glyph]
367
+ if notify:
368
+ for item in items:
369
+ item.checkInitHistoryState(0)
370
+ try:
371
+ for layer, shape in zip(layers, shapes, strict=True):
372
+ layer.addShape(shape)
373
+ except BaseException as error:
374
+ if notify:
375
+ try:
376
+ native.flItems.notifyChangesApplied(notify, items)
377
+ except BaseException as notify_error:
378
+ raise error from notify_error
379
+ raise
380
+ if notify:
381
+ native.flItems.notifyChangesApplied(notify, items)
382
+ return dict.fromkeys(plan.styles, count)
383
+
384
+
385
+ def compatibility(layers_or_recordings: Iterable[Any]) -> list[str]:
386
+ """Compare contour point counts/types; positions, metadata and components are ignored.
387
+
388
+ Inputs may be flLayer/flShape objects, RecordingPointPen objects, or their
389
+ raw value iterables. This performs no native mutations or native imports.
390
+ """
391
+ signatures = []
392
+ for item in layers_or_recordings:
393
+ if type(item).__name__ in ("flLayer", "flShape"):
394
+ recording = RecordingPointPen()
395
+ draw_points(item, recording)
396
+ value = recording.value
397
+ elif isinstance(item, RecordingPointPen):
398
+ value = item.value
399
+ else:
400
+ value = item
401
+ contours = []
402
+ for op, args, kwargs in value:
403
+ if op == "beginPath":
404
+ contours.append([])
405
+ elif op == "addPoint":
406
+ contours[-1].append(args[1] if len(args) > 1 else kwargs.get("segmentType"))
407
+ signatures.append(contours)
408
+ messages = []
409
+ for index, contours in enumerate(signatures[1:], 1):
410
+ reference = signatures[0]
411
+ if len(contours) != len(reference):
412
+ messages.append(f"Recording {index}: contour count {len(contours)} != {len(reference)}")
413
+ for number, (actual, expected) in enumerate(zip(contours, reference), 1):
414
+ if len(actual) != len(expected):
415
+ messages.append(
416
+ f"Recording {index}, contour {number}: point count {len(actual)} != {len(expected)}"
417
+ )
418
+ elif actual != expected:
419
+ messages.append(f"Recording {index}, contour {number}: segment types differ")
420
+ return messages
@@ -0,0 +1,225 @@
1
+ # this_file: src/fontlab_pens/transform.py
2
+ # Derived from fontTools Lib/fontTools/misc/transform.py and
3
+ # Lib/fontTools/pens/transformPen.py (MIT, (c) Just van Rossum; see NOTICE)
4
+ """Immutable affine `Transform` and pens that transform coordinates.
5
+
6
+ `Transform` is a 6-field NamedTuple `(xx, xy, yx, yy, dx, dy)` like fontTools',
7
+ so it compares equal to plain 6-tuples and to fontTools `Transform` objects.
8
+ `DecomposedTransform` is not ported.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ from collections.abc import Iterable, Sequence
15
+ from typing import NamedTuple
16
+
17
+ from fontlab_pens.base import AbstractPen
18
+ from fontlab_pens.filter import FilterPen, FilterPointPen
19
+ from fontlab_pens.point import AbstractPointPen
20
+
21
+ __all__ = [
22
+ "Identity",
23
+ "Offset",
24
+ "Scale",
25
+ "Transform",
26
+ "TransformPen",
27
+ "TransformPointPen",
28
+ ]
29
+
30
+ Point = tuple[float, float]
31
+
32
+ _EPSILON = 1e-15
33
+ _ONE_EPSILON = 1 - _EPSILON
34
+ _MINUS_ONE_EPSILON = -1 + _EPSILON
35
+
36
+
37
+ def _normSinCos(v: float) -> float:
38
+ """Snap near-0/±1 sine and cosine values so right-angle rotations are exact."""
39
+ if abs(v) < _EPSILON:
40
+ v = 0
41
+ elif v > _ONE_EPSILON:
42
+ v = 1
43
+ elif v < _MINUS_ONE_EPSILON:
44
+ v = -1
45
+ return v
46
+
47
+
48
+ class Transform(NamedTuple):
49
+ """2x2 matrix plus offset; every operation returns a new instance."""
50
+
51
+ xx: float = 1
52
+ xy: float = 0
53
+ yx: float = 0
54
+ yy: float = 1
55
+ dx: float = 0
56
+ dy: float = 0
57
+
58
+ def transformPoint(self, p: Point) -> Point:
59
+ """Return `p` transformed."""
60
+ x, y = p
61
+ xx, xy, yx, yy, dx, dy = self
62
+ return (xx * x + yx * y + dx, xy * x + yy * y + dy)
63
+
64
+ def transformPoints(self, points: Iterable[Point]) -> list[Point]:
65
+ """Return a list of transformed points."""
66
+ xx, xy, yx, yy, dx, dy = self
67
+ return [(xx * x + yx * y + dx, xy * x + yy * y + dy) for x, y in points]
68
+
69
+ def transformVector(self, v: Point) -> Point:
70
+ """Transform an `(dx, dy)` vector, ignoring the offset."""
71
+ dx, dy = v
72
+ xx, xy, yx, yy = self[:4]
73
+ return (xx * dx + yx * dy, xy * dx + yy * dy)
74
+
75
+ def transformVectors(self, vectors: Iterable[Point]) -> list[Point]:
76
+ """Transform `(dx, dy)` vectors, ignoring the offset."""
77
+ xx, xy, yx, yy = self[:4]
78
+ return [(xx * dx + yx * dy, xy * dx + yy * dy) for dx, dy in vectors]
79
+
80
+ def translate(self, x: float = 0, y: float = 0) -> Transform:
81
+ """Return this transformation offset by `x, y`."""
82
+ return self.transform((1, 0, 0, 1, x, y))
83
+
84
+ def scale(self, x: float = 1, y: float | None = None) -> Transform:
85
+ """Return this transformation scaled by `x, y` (`y` defaults to `x`)."""
86
+ if y is None:
87
+ y = x
88
+ return self.transform((x, 0, 0, y, 0, 0))
89
+
90
+ def rotate(self, angle: float) -> Transform:
91
+ """Return this transformation rotated by `angle` radians."""
92
+ c = _normSinCos(math.cos(angle))
93
+ s = _normSinCos(math.sin(angle))
94
+ return self.transform((c, s, -s, c, 0, 0))
95
+
96
+ def skew(self, x: float = 0, y: float = 0) -> Transform:
97
+ """Return this transformation skewed by `x` and `y` radians."""
98
+ return self.transform((1, math.tan(y), math.tan(x), 1, 0, 0))
99
+
100
+ def transform(self, other: Sequence[float]) -> Transform:
101
+ """Return `other` applied first, then this transformation."""
102
+ xx1, xy1, yx1, yy1, dx1, dy1 = other
103
+ xx2, xy2, yx2, yy2, dx2, dy2 = self
104
+ return self.__class__(
105
+ xx1 * xx2 + xy1 * yx2,
106
+ xx1 * xy2 + xy1 * yy2,
107
+ yx1 * xx2 + yy1 * yx2,
108
+ yx1 * xy2 + yy1 * yy2,
109
+ xx2 * dx1 + yx2 * dy1 + dx2,
110
+ xy2 * dx1 + yy2 * dy1 + dy2,
111
+ )
112
+
113
+ def reverseTransform(self, other: Sequence[float]) -> Transform:
114
+ """Return this transformation applied first, then `other`."""
115
+ xx1, xy1, yx1, yy1, dx1, dy1 = self
116
+ xx2, xy2, yx2, yy2, dx2, dy2 = other
117
+ return self.__class__(
118
+ xx1 * xx2 + xy1 * yx2,
119
+ xx1 * xy2 + xy1 * yy2,
120
+ yx1 * xx2 + yy1 * yx2,
121
+ yx1 * xy2 + yy1 * yy2,
122
+ xx2 * dx1 + yx2 * dy1 + dx2,
123
+ xy2 * dx1 + yy2 * dy1 + dy2,
124
+ )
125
+
126
+ def inverse(self) -> Transform:
127
+ """Return the inverse transformation (ZeroDivisionError if singular)."""
128
+ if self == Identity:
129
+ return self
130
+ xx, xy, yx, yy, dx, dy = self
131
+ det = xx * yy - yx * xy
132
+ xx, xy, yx, yy = yy / det, -xy / det, -yx / det, xx / det
133
+ dx, dy = -xx * dx - yx * dy, -xy * dx - yy * dy
134
+ return self.__class__(xx, xy, yx, yy, dx, dy)
135
+
136
+ def toPS(self) -> str:
137
+ """Return the PostScript matrix representation, e.g. `[2 0 0 3 8 15]`."""
138
+ return "[{!s} {!s} {!s} {!s} {!s} {!s}]".format(*self)
139
+
140
+ def __bool__(self) -> bool:
141
+ """True unless this is the identity transformation."""
142
+ return self != Identity
143
+
144
+ def __repr__(self) -> str:
145
+ return "<{!s} [{:g} {:g} {:g} {:g} {:g} {:g}]>".format(
146
+ self.__class__.__name__, *map(float, self)
147
+ )
148
+
149
+
150
+ Identity = Transform()
151
+
152
+
153
+ def Offset(x: float = 0, y: float = 0) -> Transform:
154
+ """Return the identity transformation offset by `x, y`."""
155
+ return Transform(1, 0, 0, 1, x, y)
156
+
157
+
158
+ def Scale(x: float, y: float | None = None) -> Transform:
159
+ """Return the identity transformation scaled by `x, y` (`y` defaults to `x`)."""
160
+ if y is None:
161
+ y = x
162
+ return Transform(x, 0, 0, y, 0, 0)
163
+
164
+
165
+ def _asTransform(transformation: Sequence[float]) -> Transform:
166
+ if hasattr(transformation, "transformPoint"):
167
+ return transformation # type: ignore[return-value]
168
+ return Transform(*transformation)
169
+
170
+
171
+ class TransformPen(FilterPen):
172
+ """Segment pen that transforms coordinates (and components) before forwarding."""
173
+
174
+ def __init__(self, outPen: AbstractPen, transformation: Sequence[float]) -> None:
175
+ super().__init__(outPen)
176
+ transformation = _asTransform(transformation)
177
+ self._transformation = transformation
178
+ self._transformPoint = transformation.transformPoint
179
+ self._stack: list = []
180
+
181
+ def moveTo(self, pt):
182
+ self._outPen.moveTo(self._transformPoint(pt))
183
+
184
+ def lineTo(self, pt):
185
+ self._outPen.lineTo(self._transformPoint(pt))
186
+
187
+ def curveTo(self, *points):
188
+ self._outPen.curveTo(*self._transformPoints(points))
189
+
190
+ def qCurveTo(self, *points):
191
+ if points[-1] is None:
192
+ points = [*self._transformPoints(points[:-1]), None]
193
+ else:
194
+ points = self._transformPoints(points)
195
+ self._outPen.qCurveTo(*points)
196
+
197
+ def _transformPoints(self, points):
198
+ transformPoint = self._transformPoint
199
+ return [transformPoint(pt) for pt in points]
200
+
201
+ def closePath(self):
202
+ self._outPen.closePath()
203
+
204
+ def endPath(self):
205
+ self._outPen.endPath()
206
+
207
+ def addComponent(self, glyphName, transformation):
208
+ self._outPen.addComponent(glyphName, self._transformation.transform(transformation))
209
+
210
+
211
+ class TransformPointPen(FilterPointPen):
212
+ """Point pen that transforms coordinates (and components) before forwarding."""
213
+
214
+ def __init__(self, outPointPen: AbstractPointPen, transformation: Sequence[float]) -> None:
215
+ super().__init__(outPointPen)
216
+ transformation = _asTransform(transformation)
217
+ self._transformation = transformation
218
+ self._transformPoint = transformation.transformPoint
219
+
220
+ def addPoint(self, pt, segmentType=None, smooth=False, name=None, **kwargs):
221
+ self._outPen.addPoint(self._transformPoint(pt), segmentType, smooth, name, **kwargs)
222
+
223
+ def addComponent(self, baseGlyphName, transformation, **kwargs):
224
+ transformation = self._transformation.transform(transformation)
225
+ self._outPen.addComponent(baseGlyphName, transformation, **kwargs)