Debian Codegraph @

src/babelfont/Axis.py

raw
1 from typing import List, Optional, Dict, Tuple
2 from .BaseObject import BaseObject, I18NDictionary, Number
3 from dataclasses import dataclass, field
4 import uuid
5 from fontTools.varLib.models import normalizeValue, piecewiseLinearMap
6
7
8 Tag = str
9
10
11 @dataclass
12 class _AxisFields:
13 name: I18NDictionary = field(
14 metadata={"description": "The display name for this axis."}
15 )
16 tag: Tag = field(metadata={"description": "The four-letter axis tag."})
17 id: str = field(
18 default_factory=lambda: str(uuid.uuid1()),
19 repr=False,
20 metadata={
21 "description": """An ID used to refer to this axis in the Master,
22 Layer and Instance `location` fields. (This is allows the user to change the
23 axis tag without the locations becoming lost.) If not provided, one will be
24 automatically generated on import from a UUID."""
25 },
26 )
27 min: int = field(
28 default=None,
29 metadata={
30 "description": "The minimum value of this axis, in user space coordinates."
31 },
32 )
33 max: int = field(
34 default=None,
35 metadata={
36 "description": "The maximum value of this axis, in user space coordinates."
37 },
38 )
39 default: int = field(
40 default=None,
41 metadata={
42 "description": """The default value of this axis (center of interpolation),
43 in user space coordinates. Note that if the min/max/default values are not supplied,
44 they are returned as `None` in the Python object, and should be computed from the
45 master locations on export."""
46 },
47 )
48 map: List[Tuple[int, int]] = field(
49 default=None,
50 metadata={
51 "description": """The mapping between userspace and designspace coordinates."""
52 },
53 )
54 hidden: bool = field(
55 default=False,
56 metadata={
57 "description": """If `True`, this axis is hidden from the user interface.
58 Hidden axes are used for internal font generation and are not displayed in the
59 user interface."""
60 },
61 )
62
63
64 @dataclass
65 class Axis(BaseObject, _AxisFields):
66 """Represents an axis in a multiple master or variable font."""
67
68 _write_one_line = True
69
70 def __post_init__(self):
71 # If they smacked my name with a bare string, replace with I18NDict
72 if isinstance(self.name, str):
73 self.name = I18NDictionary.with_default(self.name)
74 super().__post_init__()
75
76 def normalize_value(self, value: Number) -> float:
77 """Return a normalized co-ordinate (-1.0 to 1.0) for the given value.
78 The value provided is expected to be in userspace coordinates."""
79 return normalizeValue(
80 self.userspace_to_designspace(value),
81 (
82 self.userspace_to_designspace(self.min),
83 self.userspace_to_designspace(self.default),
84 self.userspace_to_designspace(self.max),
85 ),
86 )
87
88 def denormalize_value(self, value: float) -> Number:
89 """Return a userspace coordinate for the given normalized value."""
90 if value == 0:
91 return self.default
92 elif value > 0:
93 return self.default + (self.max - self.default) * value
94 else:
95 return self.default + (self.default - self.min) * value
96
97 # Compatibility with designspaceLib. Our names are smaller for serialization.
98 @property
99 def maximum(self):
100 return self.max
101
102 @property
103 def minimum(self):
104 return self.min
105
106 # Compatibility with fontTools.varLib
107 @property
108 def maxValue(self):
109 return self.max
110
111 @property
112 def minValue(self):
113 return self.min
114
115 @property
116 def axisTag(self):
117 return self.tag
118
119 @property
120 def defaultValue(self):
121 return self.default
122
123 @property
124 def inverted_map(self) -> Optional[Tuple[float, float]]:
125 """Return the axis map as a list of tuples, where the first value is the
126 designspace coordinate and the second value is the userspace coordinate."""
127 if not self.map:
128 return None
129 return [(v, k) for k, v in self.map]
130
131 # Stolen from fontTools.designspaceLib
132 def map_forward(self, v: Number) -> Number:
133 """Map a location on this axis from userspace to designspace."""
134 if not self.map:
135 return v
136 return piecewiseLinearMap(v, dict(self.map))
137
138 def map_backward(self, v: Number) -> Number:
139 """Map a location on this axis from designspace to userspace."""
140 if not self.map:
141 return v
142 return piecewiseLinearMap(v, {v: k for k, v in self.map})
143
144 # These are just better names
145 def userspace_to_designspace(self, v: Number) -> Number:
146 """Map a location on this axis from userspace to designspace."""
147 return self.map_forward(v)
148
149 def designspace_to_userspace(self, v: Number) -> Number:
150 """Map a location on this axis from designspace to userspace."""
151 return self.map_backward(v)