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.
@@ -0,0 +1,168 @@
1
+ # this_file: src/fontlab_pens/__init__.py
2
+ """fontTools-compatible Pen and PointPen protocol for FontLab, with no dependencies.
3
+
4
+ The selected implemented APIs use the class and function names of
5
+ `fontTools.pens`, with parity tests for protocol-compatible calls. This is not
6
+ the complete fontTools pen API set; see README for included and unported APIs. The native pens (`FontGatePointPen`,
7
+ `FlPointPen` and friends) target layers and elements and import
8
+ `fontgate`/`fontlab` lazily, so importing this package works anywhere. Their
9
+ readers live in `fontlab_pens.fontgate` and `fontlab_pens.fontlab`
10
+ (`draw_points`, `draw`).
11
+ """
12
+
13
+ from importlib.metadata import PackageNotFoundError, version
14
+
15
+ from fontlab_pens._native import (
16
+ ComponentError,
17
+ IncompleteContour,
18
+ StagedPoint,
19
+ StagingPointPen,
20
+ invert_transform,
21
+ layer_of,
22
+ staged_node_kinds,
23
+ )
24
+ from fontlab_pens.base import (
25
+ AbstractPen,
26
+ BasePen,
27
+ DecomposingPen,
28
+ MissingComponentError,
29
+ NullPen,
30
+ OpenContourError,
31
+ PenError,
32
+ decomposeQuadraticSegment,
33
+ decomposeSuperBezierSegment,
34
+ )
35
+ from fontlab_pens.filter import (
36
+ ContourFilterPen,
37
+ ContourFilterPointPen,
38
+ FilterPen,
39
+ FilterPointPen,
40
+ OnCurveFirstPointPen,
41
+ )
42
+ from fontlab_pens.fontgate import (
43
+ FONTGATE_NODE_TYPES,
44
+ FontGatePen,
45
+ FontGatePointPen,
46
+ edit_geometry_ready,
47
+ )
48
+ from fontlab_pens.fontlab import FlPen, FlPointPen
49
+ from fontlab_pens.measure import AreaPen, BoundsPen, ControlBoundsPen, PointInsidePen
50
+ from fontlab_pens.point import (
51
+ AbstractPointPen,
52
+ BasePointToSegmentPen,
53
+ DecomposingPointPen,
54
+ GuessSmoothPointPen,
55
+ PointToSegmentPen,
56
+ ReverseContourPointPen,
57
+ ReverseFlipped,
58
+ SegmentToPointPen,
59
+ )
60
+ from fontlab_pens.qt import QPainterPathPen, draw_onoff_contours
61
+ from fontlab_pens.recording import (
62
+ DecomposingRecordingPen,
63
+ DecomposingRecordingPointPen,
64
+ RecordingPen,
65
+ RecordingPointPen,
66
+ lerpRecordings,
67
+ replayRecording,
68
+ )
69
+ from fontlab_pens.reverse import ReverseContourPen, reversedContour
70
+ from fontlab_pens.rounding import RoundingPen, RoundingPointPen, noRound, otRound
71
+ from fontlab_pens.stroke import (
72
+ Cap,
73
+ CapType,
74
+ Join,
75
+ StrokePlan,
76
+ StrokeStyle,
77
+ UnsupportedStroke,
78
+ apply_plan,
79
+ apply_stroke,
80
+ compatibility,
81
+ expand_stroke,
82
+ )
83
+ from fontlab_pens.transform import (
84
+ Identity,
85
+ Offset,
86
+ Scale,
87
+ Transform,
88
+ TransformPen,
89
+ TransformPointPen,
90
+ )
91
+
92
+ try:
93
+ __version__ = version("fontlab-python-pens")
94
+ except PackageNotFoundError: # running from a source tree without metadata
95
+ __version__ = "0.1.0"
96
+
97
+ __all__ = [
98
+ "FONTGATE_NODE_TYPES",
99
+ "AbstractPen",
100
+ "AbstractPointPen",
101
+ "AreaPen",
102
+ "BasePen",
103
+ "BasePointToSegmentPen",
104
+ "BoundsPen",
105
+ "Cap",
106
+ "CapType",
107
+ "ComponentError",
108
+ "ContourFilterPen",
109
+ "ContourFilterPointPen",
110
+ "ControlBoundsPen",
111
+ "DecomposingPen",
112
+ "DecomposingPointPen",
113
+ "DecomposingRecordingPen",
114
+ "DecomposingRecordingPointPen",
115
+ "FilterPen",
116
+ "FilterPointPen",
117
+ "FlPen",
118
+ "FlPointPen",
119
+ "FontGatePen",
120
+ "FontGatePointPen",
121
+ "GuessSmoothPointPen",
122
+ "Identity",
123
+ "IncompleteContour",
124
+ "Join",
125
+ "MissingComponentError",
126
+ "NullPen",
127
+ "Offset",
128
+ "OnCurveFirstPointPen",
129
+ "OpenContourError",
130
+ "PenError",
131
+ "PointInsidePen",
132
+ "PointToSegmentPen",
133
+ "QPainterPathPen",
134
+ "RecordingPen",
135
+ "RecordingPointPen",
136
+ "ReverseContourPen",
137
+ "ReverseContourPointPen",
138
+ "ReverseFlipped",
139
+ "RoundingPen",
140
+ "RoundingPointPen",
141
+ "Scale",
142
+ "SegmentToPointPen",
143
+ "StagedPoint",
144
+ "StagingPointPen",
145
+ "StrokePlan",
146
+ "StrokeStyle",
147
+ "Transform",
148
+ "TransformPen",
149
+ "TransformPointPen",
150
+ "UnsupportedStroke",
151
+ "__version__",
152
+ "apply_plan",
153
+ "apply_stroke",
154
+ "compatibility",
155
+ "decomposeQuadraticSegment",
156
+ "decomposeSuperBezierSegment",
157
+ "draw_onoff_contours",
158
+ "edit_geometry_ready",
159
+ "expand_stroke",
160
+ "invert_transform",
161
+ "layer_of",
162
+ "lerpRecordings",
163
+ "noRound",
164
+ "otRound",
165
+ "replayRecording",
166
+ "reversedContour",
167
+ "staged_node_kinds",
168
+ ]
@@ -0,0 +1,227 @@
1
+ # this_file: src/fontlab_pens/_native.py
2
+ """Shared helpers for the native FontGate (`fg*`) and FontLab (`fl*`) pens.
3
+
4
+ Native pens target a layer or an element (shape), never a glyph. Targets are
5
+ recognised by `type(obj).__name__` only: an attribute lookup that falls through
6
+ on a FontGate `fgShape` recurses until FontLab crashes, so nothing here probes
7
+ native objects with `hasattr`/`getattr(..., default)` or formats them with
8
+ `repr()`/`str()`. Error messages name the type only.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ from typing import Any
15
+
16
+ from fontlab_pens.base import PenError
17
+ from fontlab_pens.point import AbstractPointPen, PointToSegmentPen
18
+ from fontlab_pens.recording import RecordingPen
19
+ from fontlab_pens.transform import Transform
20
+
21
+ __all__ = [
22
+ "ComponentError",
23
+ "IncompleteContour",
24
+ "StagedPoint",
25
+ "StagingPointPen",
26
+ "invert_transform",
27
+ "layer_of",
28
+ "staged_node_kinds",
29
+ ]
30
+
31
+ GLYPH_HINT = (
32
+ "pen targets are layers or elements, not glyphs: pass glyph.layers[...], "
33
+ "glyph.findLayer(master), layer.shapes[i], or layer_of(glyph, master)"
34
+ )
35
+
36
+
37
+ class ComponentError(PenError):
38
+ """The target cannot hold a component (an element, or any FontGate target)."""
39
+
40
+
41
+ class IncompleteContour(ValueError):
42
+ """A point-editing contour has not reached a valid pen path yet."""
43
+
44
+
45
+ def target_kind(target: Any, layer_type: str, element_type: str, glyph_type: str) -> str:
46
+ """Return "layer" or "element" for a native target, judged by type name only."""
47
+ name = type(target).__name__
48
+ if name == layer_type:
49
+ return "layer"
50
+ if name == element_type:
51
+ return "element"
52
+ if name == glyph_type:
53
+ raise TypeError(f"{name} given; {GLYPH_HINT}")
54
+ raise TypeError(f"expected {layer_type} or {element_type}, got {name}")
55
+
56
+
57
+ def layer_of(glyph: Any, master: str) -> Any:
58
+ """Return the layer of an `fgGlyph` or `flGlyph` named `master`; never guess one."""
59
+ if not master:
60
+ raise ValueError("layer_of needs a master (layer) name")
61
+ name = type(glyph).__name__
62
+ if name == "fgGlyph":
63
+ layer = next((lay for lay in glyph.layers if lay.name == master), None)
64
+ elif name == "flGlyph":
65
+ layer = glyph.findLayer(master)
66
+ else:
67
+ raise TypeError(f"layer_of expects an fgGlyph or flGlyph, got {name}")
68
+ if layer is None:
69
+ raise KeyError(f"{name} has no layer named {master!r}")
70
+ return layer
71
+
72
+
73
+ def no_identifier(identifier: str | None) -> None:
74
+ """Reject UFO identifiers before any data is written: natives store none."""
75
+ if identifier is not None:
76
+ raise PenError("FontLab native contours and components store no identifiers")
77
+
78
+
79
+ def check_transformation(transformation: Any) -> tuple[float, ...]:
80
+ """Return a finite 6-value affine tuple or raise ValueError."""
81
+ values = tuple(transformation)
82
+ if len(values) != 6:
83
+ raise ValueError("An affine transform needs six values")
84
+ if not all(math.isfinite(v) for v in values):
85
+ raise ValueError("Transform values must be finite")
86
+ return values
87
+
88
+
89
+ def invert_transform(transformation: Transform) -> Transform:
90
+ """Return the inverse of a target's matrix, for writing in its coordinates.
91
+
92
+ Raises ValueError (not ZeroDivisionError) for a singular matrix, because no
93
+ point can be written through it.
94
+ """
95
+ try:
96
+ return transformation.inverse()
97
+ except ZeroDivisionError as error:
98
+ raise ValueError("Cannot draw into a singular native transform") from error
99
+
100
+
101
+ StagedPoint = tuple[tuple[float, float], str | None, bool, str | None]
102
+ """One point collected by `StagingPointPen`: ((x, y), segmentType, smooth, name)."""
103
+
104
+
105
+ def staged_node_kinds(points: list[StagedPoint]) -> list[str]:
106
+ """Classify each staged point as "move", "on", "cubic" or "quad".
107
+
108
+ An off-curve point (segmentType None) is "cubic" when the next on-curve
109
+ point is a "curve", else "quad"; wrapping around for closed contours.
110
+ """
111
+ next_endpoint = next((p[1] for p in points if p[1] is not None), "qcurve")
112
+ kinds = [""] * len(points)
113
+ for index in range(len(points) - 1, -1, -1):
114
+ _, segment_type, _, _ = points[index]
115
+ if segment_type is None:
116
+ kinds[index] = "cubic" if next_endpoint == "curve" else "quad"
117
+ else:
118
+ kinds[index] = "move" if segment_type == "move" else "on"
119
+ next_endpoint = segment_type
120
+ return kinds
121
+
122
+
123
+ class StagingPointPen(AbstractPointPen):
124
+ """Collect a contour, validate it as pen geometry, then hand it to `append_contour`.
125
+
126
+ Nothing reaches the native side until the whole contour is known to be
127
+ valid, so a malformed contour never leaves partial native data behind.
128
+ Subclasses implement `append_contour` (called only with validated points)
129
+ and `addComponent`, which should start with `check_component`.
130
+ """
131
+
132
+ def __init__(self) -> None:
133
+ self._points: list[StagedPoint] | None = None
134
+
135
+ def beginPath(self, identifier: str | None = None, **kwargs: Any) -> None:
136
+ no_identifier(identifier)
137
+ if self._points is not None:
138
+ raise ValueError("A contour is already active")
139
+ self._points = []
140
+
141
+ def addPoint(
142
+ self,
143
+ pt: tuple[float, float],
144
+ segmentType: str | None = None,
145
+ smooth: bool = False,
146
+ name: str | None = None,
147
+ identifier: str | None = None,
148
+ **kwargs: Any,
149
+ ) -> None:
150
+ no_identifier(identifier)
151
+ if self._points is None:
152
+ raise ValueError("Call beginPath before addPoint")
153
+ if segmentType not in (None, "move", "line", "curve", "qcurve"):
154
+ raise ValueError(f"Unknown segment type: {segmentType!r}")
155
+ x, y = pt
156
+ if not all(math.isfinite(v) for v in (x, y)):
157
+ raise ValueError("Point coordinates must be finite")
158
+ self._points.append(((float(x), float(y)), segmentType, bool(smooth), name))
159
+
160
+ def endPath(self) -> None:
161
+ if self._points is None:
162
+ raise ValueError("Call beginPath before endPath")
163
+ points, self._points = self._points, None
164
+ if not points:
165
+ return # Empty editing contours have no native geometry.
166
+ validate(points)
167
+ self.append_contour(points)
168
+
169
+ def append_contour(self, points: list[StagedPoint]) -> None:
170
+ """Store one validated, non-empty contour; `endPath` calls it."""
171
+ raise NotImplementedError
172
+
173
+ def check_component(self, transformation: Any, identifier: str | None = None) -> tuple:
174
+ """Refuse identifiers and components inside a contour; return the 6-value matrix."""
175
+ no_identifier(identifier)
176
+ if self._points is not None:
177
+ raise ValueError("Cannot add a component inside a contour")
178
+ return check_transformation(transformation)
179
+
180
+
181
+ def validate(points: list[StagedPoint]) -> None:
182
+ """Raise IncompleteContour/PenError unless `points` form a valid pen contour.
183
+
184
+ A "move" after the first point is rejected. fontTools raises for it after a
185
+ leading move but silently re-reads [line, move, ...] as an open contour;
186
+ natively it would store a mid-contour Move node, so it is refused here.
187
+ """
188
+ if any(p[1] == "move" for p in points[1:]):
189
+ raise PenError("A 'move' point may only start a contour")
190
+ for index, (_, kind, _, _) in enumerate(points):
191
+ if kind != "curve":
192
+ continue
193
+ preceding = points[:index][::-1] + points[index + 1 :][::-1]
194
+ controls = 0
195
+ for point in preceding:
196
+ if point[1] is not None:
197
+ break
198
+ controls += 1
199
+ if controls != 2:
200
+ raise IncompleteContour("A cubic segment needs two control points")
201
+ if points[0][1] == "move" and points[-1][1] is None:
202
+ raise IncompleteContour("An open contour ends in incomplete controls")
203
+ check = PointToSegmentPen(RecordingPen())
204
+ check.beginPath()
205
+ for position, kind, smooth, name in points:
206
+ check.addPoint(position, kind, smooth, name)
207
+ check.endPath()
208
+
209
+
210
+ # Read node: (x, y, kind, smooth, name) with kind in "on", "cubic", "quad".
211
+ def emit_contour(
212
+ nodes: list[tuple[float, float, str, bool, str]], is_open: bool, pen: AbstractPointPen
213
+ ) -> None:
214
+ """Send one contour to a point pen as UFO points (off-curves get segmentType None)."""
215
+ if not nodes:
216
+ return # Empty contours are skipped, never handed to native code.
217
+ pen.beginPath()
218
+ for index, (x, y, kind, smooth, name) in enumerate(nodes):
219
+ if kind != "on":
220
+ segment_type = None
221
+ elif is_open and index == 0:
222
+ segment_type = "move"
223
+ else:
224
+ previous = nodes[index - 1][2]
225
+ segment_type = {"cubic": "curve", "quad": "qcurve"}.get(previous, "line")
226
+ pen.addPoint((x, y), segment_type, bool(smooth), name or None)
227
+ pen.endPath()