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/__init__.py +168 -0
- fontlab_pens/_native.py +227 -0
- fontlab_pens/base.py +332 -0
- fontlab_pens/filter.py +181 -0
- fontlab_pens/fontgate.py +276 -0
- fontlab_pens/fontlab.py +275 -0
- fontlab_pens/measure.py +423 -0
- fontlab_pens/point.py +536 -0
- fontlab_pens/qt.py +82 -0
- fontlab_pens/recording.py +159 -0
- fontlab_pens/reverse.py +103 -0
- fontlab_pens/rounding.py +116 -0
- fontlab_pens/stroke.py +420 -0
- fontlab_pens/transform.py +225 -0
- fontlab_python_pens-1.0.8.dist-info/METADATA +225 -0
- fontlab_python_pens-1.0.8.dist-info/RECORD +19 -0
- fontlab_python_pens-1.0.8.dist-info/WHEEL +4 -0
- fontlab_python_pens-1.0.8.dist-info/licenses/LICENSE +201 -0
- fontlab_python_pens-1.0.8.dist-info/licenses/NOTICE +46 -0
fontlab_pens/fontgate.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
# this_file: src/fontlab_pens/fontgate.py
|
|
2
|
+
"""Pens and readers over FontGate (`fontgate.fg*`) layers and elements.
|
|
3
|
+
|
|
4
|
+
Targets are an `fgLayer` or an `fgShape` (element), never an `fgGlyph`.
|
|
5
|
+
Writing to a layer creates one new element for the pen session; writing to an
|
|
6
|
+
element appends to it. Each contour is validated in Python first, then stored
|
|
7
|
+
with a single `contour.nodes = [...]` assignment (point names and smooth flags
|
|
8
|
+
kept). FontGate components are glyph-level only, so `addComponent` raises
|
|
9
|
+
`ComponentError`. Empty native contours are never handed to native
|
|
10
|
+
`drawPoints`, which dereferences the first node unchecked.
|
|
11
|
+
|
|
12
|
+
The native `fgPen` fast path is not offered: it binds to a glyph's work shape,
|
|
13
|
+
which conflicts with the layer/element rule.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from types import TracebackType
|
|
19
|
+
from typing import Any, Self
|
|
20
|
+
|
|
21
|
+
from fontlab_pens._native import (
|
|
22
|
+
ComponentError,
|
|
23
|
+
IncompleteContour,
|
|
24
|
+
StagedPoint,
|
|
25
|
+
StagingPointPen,
|
|
26
|
+
emit_contour,
|
|
27
|
+
invert_transform,
|
|
28
|
+
no_identifier,
|
|
29
|
+
staged_node_kinds,
|
|
30
|
+
target_kind,
|
|
31
|
+
)
|
|
32
|
+
from fontlab_pens.base import AbstractPen, PenError
|
|
33
|
+
from fontlab_pens.point import AbstractPointPen, PointToSegmentPen, SegmentToPointPen
|
|
34
|
+
from fontlab_pens.transform import Identity, Transform, TransformPointPen
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"FONTGATE_NODE_TYPES",
|
|
38
|
+
"FontGatePen",
|
|
39
|
+
"FontGatePointPen",
|
|
40
|
+
"IncompleteContour",
|
|
41
|
+
"draw",
|
|
42
|
+
"draw_contour_points",
|
|
43
|
+
"draw_points",
|
|
44
|
+
"edit_geometry_ready",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
FONTGATE_NODE_TYPES = {"move": "Move", "on": "On", "cubic": "Curve", "quad": "Off"}
|
|
48
|
+
"""FontGate `fgNode` type name for each `staged_node_kinds` kind."""
|
|
49
|
+
_READ_KIND = {"Move": "on", "On": "on", "Curve": "cubic", "Off": "quad"}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _kind(target: Any) -> str:
|
|
53
|
+
return target_kind(target, "fgLayer", "fgShape", "fgGlyph")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _matrix(native_object: Any) -> Transform:
|
|
57
|
+
"""Plain Transform from a native matrix (never pass the fgMatrix itself on)."""
|
|
58
|
+
return Transform(*native_object.matrix.asTuple())
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class FontGatePointPen(StagingPointPen):
|
|
62
|
+
"""Point pen that writes validated contours into an fgLayer or an fgShape.
|
|
63
|
+
|
|
64
|
+
A layer target gets one new element, created lazily with the first contour
|
|
65
|
+
and reused for the rest of the session. Coordinates are layer coordinates
|
|
66
|
+
for a layer target and element-space-before-matrix for an element target:
|
|
67
|
+
they are mapped through the inverse of `layer.matrix` or `shape.matrix`
|
|
68
|
+
respectively, so `draw_points` on the same target reads them back.
|
|
69
|
+
|
|
70
|
+
The target kind is detected from the native type name. Pass
|
|
71
|
+
`kind="layer"` or `kind="element"` to state it instead, for a wrapper or
|
|
72
|
+
test double that behaves like an fgLayer or fgShape.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
# Class default keeps subclasses that skip __init__ (public adapters) working.
|
|
76
|
+
_closed = False
|
|
77
|
+
|
|
78
|
+
def __init__(self, target: Any, *, native: Any = None, kind: str | None = None) -> None:
|
|
79
|
+
super().__init__()
|
|
80
|
+
if kind is None or type(target).__name__ in ("fgGlyph", "flGlyph"):
|
|
81
|
+
kind = _kind(target)
|
|
82
|
+
elif kind not in ("layer", "element"):
|
|
83
|
+
raise PenError(f'kind must be "layer" or "element", not {kind!r}')
|
|
84
|
+
self._target_kind = kind
|
|
85
|
+
self.target = target
|
|
86
|
+
self.native = native
|
|
87
|
+
self._shape: Any = target if self._target_kind == "element" else None
|
|
88
|
+
|
|
89
|
+
def _native(self) -> Any:
|
|
90
|
+
if self.native is None:
|
|
91
|
+
import fontgate
|
|
92
|
+
|
|
93
|
+
self.native = fontgate
|
|
94
|
+
return self.native
|
|
95
|
+
|
|
96
|
+
def append_contour(self, points: list[StagedPoint]) -> None:
|
|
97
|
+
native = self._native()
|
|
98
|
+
# Element: its own matrix. Layer: layer.matrix (the new element's is identity).
|
|
99
|
+
mapping = invert_transform(_matrix(self.target))
|
|
100
|
+
nodes = [
|
|
101
|
+
native.fgNode(
|
|
102
|
+
FONTGATE_NODE_TYPES[kind],
|
|
103
|
+
native.fgPoint(*mapping.transformPoint(position)),
|
|
104
|
+
name or "",
|
|
105
|
+
smooth,
|
|
106
|
+
)
|
|
107
|
+
for (position, _, smooth, name), kind in zip(
|
|
108
|
+
points, staged_node_kinds(points), strict=True
|
|
109
|
+
)
|
|
110
|
+
]
|
|
111
|
+
contour = native.fgContour()
|
|
112
|
+
contour.nodes = nodes
|
|
113
|
+
contour.open = points[0][1] == "move"
|
|
114
|
+
if self._shape is None:
|
|
115
|
+
shape = native.fgShape()
|
|
116
|
+
shape.contours.append(contour)
|
|
117
|
+
shapes = self.target.shapes
|
|
118
|
+
shapes.append(shape)
|
|
119
|
+
# append stores a copy: re-fetch the stored element and keep it.
|
|
120
|
+
self._shape = shapes[len(shapes) - 1]
|
|
121
|
+
else:
|
|
122
|
+
self._shape.contours.append(contour)
|
|
123
|
+
|
|
124
|
+
def beginPath(self, identifier: str | None = None, **kwargs: Any) -> None:
|
|
125
|
+
if self._closed:
|
|
126
|
+
raise PenError("This pen is closed; create a new pen to write again")
|
|
127
|
+
super().beginPath(identifier, **kwargs)
|
|
128
|
+
|
|
129
|
+
def close(self) -> None:
|
|
130
|
+
"""End the session; contours were already written at each endPath.
|
|
131
|
+
|
|
132
|
+
Raises PenError for an unfinished contour, like `FlPointPen.close`.
|
|
133
|
+
Closing twice is harmless; drawing after close raises PenError.
|
|
134
|
+
"""
|
|
135
|
+
if self._closed:
|
|
136
|
+
return
|
|
137
|
+
if self._points is not None:
|
|
138
|
+
raise PenError("Cannot close the pen inside an open contour")
|
|
139
|
+
self._closed = True
|
|
140
|
+
|
|
141
|
+
def __enter__(self) -> Self:
|
|
142
|
+
return self
|
|
143
|
+
|
|
144
|
+
def __exit__(
|
|
145
|
+
self,
|
|
146
|
+
exc_type: type[BaseException] | None,
|
|
147
|
+
exc: BaseException | None,
|
|
148
|
+
tb: TracebackType | None,
|
|
149
|
+
) -> None:
|
|
150
|
+
"""Close on success; on an exception drop the open contour and close.
|
|
151
|
+
|
|
152
|
+
FontGate writes each contour at its endPath, so contours finished
|
|
153
|
+
before the exception stay written (unlike `FlPointPen`, which stages
|
|
154
|
+
until close). The exception is never swallowed.
|
|
155
|
+
"""
|
|
156
|
+
if exc_type is None:
|
|
157
|
+
self.close()
|
|
158
|
+
else:
|
|
159
|
+
self._points = None
|
|
160
|
+
self._closed = True
|
|
161
|
+
|
|
162
|
+
def addComponent(
|
|
163
|
+
self,
|
|
164
|
+
baseGlyphName: str,
|
|
165
|
+
transformation: tuple,
|
|
166
|
+
identifier: str | None = None,
|
|
167
|
+
**kwargs: Any,
|
|
168
|
+
) -> None:
|
|
169
|
+
no_identifier(identifier)
|
|
170
|
+
raise ComponentError(
|
|
171
|
+
"FontGate components are glyph-level; an fgLayer or fgShape cannot hold one"
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class FontGatePen(SegmentToPointPen):
|
|
176
|
+
"""Segment pen over `FontGatePointPen` (same targets and rules)."""
|
|
177
|
+
|
|
178
|
+
def __init__(self, target: Any, *, native: Any = None, guessSmooth: bool = True) -> None:
|
|
179
|
+
self.pointPen = FontGatePointPen(target, native=native)
|
|
180
|
+
super().__init__(self.pointPen, guessSmooth)
|
|
181
|
+
|
|
182
|
+
def close(self) -> None:
|
|
183
|
+
"""Raise PenError for an unfinished contour, like `FlPen.close`."""
|
|
184
|
+
if self.contour is not None:
|
|
185
|
+
raise PenError("Unfinished contour: call closePath() or endPath() before close()")
|
|
186
|
+
self.pointPen.close()
|
|
187
|
+
|
|
188
|
+
def __enter__(self) -> Self:
|
|
189
|
+
return self
|
|
190
|
+
|
|
191
|
+
def __exit__(
|
|
192
|
+
self,
|
|
193
|
+
exc_type: type[BaseException] | None,
|
|
194
|
+
exc: BaseException | None,
|
|
195
|
+
tb: TracebackType | None,
|
|
196
|
+
) -> None:
|
|
197
|
+
if exc_type is None:
|
|
198
|
+
self.close()
|
|
199
|
+
else:
|
|
200
|
+
self.contour = None
|
|
201
|
+
self.pointPen.__exit__(exc_type, exc, tb)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def draw_points(
|
|
205
|
+
target: Any, pen: AbstractPointPen, *, components: bool = True, transform: bool = True
|
|
206
|
+
) -> None:
|
|
207
|
+
"""Draw an fgLayer (all elements, layer × element matrix) or one fgShape.
|
|
208
|
+
|
|
209
|
+
`components` is accepted for symmetry with `fontlab_pens.fontlab.draw_points`;
|
|
210
|
+
FontGate layers expose component placements as ordinary elements with
|
|
211
|
+
matrices (measured), so they are always drawn as contours. With
|
|
212
|
+
`transform=False` the native coordinates are drawn unmapped.
|
|
213
|
+
"""
|
|
214
|
+
if _kind(target) == "element":
|
|
215
|
+
shapes, base = [target], Identity
|
|
216
|
+
else:
|
|
217
|
+
shapes = target.shapes
|
|
218
|
+
base = _matrix(target) if transform else Identity
|
|
219
|
+
for shape in shapes:
|
|
220
|
+
mapping = base.transform(_matrix(shape)) if transform else Identity
|
|
221
|
+
for contour in shape.contours:
|
|
222
|
+
draw_contour_points(contour, pen, mapping)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def draw(target: Any, pen: AbstractPen, *, components: bool = True, transform: bool = True) -> None:
|
|
226
|
+
"""Segment-pen reader: `draw_points` through `PointToSegmentPen`."""
|
|
227
|
+
draw_points(target, PointToSegmentPen(pen), components=components, transform=transform)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def draw_contour_points(
|
|
231
|
+
contour: Any, pen: AbstractPointPen, transform: tuple | None = None
|
|
232
|
+
) -> None:
|
|
233
|
+
"""Emit one fgContour as UFO points, optionally through a 6-tuple transform.
|
|
234
|
+
|
|
235
|
+
A closed contour whose last node repeats a Move start (as native fgPen
|
|
236
|
+
writes it) loses the duplicate; deliberate repeated On points stay.
|
|
237
|
+
"""
|
|
238
|
+
nodes = [
|
|
239
|
+
(node.point.x, node.point.y, node.kind, node.smooth, node.name) for node in contour.nodes
|
|
240
|
+
]
|
|
241
|
+
if not nodes:
|
|
242
|
+
return
|
|
243
|
+
is_open = bool(contour.open)
|
|
244
|
+
first_smooth = nodes[0][3]
|
|
245
|
+
if not is_open and len(nodes) > 1 and nodes[0][2] == "Move" and nodes[0][:2] == nodes[-1][:2]:
|
|
246
|
+
first_smooth = nodes[-1][3]
|
|
247
|
+
nodes = nodes[:-1]
|
|
248
|
+
x, y, kind, _, name = nodes[0]
|
|
249
|
+
nodes[0] = (x, y, kind, first_smooth, name)
|
|
250
|
+
read = [(x, y, _READ_KIND[kind], smooth, name) for x, y, kind, smooth, name in nodes]
|
|
251
|
+
if transform is not None and transform != Identity:
|
|
252
|
+
pen = TransformPointPen(pen, tuple(transform))
|
|
253
|
+
emit_contour(read, is_open, pen)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
class _GeometryProbe(StagingPointPen):
|
|
257
|
+
"""Validates contours only: no target, no native allocation."""
|
|
258
|
+
|
|
259
|
+
def append_contour(self, points: list[StagedPoint]) -> None:
|
|
260
|
+
pass
|
|
261
|
+
|
|
262
|
+
def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):
|
|
263
|
+
no_identifier(identifier)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def edit_geometry_ready(target: Any) -> bool:
|
|
267
|
+
"""True when every contour of the target is valid pen geometry.
|
|
268
|
+
|
|
269
|
+
Provisional point edits stay in Python until they validate; nothing is
|
|
270
|
+
guessed or repaired.
|
|
271
|
+
"""
|
|
272
|
+
try:
|
|
273
|
+
draw_points(target, _GeometryProbe())
|
|
274
|
+
except (IncompleteContour, PenError):
|
|
275
|
+
return False
|
|
276
|
+
return True
|
fontlab_pens/fontlab.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
# this_file: src/fontlab_pens/fontlab.py
|
|
2
|
+
"""Pens and readers over FontLab (`fontlab.fl*`) layers and elements.
|
|
3
|
+
|
|
4
|
+
Targets are an `flLayer` or an `flShape` (element), never an `flGlyph`.
|
|
5
|
+
Contours are staged and validated in Python; `close()` (or leaving the `with`
|
|
6
|
+
block) writes them: a layer gets one new `flShape` holding all of them, an
|
|
7
|
+
element gets them appended. On a layer, `addComponent` is staged too and
|
|
8
|
+
`close()` adds the component elements and the contour shape in call order.
|
|
9
|
+
An exception in the drawing body writes nothing; a native commit failure may
|
|
10
|
+
leave partial geometry. The pen is spent even when a commit or notify fails.
|
|
11
|
+
An element cannot hold components, and a component element cannot take contours.
|
|
12
|
+
No undo history is recorded unless `notify="title"` is given for an attached
|
|
13
|
+
layer. Notification can change unrelated native timestamps; whole-font history
|
|
14
|
+
preservation is not guaranteed. Bare elements do not support notification.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from types import SimpleNamespace, TracebackType
|
|
20
|
+
from typing import Any, Self
|
|
21
|
+
|
|
22
|
+
from fontlab_pens._native import (
|
|
23
|
+
ComponentError,
|
|
24
|
+
StagedPoint,
|
|
25
|
+
StagingPointPen,
|
|
26
|
+
emit_contour,
|
|
27
|
+
invert_transform,
|
|
28
|
+
staged_node_kinds,
|
|
29
|
+
target_kind,
|
|
30
|
+
)
|
|
31
|
+
from fontlab_pens.base import AbstractPen, PenError
|
|
32
|
+
from fontlab_pens.point import AbstractPointPen, PointToSegmentPen, SegmentToPointPen
|
|
33
|
+
from fontlab_pens.transform import Identity, Transform, TransformPointPen
|
|
34
|
+
|
|
35
|
+
__all__ = ["FlPen", "FlPointPen", "draw", "draw_points"]
|
|
36
|
+
|
|
37
|
+
_NATIVE_KIND = {"move": "on", "on": "on", "cubic": "curve", "quad": "off"}
|
|
38
|
+
_READ_KIND = {"on": "on", "curve": "cubic", "off": "quad"}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _kind(target: Any) -> str:
|
|
42
|
+
return target_kind(target, "flLayer", "flShape", "flGlyph")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _transform(shape: Any) -> Transform:
|
|
46
|
+
"""Plain Transform from `shape.transform` (QTransform m11..dy)."""
|
|
47
|
+
t = shape.transform
|
|
48
|
+
return Transform(t.m11(), t.m12(), t.m21(), t.m22(), t.dx(), t.dy())
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _load_native() -> Any:
|
|
52
|
+
import fontlab
|
|
53
|
+
from PythonQt.QtCore import QPointF
|
|
54
|
+
from PythonQt.QtGui import QTransform
|
|
55
|
+
|
|
56
|
+
return SimpleNamespace(
|
|
57
|
+
flNode=fontlab.flNode,
|
|
58
|
+
flContour=fontlab.flContour,
|
|
59
|
+
flShape=fontlab.flShape,
|
|
60
|
+
flItems=fontlab.flItems,
|
|
61
|
+
QPointF=QPointF,
|
|
62
|
+
QTransform=QTransform,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class FlPointPen(StagingPointPen):
|
|
67
|
+
"""Point pen that writes validated contours into an flLayer or an flShape.
|
|
68
|
+
|
|
69
|
+
`native` is a namespace with `flNode`, `flContour`, `flShape`, `flItems`,
|
|
70
|
+
`QPointF` and `QTransform` (loaded from FontLab when omitted). Writing into
|
|
71
|
+
an element maps coordinates through the inverse of `shape.transform`, so
|
|
72
|
+
`draw_points` on the same element reads them back. After `close()` the pen
|
|
73
|
+
is spent: any further write raises `PenError`.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
def __init__(self, target: Any, *, native: Any = None, notify: str | None = None) -> None:
|
|
77
|
+
super().__init__()
|
|
78
|
+
self._target_kind = _kind(target)
|
|
79
|
+
if self._target_kind == "element" and target.shapeData.isComponent:
|
|
80
|
+
# Its contours are the base glyph's: writing would edit shared data.
|
|
81
|
+
raise ComponentError("A component flShape cannot take contours; use its flLayer")
|
|
82
|
+
self.target = target
|
|
83
|
+
self.native = native
|
|
84
|
+
self.notify = notify
|
|
85
|
+
self._contours: list = []
|
|
86
|
+
# Layer writes in call order: "shape" marks where the session shape goes,
|
|
87
|
+
# ("component", name, values) a component. Nothing is written before close().
|
|
88
|
+
self._ops: list = []
|
|
89
|
+
self._closed = False
|
|
90
|
+
|
|
91
|
+
def _native(self) -> Any:
|
|
92
|
+
if self.native is None:
|
|
93
|
+
self.native = _load_native()
|
|
94
|
+
return self.native
|
|
95
|
+
|
|
96
|
+
def _open(self) -> None:
|
|
97
|
+
if self._closed:
|
|
98
|
+
raise PenError("This pen is closed; create a new pen to write again")
|
|
99
|
+
|
|
100
|
+
def beginPath(self, identifier: str | None = None, **kwargs: Any) -> None:
|
|
101
|
+
self._open()
|
|
102
|
+
super().beginPath(identifier, **kwargs)
|
|
103
|
+
|
|
104
|
+
def append_contour(self, points: list[StagedPoint]) -> None:
|
|
105
|
+
native = self._native()
|
|
106
|
+
if self._target_kind == "element":
|
|
107
|
+
mapping = invert_transform(_transform(self.target))
|
|
108
|
+
else:
|
|
109
|
+
mapping = Identity
|
|
110
|
+
nodes = []
|
|
111
|
+
for (position, _, _, name), kind in zip(points, staged_node_kinds(points), strict=True):
|
|
112
|
+
node = native.flNode(
|
|
113
|
+
native.QPointF(*mapping.transformPoint(position)), nodeType=_NATIVE_KIND[kind]
|
|
114
|
+
)
|
|
115
|
+
node.name = name or ""
|
|
116
|
+
nodes.append(node)
|
|
117
|
+
if not self._contours:
|
|
118
|
+
self._ops.append("shape")
|
|
119
|
+
contour = native.flContour(nodes, closed=points[0][1] != "move")
|
|
120
|
+
# The smooth setter can move neighboring handles; assign metadata only.
|
|
121
|
+
for node, point in zip(contour.nodes(), points, strict=True):
|
|
122
|
+
if point[2]:
|
|
123
|
+
node.nodeState = node.nodeState | native.flNode.NodeKind["Smooth"]
|
|
124
|
+
self._contours.append(contour)
|
|
125
|
+
|
|
126
|
+
def addComponent(
|
|
127
|
+
self,
|
|
128
|
+
baseGlyphName: str,
|
|
129
|
+
transformation: tuple,
|
|
130
|
+
identifier: str | None = None,
|
|
131
|
+
**kwargs: Any,
|
|
132
|
+
) -> None:
|
|
133
|
+
self._open()
|
|
134
|
+
values = self.check_component(transformation, identifier)
|
|
135
|
+
if self._target_kind == "element":
|
|
136
|
+
raise ComponentError("An flShape element cannot hold a component; use its flLayer")
|
|
137
|
+
self._ops.append(("component", baseGlyphName, values))
|
|
138
|
+
|
|
139
|
+
def close(self) -> None:
|
|
140
|
+
"""Attempt the staged writes once; enrolled history is finalized on failure too.
|
|
141
|
+
|
|
142
|
+
Native writes are not atomic. A write or final-notify failure may leave
|
|
143
|
+
geometry changed; retrying this drawing with a new pen can duplicate it.
|
|
144
|
+
"""
|
|
145
|
+
if self._closed:
|
|
146
|
+
return
|
|
147
|
+
if self._points is not None:
|
|
148
|
+
raise PenError("Cannot close the pen inside an open contour")
|
|
149
|
+
self._closed = True
|
|
150
|
+
contours, self._contours = self._contours, []
|
|
151
|
+
ops, self._ops = self._ops, []
|
|
152
|
+
if not ops:
|
|
153
|
+
return
|
|
154
|
+
if self._target_kind == "layer" and self.target.autoLayer:
|
|
155
|
+
raise PenError("Cannot write into an automatic flLayer")
|
|
156
|
+
native = self._native()
|
|
157
|
+
if self.notify:
|
|
158
|
+
if self._target_kind == "element":
|
|
159
|
+
raise PenError("Element notification needs an owning layer; pass its flLayer")
|
|
160
|
+
glyph = self.target.glyph
|
|
161
|
+
if glyph is None:
|
|
162
|
+
raise PenError("Notification requires an flLayer attached to an flGlyph")
|
|
163
|
+
items = [self.target, glyph]
|
|
164
|
+
for item in items:
|
|
165
|
+
item.checkInitHistoryState(0)
|
|
166
|
+
attempted = False
|
|
167
|
+
try:
|
|
168
|
+
if self._target_kind == "element":
|
|
169
|
+
attempted = True
|
|
170
|
+
self.target.addContours(contours, True)
|
|
171
|
+
ops = [] # an element pen stages contours only
|
|
172
|
+
for op in ops:
|
|
173
|
+
if op == "shape":
|
|
174
|
+
shape = native.flShape()
|
|
175
|
+
shape.addContours(contours, True)
|
|
176
|
+
attempted = True
|
|
177
|
+
self.target.addShape(shape)
|
|
178
|
+
else:
|
|
179
|
+
_, name, values = op
|
|
180
|
+
component = (name, native.QTransform(*values))
|
|
181
|
+
attempted = True
|
|
182
|
+
self.target.addComponent(component)
|
|
183
|
+
except BaseException as error:
|
|
184
|
+
if self.notify and attempted:
|
|
185
|
+
try:
|
|
186
|
+
native.flItems.notifyChangesApplied(self.notify, items)
|
|
187
|
+
except BaseException as notify_error:
|
|
188
|
+
raise error from notify_error
|
|
189
|
+
raise
|
|
190
|
+
if self.notify:
|
|
191
|
+
native.flItems.notifyChangesApplied(self.notify, items)
|
|
192
|
+
|
|
193
|
+
def __enter__(self) -> Self:
|
|
194
|
+
return self
|
|
195
|
+
|
|
196
|
+
def __exit__(
|
|
197
|
+
self, exc_type: type[BaseException] | None,
|
|
198
|
+
exc: BaseException | None, tb: TracebackType | None,
|
|
199
|
+
) -> None:
|
|
200
|
+
if exc_type is None:
|
|
201
|
+
self.close()
|
|
202
|
+
else:
|
|
203
|
+
# A failed drawing commits nothing.
|
|
204
|
+
self._contours = []
|
|
205
|
+
self._ops = []
|
|
206
|
+
self._points = None
|
|
207
|
+
self._closed = True
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class FlPen(SegmentToPointPen):
|
|
211
|
+
"""Segment pen over `FlPointPen`; call `close()` or use it as a context manager."""
|
|
212
|
+
|
|
213
|
+
def __init__(
|
|
214
|
+
self,
|
|
215
|
+
target: Any,
|
|
216
|
+
*,
|
|
217
|
+
native: Any = None,
|
|
218
|
+
notify: str | None = None,
|
|
219
|
+
guessSmooth: bool = True,
|
|
220
|
+
) -> None:
|
|
221
|
+
self.pointPen = FlPointPen(target, native=native, notify=notify)
|
|
222
|
+
super().__init__(self.pointPen, guessSmooth)
|
|
223
|
+
|
|
224
|
+
def addComponent(self, glyphName: str, transformation: tuple) -> None:
|
|
225
|
+
self.pointPen.addComponent(glyphName, transformation)
|
|
226
|
+
|
|
227
|
+
def close(self) -> None:
|
|
228
|
+
if self.contour is not None:
|
|
229
|
+
raise PenError("Unfinished contour: call closePath() or endPath() before close()")
|
|
230
|
+
self.pointPen.close()
|
|
231
|
+
|
|
232
|
+
def __enter__(self) -> Self:
|
|
233
|
+
return self
|
|
234
|
+
|
|
235
|
+
def __exit__(
|
|
236
|
+
self, exc_type: type[BaseException] | None,
|
|
237
|
+
exc: BaseException | None, tb: TracebackType | None,
|
|
238
|
+
) -> None:
|
|
239
|
+
if exc_type is None:
|
|
240
|
+
self.close() # raises PenError on an unfinished contour
|
|
241
|
+
else:
|
|
242
|
+
self.contour = None
|
|
243
|
+
self.pointPen.__exit__(exc_type, exc, tb)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def draw_points(
|
|
247
|
+
target: Any, pen: AbstractPointPen, *, components: bool = True, transform: bool = True
|
|
248
|
+
) -> None:
|
|
249
|
+
"""Draw an flLayer (every element) or one flShape into a point pen.
|
|
250
|
+
|
|
251
|
+
Contours are mapped by `shape.transform` unless `transform=False`. With
|
|
252
|
+
`components=True` a component element (`shapeData.isComponent`) is reported
|
|
253
|
+
as `addComponent(shapeData.componentGlyph, shape transform)`; otherwise its
|
|
254
|
+
base contours are drawn.
|
|
255
|
+
"""
|
|
256
|
+
shapes = [target] if _kind(target) == "element" else target.shapes
|
|
257
|
+
for shape in shapes:
|
|
258
|
+
mapping = _transform(shape) if transform else Identity
|
|
259
|
+
if components:
|
|
260
|
+
data = shape.shapeData
|
|
261
|
+
if data.isComponent:
|
|
262
|
+
pen.addComponent(data.componentGlyph, tuple(_transform(shape)))
|
|
263
|
+
continue
|
|
264
|
+
shape_pen = pen if mapping == Identity else TransformPointPen(pen, tuple(mapping))
|
|
265
|
+
for contour in shape.contours:
|
|
266
|
+
read = [
|
|
267
|
+
(node.x, node.y, _READ_KIND[node.type], node.smooth, node.name)
|
|
268
|
+
for node in contour.nodes()
|
|
269
|
+
]
|
|
270
|
+
emit_contour(read, not contour.closed, shape_pen)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def draw(target: Any, pen: AbstractPen, *, components: bool = True, transform: bool = True) -> None:
|
|
274
|
+
"""Segment-pen reader: `draw_points` through `PointToSegmentPen`."""
|
|
275
|
+
draw_points(target, PointToSegmentPen(pen), components=components, transform=transform)
|