Debian Codegraph @

src/babelfont/Font.py

raw
1 import functools
2 import logging
3 from dataclasses import dataclass, field
4 from datetime import datetime
5 from typing import Any, Dict, List, Optional, Tuple
6
7 from fontTools.feaLib.variableScalar import VariableScalar
8 from fontTools.varLib.models import VariationModel
9
10 from .Axis import Axis, Tag
11 from .BaseObject import BaseObject, IncompatibleMastersError, Number
12 from .Features import Features
13 from .Glyph import GlyphList
14 from .Instance import Instance
15 from .Master import Master
16 from .Names import Names
17
18 log = logging.getLogger(__name__)
19
20
21 @dataclass
22 class _FontFields:
23 upm: int = field(default=1000, metadata={"description": "The font's units per em."})
24 version: Tuple[int, int] = field(
25 default=(1, 0),
26 metadata={
27 "description": "Font version number as a tuple of integers (major, minor).",
28 "json_type": "[int,int]",
29 },
30 )
31 axes: List[Axis] = field(
32 default_factory=list,
33 metadata={
34 "separate_items": True,
35 "description": "A list of axes, in the case of variable/multiple master font. May be empty.",
36 },
37 )
38 instances: List[Instance] = field(
39 default_factory=list,
40 metadata={
41 "separate_items": True,
42 "description": "A list of named/static instances.",
43 },
44 )
45 masters: List[Master] = field(
46 default_factory=list,
47 metadata={
48 "separate_items": True,
49 "description": "A list of the font's masters.",
50 },
51 )
52 glyphs: GlyphList = field(
53 default_factory=GlyphList,
54 metadata={
55 "skip_serialize": True,
56 "separate_items": True,
57 "json_type": "[dict]",
58 "json_location": "glyphs.json",
59 "description": """A list of all glyphs supported in the font.
60
61 The `GlyphList` structure in the Python object is a dictionary with array-like
62 properties (or you might think of it as an array with dictionary-like properties)
63 containing [`Glyph`](Glyph.html) objects. The `GlyphList` may be iterated
64 directly, and may be appended to, but may also be used to index a `Glyph` by
65 its name. This is generally what you want:
66
67 ```Python
68
69 for g in font.glyphs:
70 assert isinstance(g, Glyph)
71
72 font.glyphs.append(newglyph)
73
74 glyph_ampersand = font.glyphs["ampersand"]
75 ```
76 """,
77 },
78 )
79 note: str = field(
80 default=None,
81 metadata={"description": "Any user-defined textual note about this font."},
82 )
83 date: datetime = field(
84 default_factory=datetime.now,
85 metadata={
86 "description": """The font's date. When writing to Babelfont-JSON, this
87 should be stored in the format `%Y-%m-%d %H:%M:%S`. *If not provided, defaults
88 to the current date/time*.""",
89 "json_type": "str",
90 },
91 )
92 names: Names = field(default_factory=Names, metadata={"skip_serialize": True})
93 custom_opentype_values: Dict[Tuple[str, str], Any] = field(
94 default_factory=dict,
95 metadata={
96 "description": "Any values to be placed in OpenType tables on export to override defaults; these must be font-wide. Metrics which may vary by master should be placed in the `metrics` field of a Master."
97 },
98 )
99 features: Features = field(
100 default_factory=Features,
101 metadata={
102 "description": "A representation of the font's OpenType features",
103 },
104 )
105 first_kern_groups: Dict[str, List[str]] = field(
106 default_factory=dict,
107 metadata={
108 "description": "A dictionary of kerning groups, where the key is the group name and the value is a list of glyph names in the group."
109 },
110 )
111 second_kern_groups: Dict[str, List[str]] = field(
112 default_factory=dict,
113 metadata={
114 "description": "A dictionary of kerning groups, where the key is the group name and the value is a list of glyph names in the group."
115 },
116 )
117
118
119 @dataclass
120 class Font(_FontFields, BaseObject):
121 """Represents a font, with one or more masters."""
122
123 def __repr__(self):
124 return "<Font '%s' (%i masters)>" % (
125 self.names.familyName.get_default(),
126 len(self.masters),
127 )
128
129 def save(self, filename: str, **kwargs):
130 """Save the font to a file. The file type is determined by the extension.
131 Any additional keyword arguments are passed to the save method of the
132 appropriate converter."""
133 from .convertors import Convert
134
135 return Convert(filename).save(self, **kwargs)
136
137 def master(self, mid: str) -> Optional[Master]:
138 """Locates a master by its ID. Returns `None` if not found."""
139 return self._master_map[mid]
140
141 def map_forward(self, location: dict[Tag, Number]) -> dict[Tag, Number]:
142 """Map a location (dictionary of `tag: number`) from userspace to designspace."""
143 location2 = dict(location)
144 for a in self.axes:
145 if a.tag in location2:
146 location2[a.tag] = a.map_forward(location2[a.tag])
147 return location2
148
149 def map_backward(self, location: dict[Tag, Number]) -> dict[Tag, Number]:
150 """Map a location (dictionary of `tag: number`) from designspace to userspace."""
151 location2 = dict(location)
152 for a in self.axes:
153 if a.tag in location2:
154 location2[a.tag] = a.map_backward(location2[a.tag])
155 return location2
156
157 def userspace_to_designspace(self, v: dict[Tag, Number]) -> dict[Tag, Number]:
158 """Map a location (dictionary of `tag: number`) from userspace to designspace."""
159 return self.map_forward(v)
160
161 def designspace_to_userspace(self, v: dict[Tag, Number]) -> dict[Tag, Number]:
162 """Map a location (dictionary of `tag: number`) from designspace to userspace."""
163 return self.map_backward(v)
164
165 @functools.cached_property
166 def default_master(self) -> Master:
167 """Return the default master. If there is only one master, return it.
168 If there are multiple masters, return the one with the default location.
169 If there is no default location, raise an error."""
170 default_loc = {a.tag: a.userspace_to_designspace(a.default) for a in self.axes}
171 for m in self.masters:
172 if m.location == default_loc:
173 return m
174 if len(self.masters) == 1:
175 return self.masters[0]
176 raise ValueError("Could not determine default master")
177
178 @functools.cached_property
179 def _master_map(self):
180 return {m.id: m for m in self.masters}
181
182 @functools.cached_property
183 def unicode_map(self) -> Dict[int, str]:
184 """Return a dictionary mapping Unicode codepoints to glyph names."""
185 unicodes = {}
186 for g in self.glyphs:
187 for u in g.codepoints:
188 if u is not None:
189 unicodes[u] = g.name
190 return unicodes
191
192 def variation_model(self) -> VariationModel:
193 """Return a `fontTools.varLib.models.VariationModel` object representing
194 the font's axes and masters. This is used for generating variable fonts."""
195 return VariationModel(
196 [m.normalized_location for m in self.masters],
197 axisOrder=[a.tag for a in self.axes],
198 )
199
200 @functools.cached_property
201 def _all_kerning(self):
202 all_keys = [set(m.kerning.keys()) for m in self.masters]
203 kerndict = {}
204 for left, right in list(set().union(*all_keys)):
205 kern = VariableScalar()
206 kern.axes = self.axes
207 for m in self.masters:
208 thiskern = m.kerning.get((left, right), 0)
209 if (left, right) not in m.kerning:
210 log.debug(
211 "Master %s did not define a kern pair for (%s, %s), using 0"
212 % (m.name.get_default(), left, right)
213 )
214 kern.add_value(m.location, thiskern)
215 kerndict[(left, right)] = kern
216 return kerndict
217
218 @functools.cached_property
219 def _all_anchors(self):
220 _all_anchors_dict = {}
221 for g in sorted(self.glyphs.keys()):
222 default_layer = self.default_master.get_glyph_layer(g)
223 has_mark = None
224 for a in default_layer.anchors_dict.keys():
225 if a[0] == "_":
226 if has_mark:
227 log.warning(
228 "Glyph %s tried to be in two mark classes (%s, %s). The first one will win."
229 % (g, has_mark, a)
230 )
231 continue
232 has_mark = a
233 if a not in _all_anchors_dict:
234 _all_anchors_dict[a] = {}
235 _all_anchors_dict[a][g] = self.get_variable_anchor(g, a)
236 return _all_anchors_dict
237
238 def get_variable_anchor(
239 self, glyph, anchorname
240 ) -> Tuple[VariableScalar, VariableScalar]:
241 """Return a tuple of `VariableScalar` objects representing the x and y
242 coordinates of the anchor on the given glyph. The `VariableScalar` objects
243 are indexed by master location. If the anchor is not found on some master,
244 raise an `IncompatibleMastersError`."""
245 x_vs = VariableScalar()
246 x_vs.axes = self.axes
247 y_vs = VariableScalar()
248 y_vs.axes = self.axes
249 for ix, m in enumerate(self.masters):
250 layer = m.get_glyph_layer(glyph)
251 if anchorname not in layer.anchors_dict:
252 raise IncompatibleMastersError(
253 "Anchor %s not found on glyph %s in master %s"
254 % (anchorname, glyph, m)
255 )
256 anchor = m.get_glyph_layer(glyph).anchors_dict[anchorname]
257 x_vs.add_value(self.map_forward(m.location), anchor.x)
258 y_vs.add_value(self.map_forward(m.location), anchor.y)
259 return (x_vs, y_vs)
260
261 def exported_glyphs(self) -> List[str]:
262 """Return a list of glyph names that are marked for export."""
263 return [g.name for g in self.glyphs if g.exported]