Debian Codegraph @

src/babelfont/convertors/designspace.py

raw
1 import logging
2 from typing import Dict, List
3 import time
4 import uuid
5
6 import ufoLib2
7 from fontTools import designspaceLib
8 from fontTools.designspaceLib import DesignSpaceDocument
9 from fontTools.misc import timeTools
10
11 from babelfont import (
12 Features,
13 Font,
14 Master,
15 Instance,
16 Glyph,
17 Layer,
18 Shape,
19 Node,
20 Anchor,
21 Guide,
22 Axis,
23 I18NDictionary,
24 )
25 from babelfont.convertors import BaseConvertor
26
27 log = logging.getLogger(__name__)
28
29 UFO_KEY = "org.unifiedfontobject"
30
31 metrics = {
32 "xHeight": "xHeight",
33 "capHeight": "capHeight",
34 "ascender": "ascender",
35 "descender": "descender",
36 "italicAngle": "italicAngle",
37 "hheaAscender": "openTypeHheaAscender",
38 "hheaDescender": "openTypeHheaDescender",
39 "hheaLineGap": "openTypeHheaLineGap",
40 "winAscent": "openTypeOS2WinAscent",
41 "winDescent": "openTypeOS2WinDescent",
42 "typoAscender": "openTypeOS2TypoAscender",
43 "typoDescender": "openTypeOS2TypoDescender",
44 "typoLineGap": "openTypeOS2TypoLineGap",
45 "subscriptXSize": "openTypeOS2SubscriptXSize",
46 "subscriptYSize": "openTypeOS2SubscriptYSize",
47 "subscriptXOffset": "openTypeOS2SubscriptXOffset",
48 "subscriptYOffset": "openTypeOS2SubscriptYOffset",
49 "superscriptXSize": "openTypeOS2SuperscriptXSize",
50 "superscriptYSize": "openTypeOS2SuperscriptYSize",
51 "superscriptXOffset": "openTypeOS2SuperscriptXOffset",
52 "superscriptYOffset": "openTypeOS2SuperscriptYOffset",
53 "strikeoutSize": "openTypeOS2StrikeoutSize",
54 "strikeoutPosition": "openTypeOS2StrikeoutPosition",
55 "underlinePosition": "postscriptUnderlinePosition",
56 "underlineThickness": "postscriptUnderlineThickness",
57 "hheaCaretSlopeRise": "openTypeHheaCaretSlopeRise",
58 "hheaCaretSlopeRun": "openTypeHheaCaretSlopeRun",
59 "hheaCaretOffset": "openTypeHheaCaretOffset",
60 }
61
62 # Unicode ranges / code page ranges are special
63
64 ufo_custom_opentype_values = {
65 "openTypeGaspRangeRecords": ("GASP", "gaspRange"),
66 # XX more gasp here
67 "openTypeHeadCreated": ("head", "created"),
68 "openTypeHeadLowestRecPPEM": ("head", "lowestRecPPEM"),
69 "openTypeHeadFlags": ("head", "flags"),
70 "openTypeOS2WidthClass": ("OS/2", "usWidthClass"),
71 "openTypeOS2WeightClass": ("OS/2", "usWeightClass"),
72 "openTypeOS2Selection": ("OS/2", "fsSelection"),
73 "openTypeOS2VendorID": ("OS/2", "achVendID"),
74 "openTypeOS2Panose": ("OS/2", "bPanose"),
75 "openTypeOS2FamilyClass": ("OS/2", "sFamilyClass"),
76 "openTypeOS2Type": ("OS/2", "fsType"),
77 }
78
79 BITARRAY = [
80 ("head", "flags"),
81 ("GASP", "gaspRange"),
82 ("OS/2", "fsType"),
83 ("OS/2", "fsSelection"),
84 ]
85
86
87 def bitarray_to_int(value):
88 return sum(2**i for i in value)
89
90
91 def int_to_bitarray(value):
92 return [i for i in range(32) if value & 2**i]
93
94
95 def ribbi(style: str) -> bool:
96 return style.lower() in ["regular", "italic", "bold", "bold italic"]
97
98
99 class Designspace(BaseConvertor):
100 suffix = ".designspace"
101
102 @classmethod
103 def load(cls, convertor, compile_only=False):
104 self = cls()
105 self.ds = DesignSpaceDocument.fromfile(convertor.filename)
106 self.ds.loadSourceFonts(ufoLib2.Font.open)
107 self.font = Font()
108 return self._load()
109
110 def _load(self):
111 self._load_axes()
112
113 for source in self.ds.sources:
114 source._babelfont_master = self._load_master(source)
115 self.font.masters.append(source._babelfont_master)
116
117 for instance in self.ds.instances:
118 self.font.instances.append(self._load_instance(instance))
119
120 firstmaster = self.ds.sources[0].font
121 self._load_metadata(firstmaster)
122 glyphs_dict = self._load_glyphs(firstmaster)
123
124 # Right, let's find all the layers. This will be messy.
125 for source in self.ds.sources:
126 for ufo_layer in source.font.layers:
127 for g in source.font.keys():
128 if g not in glyphs_dict:
129 log.warning(
130 "Incompatible glyph set: %s appears in %s but is not in default",
131 g,
132 source.filename,
133 )
134 continue
135 if g not in ufo_layer:
136 continue
137 glyphs_dict[g].layers.append(self._load_layer(source, ufo_layer, g))
138 self._fixup_glyph_exported(self.ds.sources[0].font)
139 return self.font
140
141 def _fixup_glyph_exported(self, ufo: ufoLib2.Font):
142 for glyph in ufo.lib.get("public.skipExportGlyphs", []):
143 self.font.glyphs[glyph].exported = False
144
145 def _load_glyphs(self, master: ufoLib2.Font):
146 glyphs_dict = {}
147 # Start with glyph order if there is one
148 order = master.lib.get("public.glyphOrder", [])
149 # Then add any remaining glyphs
150 order += [g for g in master.keys() if g not in order]
151 for g in order:
152 glyphs_dict[g] = self._load_glyph(master[g])
153 self.font.glyphs.append(glyphs_dict[g])
154 return glyphs_dict
155
156 def _load_axes(self):
157 for a in self.ds.axes:
158 self.font.axes.append(
159 Axis(
160 name=a.name,
161 tag=a.tag,
162 min=a.minimum,
163 max=a.maximum,
164 default=a.default,
165 map=a.map,
166 )
167 )
168
169 def _load_master(self, source: designspaceLib.SourceDescriptor):
170 font: ufoLib2.Font = source.font
171 i = font.info
172 master = Master(
173 name=source.name,
174 id=(source.name or uuid.uuid1()),
175 )
176 for our_metric, their_metric in metrics.items():
177 master.metrics[our_metric] = getattr(i, their_metric)
178 _axis_name_to_id = {a.name.get_default(): a.tag for a in self.font.axes}
179 # names XXX
180 # guidelines
181 master.guides = [self._load_guide(g) for g in (i.guidelines or [])]
182 master.location = {_axis_name_to_id[k]: v for k, v in source.location.items()}
183 master.font = self.font
184 master.kerning = self._load_kerning(source)
185 for key, value in font.lib.items():
186 if not key.startswith("public."):
187 if UFO_KEY not in master._formatspecific:
188 master._formatspecific[UFO_KEY] = {}
189 master._formatspecific[UFO_KEY][key] = value
190 assert master.valid
191 return master
192
193 def _load_groups(self, groups: Dict[str, List[str]]):
194 for name, value in groups.items():
195 self.font.features.classes[name] = value
196
197 def _load_guide(self, ufo_guide: ufoLib2.objects.Guideline):
198 return Guide(
199 pos=[ufo_guide.x, ufo_guide.y, ufo_guide.angle],
200 name=ufo_guide.name,
201 color=ufo_guide.color,
202 )
203
204 def _load_kerning(self, source: designspaceLib.SourceDescriptor):
205 font: ufoLib2.Font = source.font
206 kerning = {}
207 for (left, right), value in font.kerning.items():
208 if left.startswith("public.kern"):
209 left = "@" + left
210 if right.startswith("public.kern"):
211 right = "@" + right
212 kerning[(left, right)] = value
213 return kerning
214
215 def _load_glyph(self, ufo_glyph: ufoLib2.objects.Glyph):
216 cp = []
217 if ufo_glyph.unicodes or ufo_glyph.unicode:
218 cp = ufo_glyph.unicodes or [ufo_glyph.unicode]
219 lib = self.ds.sources[0].font.lib
220 category = lib.get("public.openTypeCategories", {}).get(ufo_glyph.name, "base")
221 g = Glyph(name=ufo_glyph.name, codepoints=cp, category=category)
222
223 if "public.postscriptNames" in lib and g.name in lib["public.postscriptNames"]:
224 g.production_name = lib["public.postscriptNames"][g.name]
225 return g
226
227 def _load_layer(
228 self, source: designspaceLib.SourceDescriptor, ufo_layer, glyphname: str
229 ):
230 if ufo_layer.name == "public.default":
231 layer_id = source._babelfont_master.id
232 else:
233 layer_id = ufo_layer.name
234 ufo_glyph = ufo_layer[glyphname]
235 width = ufo_glyph.width
236 layer = Layer(width=width, id=layer_id)
237 layer._master = source._babelfont_master.id
238 layer._font = self.font
239 layer._glyph = self.font.glyphs[glyphname]
240 for contour in ufo_glyph:
241 layer.shapes.append(self._load_contour(contour))
242 for component in ufo_glyph.components:
243 layer.shapes.append(self._load_component(component))
244 for anchor in ufo_glyph.anchors:
245 layer.anchors.append(self._load_anchor(anchor))
246 assert layer.valid
247 return layer
248
249 def _load_component(self, shape: ufoLib2.objects.Component):
250 c = Shape(ref=shape.baseGlyph, transform=shape.transformation)
251 return c
252
253 def _load_anchor(self, anchor: ufoLib2.objects.Anchor):
254 return Anchor(name=anchor.name, x=int(anchor.x), y=int(anchor.y))
255
256 def _load_contour(self, contour):
257 shape = Shape()
258 shape.nodes = []
259 for p in contour:
260 segtype = p.segmentType
261 if p.segmentType == "move":
262 segtype = "line"
263 ourtype = Node._from_pen_type[segtype]
264 if p.smooth:
265 ourtype = ourtype + "s"
266 shape.nodes.append(Node(p.x, p.y, ourtype))
267 return shape
268
269 def _load_instance(self, ufo_instance):
270 _axis_tag = {axis.name.get_default(): axis.tag for axis in self.font.axes}
271 location = {_axis_tag[k]: v for k, v in ufo_instance.location.items()}
272 instance = Instance(name=ufo_instance.name, location=location)
273 return instance
274
275 names_dict = {
276 "designer": "openTypeNameDesigner",
277 "designerURL": "openTypeNameDesignerURL",
278 "manufacturer": "openTypeNameManufacturer",
279 "manufacturerURL": "openTypeNameManufacturerURL",
280 "license": "openTypeNameLicense",
281 "licenseURL": "openTypeNameLicenseURL",
282 "version": "openTypeNameVersion",
283 "uniqueID": "openTypeNameUniqueID",
284 "description": "openTypeNameDescription",
285 "compatibleFullName": "openTypeNameCompatibleFullName",
286 "sampleText": "openTypeNameSampleText",
287 "WWSFamilyName": "openTypeNameWWSFamilyName",
288 "WWSSubfamilyName": "openTypeNameWWSSubfamilyName",
289 "copyright": "copyright",
290 "styleMapFamilyName": "styleMapFamilyName",
291 "familyName": "familyName",
292 "trademark": "trademark",
293 "styleName": "styleName",
294 "styleMapStyleName": "styleMapStyleName",
295 "preferredSubfamilyName": "openTypeNamePreferredSubfamilyName",
296 }
297
298 def _load_metadata(self, ufo):
299 firstfontinfo = ufo.info
300 self.font.upm = firstfontinfo.unitsPerEm
301 self.font.version = (firstfontinfo.versionMajor, firstfontinfo.versionMinor)
302 self.font.note = firstfontinfo.note
303 for ours, theirs in self.names_dict.items():
304 their_value = getattr(firstfontinfo, theirs)
305 if their_value:
306 getattr(self.font.names, ours).set_default(their_value)
307 for ufofield, (table, field) in ufo_custom_opentype_values.items():
308 if getattr(firstfontinfo, ufofield) is not None:
309 value = getattr(firstfontinfo, ufofield)
310 if (table, field) in BITARRAY:
311 value = bitarray_to_int(value)
312 self.font.custom_opentype_values[(table, field)] = value
313
314 self.font.features = Features.from_fea(ufo.features.text, glyphNames=ufo.keys())
315 self._load_groups(ufo.groups)
316
317 def _save(self):
318 self.ds = DesignSpaceDocument()
319 self.save_axes()
320 self.save_sources()
321 self.save_instances()
322 # Lib
323 unexported = [g.name for g in self.font.glyphs if not g.exported]
324 if unexported:
325 self.ds.lib["public.skipExportGlyphs"] = sorted(unexported)
326 self.ds.write(self.filename)
327
328 def save_axes(self):
329 axes = self.font.axes
330 if not axes:
331 axes = [
332 Axis(
333 name=I18NDictionary.with_default("Weight"),
334 tag="wght",
335 min=100,
336 max=100,
337 default=100,
338 )
339 ]
340 for axis in axes:
341 axisDescriptor = designspaceLib.AxisDescriptor()
342 axisDescriptor.name = axis.name.get_default()
343 other_names = axis.name.as_fonttools_dict
344 if other_names:
345 axis.labelNames = other_names
346 axisDescriptor.tag = axis.tag
347 axisDescriptor.minimum = axis.min
348 axisDescriptor.maximum = axis.max
349 axisDescriptor.default = axis.default
350 axisDescriptor.map = axis.map
351 self.ds.addAxis(axisDescriptor)
352
353 def _master_filename(self, master):
354 return (
355 self.font.names.familyName.get_default().replace(" ", "")
356 + "-"
357 + master.name.get_default().replace(" ", "")
358 + ".ufo"
359 )
360
361 def save_sources(self):
362 font = self.font
363 for master in font.masters:
364 sourceDescriptor = designspaceLib.SourceDescriptor()
365 sourceDescriptor.name = (
366 font.names.familyName.get_default() + " " + master.name.get_default()
367 )
368 sourceDescriptor.filename = self._master_filename(master)
369 sourceDescriptor.styleName = master.name.get_default()
370 sourceDescriptor.familyName = font.names.familyName.get_default()
371 if master == self.font.default_master:
372 sourceDescriptor.copyLib = True
373 sourceDescriptor.copyGroups = True
374 sourceDescriptor.copyFeatures = True
375 sourceDescriptor.copyInfo = True
376 # sourceDescriptor.filename = master.filename
377 # sourceDescriptor.path = master.filename
378 axis_tags_to_names = {
379 axis.tag: axis.name.get_default() for axis in self.font.axes
380 }
381 if master.location:
382 sourceDescriptor.location = {
383 axis_tags_to_names[ax]: value
384 for ax, value in master.location.items()
385 }
386 else:
387 sourceDescriptor.location = {"Weight": 100}
388 self.ds.addSource(sourceDescriptor)
389 self.save_master_to_ufo(
390 master,
391 self._master_filename(master),
392 is_default=(master == self.font.default_master),
393 )
394
395 def save_instances(self):
396 for instance in self.font.instances:
397 instanceDescriptor = designspaceLib.InstanceDescriptor()
398 instanceDescriptor.name = (
399 self.font.names.familyName.get_default()
400 + " "
401 + instance.name.get_default()
402 )
403 names = self.font.names
404 instanceDescriptor.familyName = names.familyName.get_default()
405 instanceDescriptor.styleName = instance.name.get_default()
406 instanceDescriptor.styleMapFamilyName = (
407 names.styleMapFamilyName.get_default() or names.familyName.get_default()
408 )
409 if not ribbi(instance.name.get_default()):
410 instanceDescriptor.styleMapFamilyName += (
411 " " + instance.name.get_default()
412 )
413 instanceDescriptor.styleMapStyleName = "regular"
414 axis_tags_to_names = {
415 axis.tag: axis.name.get_default() for axis in self.font.axes
416 }
417 if instance.location:
418 instanceDescriptor.location = {
419 axis_tags_to_names[ax]: value
420 for ax, value in instance.location.items()
421 }
422 else:
423 instanceDescriptor.location = {"Weight": 400}
424 self.ds.addInstance(instanceDescriptor)
425
426 def save_master_to_ufo(self, master: Master, filename, is_default=False):
427 ufo = ufoLib2.Font()
428 ufo.info.unitsPerEm = self.font.upm
429 ufo.info.versionMajor, ufo.info.versionMinor = self.font.version
430 if self.font.note and is_default:
431 ufo.info.note = self.font.note
432 for ours, theirs in self.names_dict.items():
433 our_value = getattr(self.font.names, ours).get_default()
434 if our_value is not None:
435 setattr(ufo.info, theirs, getattr(self.font.names, ours).get_default())
436 if not ufo.info.styleName:
437 ufo.info.styleName = master.name.get_default()
438 for glyph in self.font.glyphs:
439 ufo.newGlyph(glyph.name)
440 for glyph in self.font.glyphs:
441 ufo_glyph = ufo[glyph.name]
442 layer = master.get_glyph_layer(glyph.name)
443 assert layer
444 self.save_layer_to_ufo(ufo_glyph, layer)
445 ufo_glyph.unicodes = [int(cp) for cp in glyph.codepoints]
446 if layer.background is not None:
447 if "public.background" not in ufo.layers:
448 ufo.layers.newLayer("public.background")
449 background_layer = None
450 for possible_background_layer in glyph.layers:
451 if possible_background_layer.id == layer.background:
452 background_layer = possible_background_layer
453 if background_layer:
454 background_glyph = ufo.layers["public.background"].newGlyph(
455 glyph.name
456 )
457 self.save_layer_to_ufo(background_glyph, background_layer)
458 # Metrics
459 for our_metric, their_metric in metrics.items():
460 if our_metric in master.metrics:
461 metric_value = master.metrics[our_metric]
462 if their_metric in ["openTypeOS2WinDescent"] and metric_value < 0:
463 metric_value = -metric_value
464 setattr(ufo.info, their_metric, metric_value)
465 if is_default:
466 for info_tag, (table, field) in ufo_custom_opentype_values.items():
467 if (table, field) in self.font.custom_opentype_values:
468 value = self.font.custom_opentype_values[(table, field)]
469 if (table, field) in BITARRAY:
470 if info_tag == "openTypeOS2Selection":
471 # "Bits 0 (italic), 5 (bold) and 6 (regular) must not be set here"
472 value = value & 0b11111100
473 value = int_to_bitarray(value)
474 if info_tag == "openTypeHeadCreated":
475 value = time.strftime(
476 "%Y/%m/%d %H:%M:%S",
477 time.gmtime(timeTools.epoch_diff + value),
478 )
479
480 setattr(ufo.info, info_tag, value)
481 # Guides
482 if master.guides:
483 ufo.info.guidelines = []
484 for guide in master.guides:
485 ufo.info.guidelines.append(
486 ufoLib2.objects.Guideline(
487 x=guide.pos[0],
488 y=guide.pos[1],
489 angle=guide.pos[2] % 360,
490 name=guide.name,
491 color=guide.color,
492 )
493 )
494 # Kerning
495 for group, members in self.font.first_kern_groups.items():
496 ufo.groups["public.kern1." + group] = members
497 for group, members in self.font.second_kern_groups.items():
498 ufo.groups["public.kern2." + group] = members
499 for (left, right), value in master.kerning.items():
500 if left.startswith("@first_group_"):
501 left = "public.kern1." + left[13:]
502 if right.startswith("@second_group_"):
503 right = "public.kern2." + right[14:]
504 ufo.kerning[left, right] = value
505
506 # Features and groups
507 ufo.features.text = self.font.features.to_fea()
508 # Lib
509 ufo.lib["public.glyphOrder"] = [g.name for g in self.font.glyphs]
510 psnames = {
511 g.name: g.production_name for g in self.font.glyphs if g.production_name
512 }
513 if psnames:
514 ufo.lib["public.postscriptNames"] = psnames
515 for key, value in master._formatspecific.get(UFO_KEY, {}).items():
516 ufo.lib[key] = value
517 self.logger.info("Saving %s", filename)
518 ufo.save(filename, overwrite=True)
519
520 def save_layer_to_ufo(self, ufo_glyph: ufoLib2.objects.Glyph, layer: Layer):
521 for shape in layer.shapes:
522 if shape.is_component:
523 self.save_component_to_ufo(ufo_glyph, shape)
524 else:
525 self.save_contour_to_ufo(ufo_glyph, shape)
526 for anchor in layer.anchors:
527 self.save_anchor_to_ufo(ufo_glyph, anchor)
528 ufo_glyph.width = layer.width
529 if layer.height:
530 ufo_glyph.height = layer.height
531
532 def save_anchor_to_ufo(self, ufo_glyph: ufoLib2.objects.Glyph, anchor: Anchor):
533 ufo_glyph.appendAnchor(
534 ufoLib2.objects.Anchor(name=anchor.name, x=anchor.x, y=anchor.y)
535 )
536
537 def save_component_to_ufo(self, ufo_glyph: ufoLib2.objects.Glyph, shape: Shape):
538 ufo_glyph.components.append(
539 ufoLib2.objects.Component(
540 baseGlyph=shape.ref,
541 transformation=shape.transform,
542 )
543 )
544
545 def save_contour_to_ufo(self, ufo_glyph: ufoLib2.objects.Glyph, shape: Shape):
546 pen = ufo_glyph.getPointPen()
547 pen.beginPath()
548 for node in shape.nodes:
549 pen.addPoint(
550 (node.x, node.y),
551 segmentType=Node._to_pen_type[node.type[0]],
552 smooth=node.is_smooth,
553 )
554 pen.endPath()