-
Notifications
You must be signed in to change notification settings - Fork 35
/
component.py
417 lines (344 loc) · 14.1 KB
/
component.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
from __future__ import absolute_import
import weakref
from warnings import warn
from fontTools.misc.transform import Transform
from defcon.objects.base import BaseObject
from defcon.tools.identifiers import makeRandomIdentifier
from defcon.tools.representations import componentBoundsRepresentationFactory, componentPointBoundsRepresentationFactory
_defaultTransformation = (1, 0, 0, 1, 0, 0)
class Component(BaseObject):
"""
This object represents a reference to another glyph.
**This object posts the following notifications:**
- Component.Changed
- Component.BaseGlyphChanged
- Component.BaseGlyphDataChanged
- Component.TransformationChanged
- Component.IdentifierChanged
"""
changeNotificationName = "Component.Changed"
representationFactories = {
"defcon.component.bounds" : dict(
factory=componentBoundsRepresentationFactory,
destructiveNotifications=("Component.TransformationChanged", "Component.BaseGlyphChanged")
),
"defcon.component.controlPointBounds" : dict(
factory=componentPointBoundsRepresentationFactory,
destructiveNotifications=("Component.TransformationChanged", "Component.BaseGlyphChanged")
)
}
def __init__(self, glyph=None):
self._font = None
self._layerSet = None
self._layer = None
self._glyph = None
self.glyph = glyph
self._dirty = False
self._baseGlyph = None
self._transformation = tuple(_defaultTransformation)
self._identifier = None
super(Component, self).__init__()
self.beginSelfNotificationObservation()
# ----------
# Attributes
# ----------
# parents
def getParent(self):
return self.glyph
def _get_font(self):
font = None
if self._font is None:
glyph = self.glyph
if glyph is not None:
font = glyph.font
if font is not None:
self._font = weakref.ref(font)
else:
font = self._font()
return font
font = property(_get_font, doc="The :class:`Font` that this component belongs to.")
def _get_layerSet(self):
layerSet = None
if self._layerSet is None:
glyph = self.glyph
if glyph is not None:
layerSet = glyph.layerSet
if layerSet is not None:
self._layerSet = weakref.ref(layerSet)
else:
layerSet = self._layerSet()
return layerSet
layerSet = property(_get_layerSet, doc="The :class:`LayerSet` that this component belongs to.")
def _get_layer(self):
layer = None
if self._layer is None:
glyph = self.glyph
if glyph is not None:
layer = glyph.layer
if layer is not None:
self._layer = weakref.ref(layer)
else:
layer = self._layer()
return layer
layer = property(_get_layer, doc="The :class:`Layer` that this component belongs to.")
def _get_glyph(self):
if self._glyph is None:
return None
return self._glyph()
def _set_glyph(self, glyph):
assert self._glyph is None
if glyph is not None:
glyph = weakref.ref(glyph)
self._font = None
self._layerSet = None
self._layer = None
self._glyph = glyph
glyph = property(_get_glyph, _set_glyph, doc="The :class:`Glyph` that this component belongs to. This should not be set externally.")
# bounds
def _get_bounds(self):
return self.getRepresentation("defcon.component.bounds")
bounds = property(_get_bounds, doc="The bounds of the components's outline expressed as a tuple of form (xMin, yMin, xMax, yMax).")
def _get_controlPointBounds(self):
return self.getRepresentation("defcon.component.controlPointBounds")
controlPointBounds = property(_get_controlPointBounds, doc="The control bounds of all points in the components. This only measures the point positions, it does not measure curves. So, curves without points at the extrema will not be properly measured.")
# base glyph
def _set_baseGlyph(self, value):
newBaseGlyph = value
oldBaseGlyph = self._baseGlyph
if newBaseGlyph == oldBaseGlyph:
return
self.endSelfBaseGlyphNotificationObservation()
self._baseGlyph = newBaseGlyph
self.beginSelfBaseGlyphNotificationObservation()
self.postNotification(notification="Component.BaseGlyphChanged", data=dict(oldValue=oldBaseGlyph, newValue=newBaseGlyph))
self.dirty = True
def _get_baseGlyph(self):
return self._baseGlyph
baseGlyph = property(_get_baseGlyph, _set_baseGlyph, doc="The glyph that the components references. Setting this will post *Component.BaseGlyphChanged* and *Component.Changed* notifications.")
# transformation
def _set_transformation(self, value):
oldValue = self._transformation
if value == oldValue:
return
self._transformation = value
self.postNotification(notification="Component.TransformationChanged", data=dict(oldValue=oldValue, newValue=value))
self.dirty = True
def _get_transformation(self):
return self._transformation
transformation = property(_get_transformation, _set_transformation, doc="The transformation matrix for the component. Setting this will post *Component.TransformationChanged* and *Component.Changed* notifications.")
# -----------
# Pen Methods
# -----------
def draw(self, pen):
"""
Draw the component with **pen**.
"""
from fontTools.pens.pointPen import PointToSegmentPen
pointPen = PointToSegmentPen(pen)
self.drawPoints(pointPen)
def drawPoints(self, pointPen):
"""
Draw the component with **pointPen**.
"""
try:
pointPen.addComponent(self._baseGlyph, self._transformation, identifier=self.identifier)
except TypeError:
pointPen.addComponent(self._baseGlyph, self._transformation)
warn("The addComponent method needs an identifier kwarg. The component's identifier value has been discarded.", DeprecationWarning)
# ----
# Move
# ----
def move(self, values):
"""
Move the component by **(x, y)**.
This posts *Component.TransformationChanged* and *Component.Changed* notifications.
"""
(x, y) = values
xScale, xyScale, yxScale, yScale, xOffset, yOffset = self._transformation
xOffset += x
yOffset += y
self.transformation = (xScale, xyScale, yxScale, yScale, xOffset, yOffset)
# ------------
# Point Inside
# ------------
def pointInside(self, coordinates, evenOdd=False):
"""
Returns a boolean indicating if **(x, y)** is in the
"black" area of the component.
"""
(x, y) = coordinates
from fontTools.pens.pointInsidePen import PointInsidePen
glyph = self.glyph
if glyph is None:
return False
font = self.font
if font is None:
return False
pen = PointInsidePen(glyphSet=font, testPoint=(x, y), evenOdd=evenOdd)
self.draw(pen)
return pen.getResult()
# ----------
# Identifier
# ----------
def _get_identifiers(self):
identifiers = None
glyph = self.glyph
if glyph is not None:
identifiers = glyph.identifiers
if identifiers is None:
identifiers = set()
return identifiers
identifiers = property(_get_identifiers, doc="Set of identifiers for the glyph that this component belongs to. This is primarily for internal use.")
def _get_identifier(self):
return self._identifier
def _set_identifier(self, value):
# don't allow overwritting an existing identifier
if self._identifier is not None:
return
oldIdentifier = self.identifier
if value == oldIdentifier:
return
# don't allow a duplicate
identifiers = self.identifiers
assert value not in identifiers
# free the old identifier
if oldIdentifier in identifiers:
identifiers.remove(oldIdentifier)
# store
self._identifier = value
if value is not None:
identifiers.add(value)
# post notifications
self.postNotification("Component.IdentifierChanged", data=dict(oldValue=oldIdentifier, newValue=value))
self.dirty = True
identifier = property(_get_identifier, _set_identifier, doc="The identifier. Setting this will post *Component.IdentifierChanged* and *Component.Changed* notifications.")
def generateIdentifier(self):
"""
Create a new, unique identifier for and assign it to the contour.
This will post *Component.IdentifierChanged* and *Component.Changed* notifications.
"""
if self.identifier is None:
identifier = makeRandomIdentifier(existing=self.identifiers)
self.identifier = identifier
return self.identifier
# ------------------------
# Notification Observation
# ------------------------
def beginSelfNotificationObservation(self):
super(Component, self).beginSelfNotificationObservation()
self.beginSelfBaseGlyphNotificationObservation()
def endSelfNotificationObservation(self):
self.endSelfBaseGlyphNotificationObservation()
super(Component, self).endSelfNotificationObservation()
self._font = None
self._layerSet = None
self._layer = None
self._glyph = None
def beginSelfBaseGlyphNotificationObservation(self):
baseGlyph = self.baseGlyph
if baseGlyph is None:
return
dispatcher = self.dispatcher
if dispatcher is None:
return
layer = self.layer
# base glyph is available
if baseGlyph in layer:
self._beginBaseGlyphObservations()
# base glyph is not available
else:
self._beginLayerObservations()
def endSelfBaseGlyphNotificationObservation(self):
dispatcher = self.dispatcher
if dispatcher is None:
return
self._endBaseGlyphObservations()
self._endLayerObservations()
def _beginBaseGlyphObservations(self, baseGlyph=None):
layer = self.layer
if baseGlyph is None:
baseGlyph = layer[self.baseGlyph]
baseGlyph.addObserver(self, "baseGlyphNameChangedNotificationCallback", "Glyph.NameChanged")
baseGlyph.addObserver(self, "baseGlyphDataChangedNotificationCallback", "Glyph.ContoursChanged")
baseGlyph.addObserver(self, "baseGlyphDataChangedNotificationCallback", "Glyph.ComponentsChanged")
layer.addObserver(self, "layerGlyphWillBeDeletedNotificationCallback", "Layer.GlyphWillBeDeleted")
def _endBaseGlyphObservations(self, baseGlyph=None):
layer = self.layer
if baseGlyph is None:
baseGlyph = self.baseGlyph
if baseGlyph is None:
return
if baseGlyph in layer:
baseGlyph = layer[baseGlyph]
else:
return
if baseGlyph.hasObserver(self, "Glyph.NameChanged"):
baseGlyph.removeObserver(self, "Glyph.NameChanged")
baseGlyph.removeObserver(self, "Glyph.ContoursChanged")
baseGlyph.removeObserver(self, "Glyph.ComponentsChanged")
if layer.hasObserver(self, "Layer.GlyphWillBeDeleted"):
layer.removeObserver(self, "Layer.GlyphWillBeDeleted")
def _beginLayerObservations(self):
layer = self.layer
layer.addObserver(self, "layerGlyphNameChangedNotificationCallback", "Layer.GlyphNameChanged")
layer.addObserver(self, "layerGlyphAddedNotificationCallback", "Layer.GlyphAdded")
def _endLayerObservations(self):
layer = self.layer
if not layer.hasObserver(self, "Layer.GlyphNameChanged"):
return
layer.removeObserver(self, "Layer.GlyphNameChanged")
layer.removeObserver(self, "Layer.GlyphAdded")
def baseGlyphNameChangedNotificationCallback(self, notification):
newName = notification.data["newValue"]
layer = self.layer
notBaseGlyph = layer[newName]
self._endBaseGlyphObservations(notBaseGlyph)
self._beginLayerObservations()
def layerGlyphNameChangedNotificationCallback(self, notification):
newName = notification.data["newValue"]
baseGlyph = self.baseGlyph
if newName != baseGlyph:
return
self._endLayerObservations()
self._beginBaseGlyphObservations()
def layerGlyphWillBeDeletedNotificationCallback(self, notification):
name = notification.data["name"]
if name != self.baseGlyph:
return
self._endBaseGlyphObservations()
self._beginLayerObservations()
def layerGlyphAddedNotificationCallback(self, notification):
name = notification.data["name"]
if name != self.baseGlyph:
return
self._endLayerObservations()
self._beginBaseGlyphObservations()
def baseGlyphDataChangedNotificationCallback(self, notification):
self.postNotification("Component.BaseGlyphDataChanged")
# -----------------------------
# Serialization/Deserialization
# -----------------------------
def getDataForSerialization(self, **kwargs):
from functools import partial
simple_get = partial(getattr, self)
getters = (
('baseGlyph', simple_get),
('transformation', simple_get),
('identifier', simple_get)
)
return self._serialize(getters, **kwargs)
def setDataFromSerialization(self, data):
from functools import partial
simple_set = partial(setattr, self)
setters = (
('baseGlyph', simple_set),
('transformation', simple_set),
('identifier', simple_set)
)
for key, setter in setters:
if key not in data:
continue
setter(key, data[key])
if __name__ == "__main__":
import doctest
doctest.testmod()