| 1 |
import datetime |
| 2 |
import re |
| 3 |
import math |
| 4 |
|
| 5 |
import orjson |
| 6 |
from fontTools.misc.transform import Transform |
| 7 |
|
| 8 |
from babelfont import Axis, Glyph, Layer, Master, Node, Shape, Guide |
| 9 |
from babelfont.BaseObject import Color, I18NDictionary |
| 10 |
from babelfont.convertors import BaseConvertor |
| 11 |
|
| 12 |
|
| 13 |
class FontlabVFJ(BaseConvertor): |
| 14 |
suffix = ".vfj" |
| 15 |
|
| 16 |
def _load(self): |
| 17 |
self.fontlab = orjson.loads(open(self.filename).read())["font"] |
| 18 |
self.known_transforms = {} |
| 19 |
self._load_axes() |
| 20 |
self._load_masters() |
| 21 |
if "defaultMaster" in self.fontlab: |
| 22 |
default = self.font.master(self.fontlab["defaultMaster"]) |
| 23 |
if self.font.axes: |
| 24 |
def_loc = default.location |
| 25 |
for axis in self.font.axes: |
| 26 |
if axis.tag in default.location: |
| 27 |
axis.default = axis.designspace_to_userspace(def_loc[axis.tag]) |
| 28 |
assert self.font.default_master |
| 29 |
for g in self.fontlab.get("glyphs", []): |
| 30 |
glyph = self._load_thing(g, self.glyph_loader) |
| 31 |
# Fontlab allows glyphs to elide layers with no shapes |
| 32 |
# so we need to ensure there is a layer for each master |
| 33 |
layer_ids = [l.id for l in glyph.layers] |
| 34 |
for master in self.font.masters: |
| 35 |
if master.id not in layer_ids: |
| 36 |
layer = Layer( |
| 37 |
name=master.id, |
| 38 |
_master=master.id, |
| 39 |
) |
| 40 |
layer._font = self.font |
| 41 |
glyph.layers.append(layer) |
| 42 |
|
| 43 |
self.font.glyphs.append(glyph) |
| 44 |
for cls in self.fontlab.get("classes", []): |
| 45 |
self._load_class(cls) |
| 46 |
for feature in self.fontlab.get("openTypeFeatures", []): |
| 47 |
self._load_feature(feature) |
| 48 |
self.font.upm = self.fontlab.get("upm", 1000) |
| 49 |
self._load_metadata() |
| 50 |
return self.font |
| 51 |
|
| 52 |
def _load_feature(self, feature): |
| 53 |
count = 0 |
| 54 |
if "name" in feature: |
| 55 |
# Remove the "feature ... {" first line and "} tag;" last line |
| 56 |
feature["feature"] = re.sub( |
| 57 |
r"^\s*feature\s+(\w+)\s*{(.*)\s*}\s*\1\s*;", |
| 58 |
r"\2", |
| 59 |
feature["feature"], |
| 60 |
flags=re.DOTALL, |
| 61 |
) |
| 62 |
self.font.features.features.append((feature["name"], feature["feature"])) |
| 63 |
else: |
| 64 |
self.font.features.prefixes["Anonymous prefix " + str(count)] = feature[ |
| 65 |
"feature" |
| 66 |
] |
| 67 |
count += 1 |
| 68 |
|
| 69 |
def _load_class(self, cls): |
| 70 |
self.font.features.classes[cls["name"]] = cls["names"] |
| 71 |
|
| 72 |
axis_loader = ( |
| 73 |
Axis, |
| 74 |
{ |
| 75 |
"name": "name", |
| 76 |
"tag": "tag", |
| 77 |
"minimum": "min", |
| 78 |
"maximum": "max", |
| 79 |
"default": "default", |
| 80 |
"axisGraph": ("map", lambda _, x: [(v, int(k)) for k, v in x.items()]), |
| 81 |
}, |
| 82 |
) |
| 83 |
|
| 84 |
def _load_kerning(self, flkerning): |
| 85 |
for kclass in flkerning.get("kerningClasses", []): |
| 86 |
if kclass.get("1st"): |
| 87 |
self.font.first_kern_groups[kclass["name"]] = kclass["names"] |
| 88 |
if kclass.get("2nd"): |
| 89 |
self.font.second_kern_groups[kclass["name"]] = kclass["names"] |
| 90 |
kerning = {} |
| 91 |
for left, rvalue in flkerning.get("pairs", {}).items(): |
| 92 |
if left.startswith("@"): |
| 93 |
left = "@first_group_" + left[1:] |
| 94 |
for right, value in rvalue.items(): |
| 95 |
if right.startswith("@"): |
| 96 |
right = "@second_group_" + right[1:] |
| 97 |
kerning[(left, right)] = int(value) |
| 98 |
return kerning |
| 99 |
|
| 100 |
def _convert_color(_, col): |
| 101 |
r, g, b = int(col[1:3], 16), int(col[3:5], 16), int(col[5:7], 16) |
| 102 |
return Color(r, g, b, 0) |
| 103 |
|
| 104 |
def _convert_shapes(self, flshapes): |
| 105 |
shapes = [] |
| 106 |
for shape in flshapes: |
| 107 |
transform_j = shape.get("transform", {}) |
| 108 |
if "id" in transform_j: |
| 109 |
self.known_transforms[transform_j["id"]] = transform_j |
| 110 |
if isinstance(transform_j, str): |
| 111 |
transform_j = self.known_transforms[transform_j] |
| 112 |
transform = Transform().translate( |
| 113 |
transform_j.get("xOffset", 0), |
| 114 |
transform_j.get("yOffset", 0), |
| 115 |
) |
| 116 |
if "component" in shape: |
| 117 |
shapes.append( |
| 118 |
Shape( |
| 119 |
ref=shape["component"]["glyphName"], |
| 120 |
transform=transform, |
| 121 |
_=shape["component"], |
| 122 |
) |
| 123 |
) |
| 124 |
elif "elementData" not in shape or not isinstance( |
| 125 |
shape["elementData"], dict |
| 126 |
): |
| 127 |
self.logger.warning("Ack, I don't support elements in %s", shape) |
| 128 |
else: |
| 129 |
for flcontour in shape["elementData"].get("contours", []): |
| 130 |
contour = Shape(nodes=[]) |
| 131 |
for n in flcontour["nodes"]: |
| 132 |
contour.nodes.extend(self._load_node(n)) |
| 133 |
if ( |
| 134 |
contour.nodes[0].type[0] == "l" |
| 135 |
and contour.nodes[-1].type[0] == "q" |
| 136 |
): |
| 137 |
contour.nodes[0].type = "cs" |
| 138 |
contour.nodes[-1].type = "o" |
| 139 |
shapes.append(contour) |
| 140 |
return shapes |
| 141 |
|
| 142 |
def _convert_guides(self, flguides): |
| 143 |
guides = [] |
| 144 |
for guide in flguides: |
| 145 |
if "horizontal" in guide: |
| 146 |
y = guide.get("position", 0) |
| 147 |
x = 0 |
| 148 |
angle = 0 |
| 149 |
elif "vertical" in guide: |
| 150 |
x = guide.get("position", 0) |
| 151 |
y = 0 |
| 152 |
angle = 90 |
| 153 |
else: |
| 154 |
x, y = [float(v) for v in guide.get("center", "0 0").split(" ")] |
| 155 |
vector_x, vector_y = [ |
| 156 |
float(v) for v in guide.get("vector", "0 0").split(" ") |
| 157 |
] |
| 158 |
angle = math.degrees(math.atan2(vector_y - y, vector_x - x)) |
| 159 |
guides.append(Guide(pos=(x, y, angle))) |
| 160 |
return guides |
| 161 |
|
| 162 |
def _load_node(self, input_): |
| 163 |
stuff = input_.split(" ") |
| 164 |
rv = [] |
| 165 |
for ix, node in enumerate(stuff): |
| 166 |
m = re.match(r"(-?[\d\.]+) (-?[\d\.]+)( s)?", node) |
| 167 |
if not m: |
| 168 |
raise ValueError("Can't understand nodestring %s" % node) |
| 169 |
if len(stuff) == 1: |
| 170 |
ntyp = "l" |
| 171 |
elif len(stuff) == 3 and ix == 2: |
| 172 |
ntyp = "c" |
| 173 |
elif len(stuff) == 2 and ix == 1: |
| 174 |
ntyp = "q" |
| 175 |
else: |
| 176 |
ntyp = "o" |
| 177 |
if m[3]: |
| 178 |
ntyp = ntyp + "s" |
| 179 |
rv.append(Node(x=float(m[1]), y=float(m[2]), type=ntyp)) |
| 180 |
return rv |
| 181 |
|
| 182 |
# The way these loaders work is they define a class to load into and a schema. |
| 183 |
# The schema is a mapping between *Fontlab* field names, and what we do with |
| 184 |
# it: if it's a plain string, this is our field name; if it's a tuple, it's |
| 185 |
# our field name and a method to transform the value; if it's a list, it's |
| 186 |
# a combination of field/tuples. |
| 187 |
master_loader = ( |
| 188 |
Master, |
| 189 |
{ |
| 190 |
"name": ["id", "name"], |
| 191 |
"kerning": ("kerning", _load_kerning), |
| 192 |
"location": ( |
| 193 |
"location", |
| 194 |
lambda s, x: {s.axis_name_map[k].tag: v for k, v in x.items()}, |
| 195 |
), |
| 196 |
}, |
| 197 |
) |
| 198 |
|
| 199 |
_layer_loader = ( |
| 200 |
Layer, |
| 201 |
{ |
| 202 |
"advanceWidth": "width", |
| 203 |
"name": ["name", "_master", "id"], |
| 204 |
"color": ("color", _convert_color), |
| 205 |
"elements": ("shapes", _convert_shapes), |
| 206 |
"guidelines": ("guides", _convert_guides), |
| 207 |
}, |
| 208 |
) |
| 209 |
|
| 210 |
glyph_loader = ( |
| 211 |
Glyph, |
| 212 |
{ |
| 213 |
"name": "name", |
| 214 |
"unicode": ( |
| 215 |
"codepoints", |
| 216 |
lambda _, x: [int(cp, 16) for cp in x.split(",")], |
| 217 |
), |
| 218 |
"layers": ("layers", _layer_loader), |
| 219 |
"elements": None, |
| 220 |
"openTypeGlyphClass": ( |
| 221 |
"category", |
| 222 |
lambda _, x: [None, "base", "ligature", "mark", "component"][x], |
| 223 |
), |
| 224 |
}, |
| 225 |
) |
| 226 |
|
| 227 |
def _load_thing(self, thing, handler): |
| 228 |
kwargs = {} |
| 229 |
kwargs["_"] = {} |
| 230 |
cls, mapping = handler |
| 231 |
for k, v in thing.items(): |
| 232 |
if k not in mapping: |
| 233 |
kwargs["_"][k] = v |
| 234 |
elif mapping[k] is None: |
| 235 |
continue |
| 236 |
elif isinstance(mapping[k], list): |
| 237 |
for newname in mapping[k]: |
| 238 |
kwargs[newname] = v |
| 239 |
elif isinstance(mapping[k], str): |
| 240 |
kwargs[mapping[k]] = v |
| 241 |
elif isinstance(mapping[k], tuple) and callable(mapping[k][1]): |
| 242 |
newName, convertor = mapping[k] |
| 243 |
kwargs[newName] = convertor(self, v) |
| 244 |
else: |
| 245 |
newName, convertor = mapping[k] |
| 246 |
if isinstance(v, list): |
| 247 |
kwargs[newName] = [self._load_thing(v1, convertor) for v1 in v] |
| 248 |
else: |
| 249 |
kwargs[newName] = self._load_thing(v, convertor) |
| 250 |
obj = cls(**kwargs) |
| 251 |
obj._font = self.font |
| 252 |
return obj |
| 253 |
|
| 254 |
def _load_axes(self): |
| 255 |
self.axis_name_map = {} |
| 256 |
for ax in self.fontlab.get("axes", []): |
| 257 |
axis = self._load_thing(ax, self.axis_loader) |
| 258 |
self.axis_name_map[ax["shortName"]] = axis |
| 259 |
self.font.axes.append(axis) |
| 260 |
|
| 261 |
def _load_masters(self): |
| 262 |
for m in self.fontlab.get("masters", []): |
| 263 |
fl_master = m["fontMaster"] |
| 264 |
metric_dict = {} |
| 265 |
for metric in [ |
| 266 |
"ascender", |
| 267 |
"descender", |
| 268 |
"xHeight", |
| 269 |
"capsHeight", |
| 270 |
"measurement", |
| 271 |
"linegap", |
| 272 |
"underlineThickness", |
| 273 |
"underlinePosition", |
| 274 |
]: |
| 275 |
if metric not in fl_master: |
| 276 |
continue |
| 277 |
value = fl_master[metric] |
| 278 |
del fl_master[metric] |
| 279 |
if metric == "capsHeight": |
| 280 |
metric = "capHeight" |
| 281 |
if metric == "linegap": |
| 282 |
metric = "hheaLineGap" |
| 283 |
metric_dict[metric] = value |
| 284 |
master = self._load_thing(fl_master, self.master_loader) |
| 285 |
master.metrics = metric_dict |
| 286 |
master.font = self.font |
| 287 |
master.guides = self._convert_guides(fl_master.get("guidelines", [])) |
| 288 |
self.font.masters.append(master) |
| 289 |
|
| 290 |
def _load_metadata(self): |
| 291 |
info = self.fontlab.get("info", {}) |
| 292 |
self.font.names.familyName = I18NDictionary.with_default(info.get("tfn")) |
| 293 |
# sgn? |
| 294 |
for tag in [ |
| 295 |
"copyright", |
| 296 |
"designer", |
| 297 |
"designerURL", |
| 298 |
"license", |
| 299 |
"licenseURL", |
| 300 |
"manufacturer", |
| 301 |
"manufacturerURL", |
| 302 |
"version", |
| 303 |
]: |
| 304 |
setattr(self.font.names, tag, I18NDictionary.with_default(info.get(tag))) |
| 305 |
self.font.version = (info.get("versionMajor"), info.get("versionMinor")) |
| 306 |
if "vendor" in info: |
| 307 |
self.font.custom_opentype_values[("OS/2", "achVendID")] = info["vendor"] |
| 308 |
# Fontlab date format = "2020/08/28 15:33:36" |
| 309 |
if "date" in info: |
| 310 |
self.font.date = datetime.datetime.strptime( |
| 311 |
info["creationDate"], |
| 312 |
"%Y/%m/%d %H:%M:%S", |
| 313 |
) |
| 314 |
if "useTypoMetrics" in info: |
| 315 |
self.font.custom_opentype_values[("OS/2", "fsSelection")] = 0x7 |
| 316 |
if "embedding" in info: |
| 317 |
self.font.custom_opentype_values[("OS/2", "fsType")] = int( |
| 318 |
info["embedding"], 16 |
| 319 |
) |
| 320 |
# codepageRange |
| 321 |
# unicodeRange |