Debian Codegraph @

src/babelfont/fontFilters/intermediateLayer.py

raw
1 import logging
2 import uuid
3 from collections import defaultdict
4 from typing import Dict, Optional
5
6 from babelfont import Font, Layer, Master
7
8 logger = logging.getLogger(__name__)
9
10
11 def promote_intermediate_layers(font: Font, _args: dict):
12 # Intermediate layers are sparse masters. To handle intermediate
13 # layers, we're going to find all the intermediate layers situated
14 # at the same point in the designspace, and create a sparse master
15 # at that point.
16 additional_masters = defaultdict(list)
17
18 for glyph in font.glyphs:
19 newlayers = []
20 for layer in glyph.layers:
21 if loc := intermediate_location(layer, font):
22 additional_masters[tuple(loc.items())].append(layer)
23 else:
24 newlayers.append(layer)
25 glyph.layers = newlayers
26
27 if not additional_masters:
28 return
29 logger.info("Promoting intermediate layers to sparse masters")
30
31 # Create the masters and associate the layers with them
32 for loc_tuple, layers in additional_masters.items():
33 loc = dict(loc_tuple)
34 if any(master.location == loc for master in font.masters):
35 _master_exists_error(loc, layers)
36 continue
37 master = Master(
38 name=str(loc), id=str(uuid.uuid1()), location=loc, sparse=True, font=font
39 )
40 font.masters.append(master)
41 for layer in layers:
42 layer._master = master.id
43 layer.id = master.id
44 # Remove the intermediate coordinate, making it a regular layer
45 del layer._formatspecific["com.glyphsapp"]["attr"]["coordinates"]
46
47
48 # We know a layer is "intermediate" if it has a Glyphs-specific attribute
49 # ["attr"]["coordinates"]. The coordinates are the location of the sparse master;
50 # just the raw values, so we zip them with the axis tags in order.
51 def intermediate_location(l: Layer, f: Font) -> Optional[Dict[str, float]]:
52 if not l._formatspecific or not l._formatspecific["com.glyphsapp"]:
53 return
54 attr = l._formatspecific["com.glyphsapp"].get("attr")
55 if attr and "coordinates" in attr:
56 return {axis.tag: coord for axis, coord in zip(f.axes, attr["coordinates"])}
57
58
59 def _master_exists_error(loc, layers):
60 glyphs = ", ".join(sorted(layer.glyph.name for layer in layers))
61 pl = "s" if len(layers) > 1 else ""
62 logger.error(
63 f"Glyph{pl} {glyphs} had an 'intermediate' layer at {loc}, but a master already exists"
64 )