Debian Codegraph @

src/babelfont/convertors/gsobject.py

raw
1 from fontFeatures.feaLib import FeaParser
2 from babelfont.convertors import BaseConvertor
3 from babelfont import (
4 Master,
5 Glyph,
6 Layer,
7 Guide,
8 Anchor,
9 Shape,
10 Node,
11 Axis,
12 Instance,
13 )
14 import uuid
15
16
17 opentype_custom_parameters = {
18 "typoAscender": ("OS/2", "sTypoAscender"),
19 "typoDescender": ("OS/2", "sTypoDescender"),
20 "typoLineGap": ("OS/2", "sTypoLineGap"),
21 "winAscent": ("OS/2", "usWinAscent"),
22 "winDescent": ("OS/2", "usWinDescent"),
23 "hheaAscender": ("hhea", "ascent"),
24 "hheaDescender": ("hhea", "descent"),
25 "hheaLineGap": ("hhea", "lineGap"),
26 "underlinePosition": ("post", "underlinePosition"),
27 "underlineThickness": ("post", "underlineThickness"),
28 }
29
30 _rename_metrics = {"x-height": "xHeight", "cap height": "capHeight"}
31 _reverse_rename_metrics = {v: k for k, v in _rename_metrics.items()}
32
33
34 def _glyphs_metrics_to_ours(k):
35 return _rename_metrics.get(k, k)
36
37
38 def _our_metrics_to_glyphs(k):
39 return _reverse_rename_metrics.get(k, k)
40
41
42 class GSObject(BaseConvertor):
43 @classmethod
44 def can_load(cls, convertor):
45 return "gsfont" in convertor.scratch
46
47 def _load(self):
48 self.gsfont = self.scratch["gsfont"]
49 self.customParameters = {}
50 for param in self.gsfont.customParameters:
51 self.customParameters[param.name] = param.value
52 self._load_axes()
53 self._load_kern_groups(self.gsfont.glyphs)
54
55 for gmaster in self.gsfont.masters:
56 self.font.masters.append(self._load_master(gmaster))
57 self._fixup_axes()
58
59 for gglyph in self.gsfont.glyphs:
60 g = self._load_glyph(gglyph)
61 self.font.glyphs.append(g)
62
63 for ginstance in self.gsfont.instances:
64 self.font.instances.append(self._load_instance(ginstance))
65
66 self._fixup_axis_mappings()
67
68 self._load_metadata()
69 self._load_features()
70 return self.font
71
72 def _fixup_axes(self):
73 for master in self.font.masters:
74 for axis in self.font.axes:
75 thisLoc = master.location[axis.tag]
76 if axis.min is None or thisLoc < axis.min:
77 axis.min = thisLoc
78 if master.id == self._default_master_id():
79 axis.default = master.location[axis.tag]
80 if axis.max is None or thisLoc > axis.max:
81 axis.max = thisLoc
82
83 def _fixup_axis_mappings(self):
84 for axis in self.font.axes:
85 if not axis.map:
86 continue
87 axis.map = list(sorted(set(axis.map)))
88 axis.min, axis.max, axis.default = (
89 axis.map_backward(axis.min),
90 axis.map_backward(axis.max),
91 axis.map_backward(axis.default),
92 )
93
94 def _custom_parameter(self, thing, name):
95 for param in thing.customParameters or []:
96 if param.name == name:
97 return param.value
98 return None
99
100 def _default_master_id(self):
101 # The default master in glyphs is either the first master or the
102 # one selected by the Variable Font Origin custom parameter
103 return (
104 self._custom_parameter(self.gsfont, "Variable Font Origin")
105 or self.gsfont.masters[0].id
106 )
107
108 def _load_axes(self):
109 self.axis_name_map = {}
110 for gaxis in self.gsfont.axes:
111 axis = Axis(name=gaxis.name, tag=gaxis.axisTag)
112 self.axis_name_map[gaxis.name] = axis
113 _maybesetformatspecific(axis, gaxis, "hidden")
114 self.font.axes.append(axis)
115
116 def _load_master(self, gmaster):
117 location = gmaster.axes
118 metrics = self.gsfont.metrics()
119 master = Master(name=gmaster.name, id=gmaster.id, font=self.font)
120 metric_types = [m.name or m.typeName() for m in metrics]
121 for k, v in zip(metric_types, gmaster.metrics()):
122 master.metrics[_glyphs_metrics_to_ours(k)] = v.position
123 if v.overshoot:
124 master.metrics["%s overshoot" % _glyphs_metrics_to_ours(k)] = (
125 v.overshoot
126 )
127
128 master.location = {k.tag: v for k, v in zip(self.font.axes, location)}
129 master.guides = [self._load_guide(x) for x in gmaster.guides]
130 kerntable = self.gsfont.kerning.get(master.id, {})
131 master.kerning = self._load_kerning(kerntable)
132 # XXX support RTL kerning etc.
133
134 # _maybesetformatspecific(master, gmaster, "customParameters") # XXX
135 _maybesetformatspecific(master, gmaster, "iconName")
136 _maybesetformatspecific(master, gmaster, "numberValues")
137 _maybesetformatspecific(master, gmaster, "stemValues")
138 _maybesetformatspecific(master, gmaster, "properties")
139 _maybesetformatspecific(master, gmaster, "userData")
140 _maybesetformatspecific(master, gmaster, "visible")
141 assert master.valid
142 return master
143
144 def _get_codepoint(self, gglyph):
145 if gglyph.unicodes:
146 return [int(x, 16) for x in gglyph.unicodes]
147 return []
148
149 def _load_glyph(self, gglyph):
150 name = gglyph.name
151 c = gglyph.category
152 sc = gglyph.subCategory
153 if sc == "Ligature":
154 category = "ligature"
155 if c == "Mark":
156 category = "mark"
157 else:
158 category = "base"
159 cp = self._get_codepoint(gglyph)
160 g = Glyph(
161 name=name,
162 codepoints=cp,
163 category=category,
164 exported=gglyph.export,
165 )
166 g.production_name = gglyph.productionName
167 for entry in [
168 "case",
169 "category",
170 "subCategory",
171 "color",
172 "direction",
173 "locked",
174 "partsSettings",
175 "script",
176 "tags",
177 ]:
178 _maybesetformatspecific(g, gglyph, entry)
179
180 for layer in gglyph.layers:
181 g.layers.extend(self._load_layer(layer))
182
183 return g
184
185 def _load_layer(self, layer, width=None):
186 if width is None:
187 width = layer.width
188 l = Layer(width=width, id=str(layer.layerId), _font=self.font)
189 l.name = layer.name
190 if [x for x in self.font.masters if x.id == l.id]:
191 l._master = l.id
192 else:
193 l._master = layer.associatedMasterId
194 l.guides = [self._load_guide(x) for x in layer.guides]
195 l.shapes = []
196 for shape in layer.shapes:
197 l.shapes.append(self._load_shape(shape))
198 for anchor in layer.anchors:
199 l.anchors.append(self._load_anchor(anchor))
200
201 _maybesetformatspecific(l, layer, "hints")
202 _maybesetformatspecific(l, layer, "partSelection")
203 _maybesetformatspecific(l, layer, "visible")
204 _maybesetformatspecific(l, layer, "attr")
205 returns = [l]
206 if "Background" not in str(type(layer)) and layer.background:
207 (background,) = self._load_layer(layer.background, width=l.width)
208 # If it doesn't have an ID, we need to generate one
209 background.id = str(uuid.uuid1())
210 # XXX
211 # For some INSANE REASON orjson is serializing this to `True` in json,
212 # not `true`.
213 # background.isBackground = True
214 del background._master
215
216 l.background = background.id
217 returns.append(background)
218 # TODO backgroundImage, metricTop/Bottom/etc, vertOrigin, vertWidth.
219 for r in returns:
220 assert r.valid
221 return returns
222
223 def _load_guide(self, gguide):
224 pos = gguide.position
225 return Guide(pos=[int(pos[0]), int(pos[1]), int(gguide.angle)])
226
227 def _load_anchor(self, ganchor):
228 pos = ganchor.position
229 return Anchor(name=ganchor.name, x=float(pos[0]), y=float(pos[1]))
230
231 def _load_instance(self, ginstance):
232 if ginstance.axes:
233 location = ginstance.axes
234 instance_location = {k.tag: v for k, v in zip(self.font.axes, location)}
235 elif ginstance.instanceInterpolations:
236 # All right then.
237 instance_location = {k.tag: 0 for k in self.font.axes}
238 for mId, factor in ginstance.instanceInterpolations.items():
239 master_loc = self.font.master(mId).location
240 for k in self.font.axes:
241 instance_location[k.tag] += master_loc[k.tag] * factor
242 else:
243 raise ValueError("Need to Synthesize location")
244 i = Instance(
245 name=ginstance.name,
246 styleName=ginstance.name,
247 location=instance_location,
248 )
249 c = self._custom_parameter(ginstance, "Axis Location") or []
250 for loc in c:
251 ax = self.axis_name_map[loc["Axis"]]
252 if not ax.map:
253 ax.map = []
254 ax.map.append(
255 (
256 int(loc["Location"]),
257 instance_location[ax.tag],
258 )
259 )
260
261 # _maybesetformatspecific(i, ginstance, "customParameters") # XXX
262 return i
263
264 def _load_component(self, shape):
265 glyphname = shape.componentName
266 transform = shape.transform
267 c = Shape(ref=glyphname)
268 c.transform = transform
269 for entry in [
270 "alignment",
271 "anchorTo",
272 "attr",
273 "locked",
274 "orientation",
275 "piece",
276 "userData",
277 ]:
278 _maybesetformatspecific(c, shape, entry)
279 return c
280
281 def _load_kerning(self, kerndict):
282 return {
283 (l, r): value
284 for l, level2 in kerndict.items()
285 for r, value in level2.items()
286 }
287
288 def _load_metadata(self):
289 self.font.upm = self.gsfont.upm
290 self.font.version = (self.gsfont.versionMajor, self.gsfont.versionMinor)
291 self.font.names.familyName.set_default(self.gsfont.familyName)
292
293 # This is very glyphs 3
294 props = {}
295 for prop in self.gsfont.properties:
296 if hasattr(prop, "value"):
297 props[prop.key] = prop.value
298 else:
299 props[prop.key] = {p.languageTag: p.value for p in prop.values}
300
301 if props:
302 interestingProps = {
303 "copyrights": "copyright",
304 "designer": "designer",
305 "designerURL": "designerURL",
306 } # Etc
307 for glyphsname, attrname in interestingProps.items():
308 thing = props.get(glyphsname, "")
309 if hasattr(thing, dict):
310 getattr(self.font.names, attrname).copy_in(thing)
311 else:
312 getattr(self.font.names, attrname).set_default(thing)
313 # Do other properties here
314
315 # Any customparameters in the default master which look like
316 # custom OT values need to move there.
317 cp = self.font.default_master._formatspecific.get("com.glyphsapp", {}).get(
318 "customParameters", {}
319 )
320 for param in cp:
321 ot_param = opentype_custom_parameters.get(param.name)
322 if not ot_param:
323 continue
324 self.font.custom_opentype_values[ot_param] = param.value
325
326 self.font.note = self.gsfont.note
327 self.font.date = self.gsfont.date
328
329 _maybesetformatspecific(self.font, self.gsfont, ".appVersion")
330 _maybesetformatspecific(self.font, self.gsfont, ".formatVersion")
331 _maybesetformatspecific(self.font, self.gsfont, "DisplayStrings")
332 _maybesetformatspecific(self.font, self.gsfont, "customParameters")
333 _maybesetformatspecific(self.font, self.gsfont, "settings")
334 _maybesetformatspecific(self.font, self.gsfont, "numbers")
335 _maybesetformatspecific(self.font, self.gsfont, "stems")
336 _maybesetformatspecific(self.font, self.gsfont, "userData")
337 _maybesetformatspecific(self.font, self.gsfont, "metrics")
338
339 def _load_features(self):
340 for c in self.gsfont.classes:
341 self.font.features.namedClasses[c.name] = tuple(c.code.split())
342
343 featurefile = ""
344 for f in self.gsfont.featurePrefixes:
345 featurefile = featurefile + f.code
346 for f in self.gsfont.features:
347 tag = f.name
348 feacode = "feature %s { %s\n} %s;" % (tag, f.code, tag)
349 featurefile = featurefile + feacode
350
351 try:
352 glyphNames = {g.name for g in self.font.glyphs}
353 feaparser = FeaParser(featurefile, glyphNames=glyphNames)
354 ast = feaparser.parser.ast
355 for name, members in self.font.features.namedClasses.items():
356 glyphclass = ast.GlyphClassDefinition(
357 name, ast.GlyphClass([m for m in members])
358 )
359 feaparser.parser.glyphclasses_.define(name, glyphclass)
360 feaparser.parse()
361 except Exception:
362 pass
363
364 def _load_shape(self, shape):
365 if hasattr(shape, "nodes"): # It's a path
366 return self._load_path(shape)
367 else:
368 return self._load_component(shape)
369
370 def _load_path(self, path):
371 shape = Shape()
372 shape.nodes = [Node(n.position.x, n.position.y, n.type[0]) for n in path.nodes]
373 shape.closed = path.closed
374 return shape
375
376 def _load_kern_groups(self, glyphs):
377 kerngroups = {}
378 for g in glyphs:
379 if g.leftKerningGroup:
380 kerngroups.setdefault("MMK_L_" + g.leftKerningGroup, []).append(g.name)
381 if g.rightKerningGroup:
382 kerngroups.setdefault("MMK_R_" + g.rightKerningGroup, []).append(g.name)
383 for k, v in kerngroups.items():
384 self.font.features.namedClasses[k] = tuple(v)
385
386
387 def _maybesetformatspecific(item, glyphs, key):
388 if hasattr(glyphs, key):
389 if "com.glyphsapp" not in item._formatspecific:
390 item._formatspecific["com.glyphsapp"] = {}
391 value = getattr(glyphs, key) # XXX
392 try:
393 orjson.dumps(value)
394 item._formatspecific["com.glyphsapp"][key] = value
395 except Exception:
396 print("%s.%s cannot be serialized!" % (glyphs, key))
397
398
399 def _moveformatspecific(item):
400 rv = {}
401 if "com.glyphsapp" in item._formatspecific:
402 rv = {**item._formatspecific.get("com.glyphsapp", {})}
403 return rv
404
405
406 def _copyattrs(src, dst, attrs):
407 for a in attrs:
408 v = getattr(src, a)
409 if isinstance(v, I18NDictionary):
410 v = v.get_default()
411 if v:
412 dst[a] = v