Debian Codegraph @

src/babelfont/convertors/truetype.py

raw
1 import uuid
2 from datetime import datetime
3 from itertools import chain
4 from typing import Dict
5
6 from fontFeatures import Attachment
7 from fontFeatures.ttLib import unparse
8 from fontTools.fontBuilder import FontBuilder
9 from fontTools.misc.fixedTools import otRound
10 from fontTools.misc.timeTools import epoch_diff, timestampSinceEpoch
11 from fontTools.pens.recordingPen import RecordingPen
12 from fontTools.pens.ttGlyphPen import TTGlyphPen
13 from fontTools.ttLib import TTFont
14 from fontTools.ttLib.tables._g_l_y_f import GlyphCoordinates
15 from fontTools.ttLib.tables.O_S_2f_2 import Panose
16 from fontTools.ttLib.tables.TupleVariation import TupleVariation
17 from fontTools.ttLib.ttGlyphSet import _TTGlyph
18 from fontTools.varLib.iup import iup_delta_optimize
19
20 from babelfont import (
21 Anchor,
22 Axis,
23 Features,
24 Glyph,
25 Instance,
26 Layer,
27 Master,
28 Node,
29 Shape,
30 )
31 from babelfont.convertors import BaseConvertor
32 from babelfont.fontFilters.featureWriters import build_all_features
33
34
35 def _categorize_glyph(font, glyphname):
36 if "GDEF" not in font:
37 return None
38 if not font["GDEF"].table.GlyphClassDef:
39 return None
40 classdefs = font["GDEF"].table.GlyphClassDef.classDefs
41 if glyphname not in classdefs:
42 return None
43 if classdefs[glyphname] == 1:
44 return "base"
45 if classdefs[glyphname] == 2:
46 return "ligature"
47 if classdefs[glyphname] == 3:
48 return "mark"
49 if classdefs[glyphname] == 4:
50 return "component"
51
52
53 def compile_panose(data):
54 panose = Panose()
55 panose.bFamilyType = data[0]
56 panose.bSerifStyle = data[1]
57 panose.bWeight = data[2]
58 panose.bProportion = data[3]
59 panose.bContrast = data[4]
60 panose.bStrokeVariation = data[5]
61 panose.bArmStyle = data[6]
62 panose.bLetterForm = data[7]
63 panose.bMidline = data[8]
64 panose.bXHeight = data[9]
65 return panose
66
67
68 class TrueType(BaseConvertor):
69 suffix = ".ttf"
70
71 def _decompose_mixed_layer(self, layer, exportable):
72 if (layer.paths and layer.components) or any(
73 c.ref not in exportable for c in layer.components
74 ):
75 layer.decompose()
76
77 def _load(self):
78 self.tt = TTFont(self.filename)
79 self._load_fvar()
80 self._load_head()
81 self._load_masters()
82 self._load_names()
83 self._load_glyphs()
84 self._load_features()
85 return self.font
86
87 def _load_fvar(self):
88 avar = self.tt.get("avar")
89 if "fvar" in self.tt:
90 for axis in self.tt["fvar"].axes:
91 name = self.tt["name"].getDebugName(axis.axisNameID) # XXX multilingual
92 bb_axis = Axis(
93 tag=axis.axisTag,
94 min=axis.minValue,
95 max=axis.maxValue,
96 default=axis.defaultValue,
97 name=name,
98 )
99 self.font.axes.append(bb_axis)
100 if avar:
101 segs = avar.segments[axis.axisTag]
102 mapping = {
103 bb_axis.denormalize_value(k): bb_axis.denormalize_value(v)
104 for k, v in segs.items()
105 }
106 bb_axis.map = mapping
107 for instance in self.tt["fvar"].instances:
108 self.font.instances.append(
109 Instance(
110 name=self.tt["name"].getDebugName(instance.subfamilyNameID),
111 location=instance.coordinates,
112 )
113 )
114
115 def _load_masters(self):
116 m = Master(location={}, name="Default", id=str(uuid.uuid1()))
117 # Metrics
118 m.metrics = {
119 "xHeight": (
120 self.tt["OS/2"].sxHeight
121 if hasattr(self.tt["OS/2"], "sxHeight")
122 else None
123 ),
124 "capHeight": (
125 self.tt["OS/2"].sCapHeight
126 if hasattr(self.tt["OS/2"], "capHeight")
127 else None
128 ),
129 "ascender": self.tt["hhea"].ascender,
130 "descender": self.tt["hhea"].descender,
131 }
132 m.font = self.font
133 self.font.masters = [m]
134 if "fvar" in self.tt:
135 m.location = {axis.tag: axis.default for axis in self.font.axes}
136 all_masters = [
137 frozenset(x.axes.items())
138 for x in chain(*self.tt["gvar"].variations.values())
139 ]
140 all_masters = [{k: v[1] for k, v in dict(m1).items()} for m1 in all_masters]
141 # Now denormalize.
142 # XXX
143 pass
144
145 def _load_head(self):
146 head = self.tt["head"]
147 self.font.upm = head.unitsPerEm
148 minor = head.fontRevision % 1
149 while minor - int(minor) > 1e-4:
150 minor *= 10
151 self.font.version = (int(head.fontRevision), int(minor))
152 self.font.date = datetime.fromtimestamp(self.tt["head"].created + epoch_diff)
153
154 def _load_names(self):
155 names = self.tt["name"]
156 # XXX
157
158 def _load_glyphs(self):
159 mapping = self.tt["cmap"].buildReversed()
160 glyphs_dict = {}
161 for glyph in self.tt.getGlyphOrder():
162 category = _categorize_glyph(self.tt, glyph) or "base"
163 glyphs_dict[glyph] = Glyph(
164 name=glyph, codepoints=list(mapping.get(glyph, [])), category=category
165 )
166 self.font.glyphs.append(glyphs_dict[glyph])
167 glyphs_dict[glyph].layers = self._load_layers(glyph, glyphs_dict[glyph])
168 return glyphs_dict
169
170 def _load_layers(self, glyphname, glyph):
171 ttglyph = self.tt.getGlyphSet()[glyphname] # _TTGlyphGlyf object
172 width = self.tt["hmtx"][glyphname][0]
173 # leftMargin = self.tt["hmtx"][g][1]
174 layer = Layer(width=width, id=str(uuid.uuid1()))
175 layer._master = self.font.masters[0].id
176 layer._font = self.font
177 layer._glyph = glyph
178 ttglyph.draw(layer.getPen())
179 return [layer]
180
181 SAVE_FILTERS = [
182 "renameGlyphs:production=True",
183 "decomposeMixedGlyphs",
184 "dropUnexportedGlyphs",
185 "zeroMarkWidths",
186 "cubicToQuadratic",
187 "fillOpentypeValues",
188 ]
189
190 def _save(self):
191 f = self.font
192 fb = FontBuilder(f.upm, isTTF=True)
193 fb.setupGlyphOrder(list(f.glyphs.keys()))
194 fb.setupCharacterMap(f.unicode_map)
195
196 metrics = {}
197 for g in f.glyphs.keys():
198 layer = f.default_master.get_glyph_layer(g)
199 metrics[g] = (layer.width or 0, layer.lsb or 0)
200
201 fb.setupHorizontalMetrics(metrics)
202
203 ttglyphsets: Dict[str, Dict[str, _TTGlyph]] = {m.id: {} for m in f.masters}
204 # We need to do this in order of single components first
205 done = set()
206
207 def convert_glyph(g):
208 if g in done:
209 return
210 for m in f.masters:
211 layer = m.get_glyph_layer(g)
212 if layer:
213 for c in layer.components:
214 convert_glyph(c.ref)
215 pen = TTGlyphPen(ttglyphsets[m.id])
216 layer.draw(pen)
217
218 ttglyphsets[m.id][g] = pen.glyph()
219 done.add(g)
220
221 for g in f.glyphs.keys():
222 convert_glyph(g)
223
224 try:
225 fb.setupGlyf(ttglyphsets[f.default_master.id])
226 except ValueError:
227 fb.font["head"].glyphDataFormat = 1
228 self.logger.warning(
229 "Using Boring Expansion, eh? Setting glyf data format to 1"
230 )
231 fb.setupGlyf(ttglyphsets[f.default_master.id])
232 fb.setupHorizontalHeader()
233 f.names.typographicSubfamily = f.default_master.name
234 f.names.typographicFamily = f.names.familyName
235 fb.setupNameTable(f.names.as_nametable_dict(), mac=False)
236 fb.setupOS2()
237
238 if f.axes:
239 model = f.variation_model()
240 axis_map = {}
241 variations = {}
242 self.logger.info("Calculating gvar table")
243 for g in f.glyphs.keys():
244 variations[g] = self.calculate_a_gvar(f, model, g, ttglyphsets)
245
246 for ax in f.axes:
247 ax.name = ax.name.as_fonttools_dict
248 axis_map[ax.tag] = ax
249 for instance in f.instances:
250 instance.location = {
251 k: axis_map[k].map_backward(v) for k, v in instance.location.items()
252 }
253 fb.setupFvar(f.axes, f.instances)
254
255 fb.setupGvar(variations)
256 fb.setupAvar(f.axes)
257 build_all_features(f, fb.font)
258 fb.setupPost()
259 # Set OS/2 version to 4 for ufo2ft compatibility
260 fb.font["OS/2"].version = 4
261 fb.font["maxp"].maxZones = 1
262
263 for (table, field), value in f.custom_opentype_values.items():
264 if field == "panose":
265 value = compile_panose(value)
266 setattr(fb.font[table], field, value)
267 self.logger.debug("Setting %s.%s to %s", table, field, value)
268 fb.font.save(self.filename)
269
270 def calculate_a_gvar(
271 self, f, model, g, ttglyphsets: Dict[str, Dict[str, _TTGlyph]]
272 ):
273 if g not in ttglyphsets[f.default_master.id]:
274 return None
275 default_g = ttglyphsets[f.default_master.id][g]
276 all_coords = []
277 layers = [m.get_glyph_layer(g) for m in f.masters]
278 submodel, _ = model.getSubModel(layers)
279 for m in f.masters:
280 layer = m.get_glyph_layer(g)
281 if not layer:
282 continue
283 masterglyph = ttglyphsets[m.id][g]
284 basecoords = GlyphCoordinates(masterglyph.coordinates)
285 if masterglyph.isComposite():
286 component_point = GlyphCoordinates(
287 [
288 (otRound(layer_comp.pos[0]), otRound(layer_comp.pos[1]))
289 for layer_comp in layer.components
290 ]
291 )
292 basecoords.extend(component_point)
293 phantomcoords = GlyphCoordinates(
294 [(0, 0), (otRound(layer.width), 0), (0, 0), (0, 0)]
295 )
296 basecoords.extend(phantomcoords)
297 all_coords.append(basecoords)
298 for ix, c in enumerate(all_coords):
299 all_ok = True
300 if len(c) != len(all_coords[0]):
301 print("Incompatible master %i in glyph %s" % (ix, g))
302 all_ok = False
303 if not all_ok:
304 return []
305 deltas = submodel.getDeltas(all_coords)
306 gvar_entry = []
307 if default_g.isComposite():
308 endPts = list(range(len(default_g.components)))
309 else:
310 endPts = default_g.endPtsOfContours
311
312 for delta, sup in zip(deltas, submodel.supports):
313 if not sup:
314 continue
315 var = TupleVariation(sup, round(delta))
316 # This assumes we do the default master first, which may not be true
317 delta_opt = iup_delta_optimize(
318 round(delta), round(deltas[0]), endPts, tolerance=0.5
319 )
320 if None in delta_opt:
321 var = TupleVariation(sup, delta_opt)
322 gvar_entry.append(var)
323 return gvar_entry
324
325 def _load_features(self):
326 features = unparse(self.tt)
327 # Load anchors
328 for routine in features.routines:
329 for rule in routine.rules:
330 if isinstance(rule, Attachment):
331 for glyphname, pos in rule.bases.items():
332 self._add_anchor(glyphname, pos, rule.base_name)
333 for glyphname, pos in rule.marks.items():
334 self._add_anchor(glyphname, pos, rule.mark_name)
335
336 self.font.features = Features()
337 for feature, routines in features.features.items():
338 self.font.features.features.append(
339 (str(feature), "\n".join(x.asFea() for x in routines))
340 )
341 for routine in features.routines:
342 self.font.features.prefixes[routine.name] = routine.asFea()
343 self.font.features.classes = features.namedClasses
344
345 def _add_anchor(self, glyphname, pos, name):
346 # Would be nice if this was variable.
347 layer = self.font.default_master.get_glyph_layer(glyphname)
348 layer.anchors.append(Anchor(name=name, x=pos[0], y=pos[1]))
349
350 # import numpy as np
351 # def calculate_a_gvar(self, f, model, g, default_width):
352 # if not g in f.default_master.ttglyphset._glyphs:
353 # return None
354
355 # all_coords = []
356 # master_ix = f.masters.index(f.default_master)
357
358 # for m in f.masters:
359 # coords = list(m.ttglyphset._glyphs[g].coordinates)
360 # layer = m.get_glyph_layer(g)
361 # if m.ttglyphset._glyphs[g].isComposite():
362 # coords.extend([c.pos for c in layer.components])
363 # coords.extend( [ (0,0), (layer.width,0), (0,0), (0,0) ] )
364 # all_coords.append(np.array(coords))
365 # stacked = np.array(all_coords)
366 # defaults = stacked[np.newaxis,master_ix,:,:].repeat(len(f.masters),axis=0)
367 # base_deltas = stacked-defaults
368 # x_deltas = np.apply_along_axis(model.getDeltas, 1, base_deltas[:,:,0].transpose())
369 # y_deltas = np.apply_along_axis(model.getDeltas, 1, base_deltas[:,:,1].transpose())
370 # alldeltas = np.array([x_deltas, y_deltas]).transpose()
371 # gvar_entry = []
372 # for deltaset, sup in zip(alldeltas, model.supports):
373 # gvar_entry.append(TupleVariation(sup, list(map(tuple, deltaset))))
374 # return gvar_entry
375
376
377 class OpenType(TrueType):
378 suffix = ".otf"
379
380 def _load_layers(self, g, _glyph):
381 ttglyph = self.tt.getGlyphSet()[g]
382 width = self.tt["hmtx"][g][0]
383 layer = Layer(width=width, id=self.font.masters[0].id)
384 layer._master = self.font.masters[0].id
385 layer._font = self.font
386 pen = RecordingPen()
387 ttglyph.draw(pen)
388 contours = pen.value
389 lastcontour = []
390 startPt = (0, 0)
391 lastPt = (0, 0)
392 index = 0
393 for operation, segment in contours:
394 if operation == "moveTo":
395 startPt = segment[0]
396 elif operation == "closePath":
397 if startPt != lastPt:
398 lastcontour.append(Node(x=startPt[0], y=startPt[1], type="l"))
399 contour = Shape()
400 contour.nodes = lastcontour
401 layer.shapes.append(contour)
402 lastcontour = []
403 elif operation == "curveTo":
404 lastcontour.append(Node(x=segment[0][0], y=segment[0][1], type="o"))
405 lastcontour.append(Node(x=segment[1][0], y=segment[1][1], type="o"))
406 lastcontour.append(Node(x=segment[2][0], y=segment[2][1], type="c"))
407 lastPt = segment[2]
408 elif operation == "lineTo":
409 lastcontour.append(Node(x=segment[0][0], y=segment[0][1], type="l"))
410 lastPt = segment[0]
411 elif operation == "qCurveTo":
412 lastcontour.append(Node(x=segment[0][0], y=segment[0][1], type="o"))
413 lastcontour.append(Node(x=segment[1][0], y=segment[1][1], type="q"))
414
415 return [layer]