| 1 |
import datetime |
| 2 |
import math |
| 3 |
import re |
| 4 |
import uuid |
| 5 |
|
| 6 |
import openstep_plist |
| 7 |
|
| 8 |
from babelfont import ( |
| 9 |
Anchor, |
| 10 |
Axis, |
| 11 |
Glyph, |
| 12 |
Guide, |
| 13 |
Instance, |
| 14 |
Layer, |
| 15 |
Master, |
| 16 |
Node, |
| 17 |
Shape, |
| 18 |
Transform, |
| 19 |
) |
| 20 |
from babelfont.convertors.glyphs.glyphs3 import GlyphsThree |
| 21 |
from babelfont.convertors.glyphs.utils import ( |
| 22 |
_glyphs_metrics_to_ours, |
| 23 |
_stash, |
| 24 |
) |
| 25 |
|
| 26 |
|
| 27 |
class Glyphs2(GlyphsThree): |
| 28 |
suffix = ".glyphs" |
| 29 |
|
| 30 |
@classmethod |
| 31 |
def is_suitable_plist(cls, convertor): |
| 32 |
return ( |
| 33 |
".formatVersion" not in convertor.scratch["plist"] |
| 34 |
or convertor.scratch["plist"][".formatVersion"] < 3 |
| 35 |
) |
| 36 |
|
| 37 |
@classmethod |
| 38 |
def can_save(cls, convertor, **kwargs): |
| 39 |
if not super().can_save(convertor, **kwargs): |
| 40 |
return False |
| 41 |
if "format" not in kwargs or kwargs["format"] != 2: |
| 42 |
return False |
| 43 |
return True |
| 44 |
|
| 45 |
@classmethod |
| 46 |
def can_load(cls, convertor): |
| 47 |
if not super().can_load(convertor): |
| 48 |
return False |
| 49 |
if "plist" not in convertor.scratch: |
| 50 |
convertor.scratch["plist"] = openstep_plist.load( |
| 51 |
open(convertor.filename, "r"), use_numbers=True |
| 52 |
) |
| 53 |
return cls.is_suitable_plist(convertor) |
| 54 |
|
| 55 |
def _load(self): |
| 56 |
self.glyphs = self.scratch["plist"] |
| 57 |
|
| 58 |
self.customParameters = {} |
| 59 |
for param in self.glyphs.get("customParameters", []): |
| 60 |
self.customParameters[param["name"]] = param["value"] |
| 61 |
|
| 62 |
self._load_axes() |
| 63 |
|
| 64 |
self._load_kern_groups(self.glyphs["glyphs"]) |
| 65 |
|
| 66 |
for gmaster in self.glyphs["fontMaster"]: |
| 67 |
self.font.masters.append(self._load_master(gmaster)) |
| 68 |
self._fixup_axes() |
| 69 |
if not self.font.default_master: |
| 70 |
raise ValueError("Cannot identify default master") |
| 71 |
|
| 72 |
for gglyph in self.glyphs["glyphs"]: |
| 73 |
g = self._load_glyph(gglyph) |
| 74 |
self.font.glyphs.append(g) |
| 75 |
|
| 76 |
for ginstance in self.glyphs.get("instances", []): |
| 77 |
self.font.instances.append(self._load_instance(ginstance)) |
| 78 |
|
| 79 |
self._fixup_axis_mappings() |
| 80 |
|
| 81 |
self._load_metadata() |
| 82 |
_stash(self.font, self.glyphs) |
| 83 |
|
| 84 |
self.interpret_features() |
| 85 |
return self.font |
| 86 |
|
| 87 |
def _load_axes(self): |
| 88 |
self.axis_name_map = {} |
| 89 |
if "Axes" in self.customParameters: |
| 90 |
for ax in self.customParameters["Axes"]: |
| 91 |
self.font.axes.append(Axis(name=ax["Name"], tag=ax["Tag"])) |
| 92 |
self.axis_name_map[ax["Name"]] = self.font.axes[-1] |
| 93 |
else: |
| 94 |
self.font.axes.append(Axis(name="Weight", tag="wght")) |
| 95 |
self.font.axes.append(Axis(name="Width", tag="wdth")) |
| 96 |
self.axis_name_map = { |
| 97 |
"Weight": self.font.axes[-1], |
| 98 |
"Width": self.font.axes[-1], |
| 99 |
} |
| 100 |
|
| 101 |
def _fixup_axes(self): |
| 102 |
for master in self.font.masters: |
| 103 |
for axis in self.font.axes: |
| 104 |
thisLoc = master.location[axis.tag] |
| 105 |
if axis.min is None or thisLoc < axis.min: |
| 106 |
axis.min = thisLoc |
| 107 |
if master.id == self._default_master_id(): |
| 108 |
axis.default = master.location[axis.tag] |
| 109 |
if axis.max is None or thisLoc > axis.max: |
| 110 |
axis.max = thisLoc |
| 111 |
|
| 112 |
def _fixup_axis_mappings(self): |
| 113 |
for axis in self.font.axes: |
| 114 |
if not axis.map: |
| 115 |
continue |
| 116 |
axis.map = list(sorted(set(axis.map))) |
| 117 |
axis.min, axis.max, axis.default = ( |
| 118 |
axis.map_backward(axis.min), |
| 119 |
axis.map_backward(axis.max), |
| 120 |
axis.map_backward(axis.default), |
| 121 |
) |
| 122 |
|
| 123 |
def _custom_parameter(self, thing, name): |
| 124 |
for param in thing.get("customParameters", []): |
| 125 |
if param["name"] == name: |
| 126 |
return param["value"] |
| 127 |
return None |
| 128 |
|
| 129 |
def _default_master_id(self): |
| 130 |
# The default master in glyphs is either the first master or the |
| 131 |
# one selected by the Variable Font Origin custom parameter |
| 132 |
vfo = self._custom_parameter(self.glyphs, "Variable Font Origin") |
| 133 |
if vfo and vfo in self.font._master_map: |
| 134 |
return vfo |
| 135 |
return self.glyphs["fontMaster"][0]["id"] |
| 136 |
|
| 137 |
def _get_master_name(self, gmaster): |
| 138 |
if gmaster.get("name"): |
| 139 |
return gmaster["name"] |
| 140 |
cname = self._custom_parameter(gmaster, "Master Name") |
| 141 |
if cname: |
| 142 |
return cname |
| 143 |
# Remove None and empty string |
| 144 |
names = list( |
| 145 |
filter( |
| 146 |
None, |
| 147 |
[ |
| 148 |
gmaster.get("width", "Regular"), |
| 149 |
gmaster.get("weight", "Regular"), |
| 150 |
gmaster.get("custom", ""), |
| 151 |
], |
| 152 |
) |
| 153 |
) |
| 154 |
|
| 155 |
# Remove redundant occurences of 'Regular' |
| 156 |
while len(names) > 1 and "Regular" in names: |
| 157 |
names.remove("Regular") |
| 158 |
if gmaster.get("italicAngle"): |
| 159 |
if names == ["Regular"]: |
| 160 |
return "Italic" |
| 161 |
if "Italic" not in gmaster.get("custom", ""): |
| 162 |
names.append("Italic") |
| 163 |
return " ".join(names) |
| 164 |
|
| 165 |
def _load_master(self, gmaster): |
| 166 |
# location = gmaster.get("axesValues", []) |
| 167 |
master = Master( |
| 168 |
name=self._get_master_name(gmaster), |
| 169 |
id=gmaster.get("id"), |
| 170 |
) |
| 171 |
for metric in Master.CORE_METRICS: |
| 172 |
master.metrics[metric] = gmaster.get(_glyphs_metrics_to_ours(metric)) |
| 173 |
# Check for metrics in custom parameters |
| 174 |
|
| 175 |
master.font = self.font |
| 176 |
|
| 177 |
axisloc = self._custom_parameter(gmaster, "Axis Location") |
| 178 |
if axisloc: |
| 179 |
# I dunno, use that? Needs mapping? Check we are using tags/IDs |
| 180 |
location = axisloc |
| 181 |
else: |
| 182 |
potential_locations = [ |
| 183 |
gmaster.get("weightValue", 100), |
| 184 |
gmaster.get("widthValue", 100), |
| 185 |
gmaster.get("customValue", 0), |
| 186 |
gmaster.get("customValue1", 0), |
| 187 |
gmaster.get("customValue2", 0), |
| 188 |
gmaster.get("customValue3", 0), |
| 189 |
] |
| 190 |
location = {} |
| 191 |
for k, loc in zip(self.font.axes, potential_locations): |
| 192 |
location[k.tag] = loc |
| 193 |
master.location = location |
| 194 |
|
| 195 |
master.guides = [self._load_guide(x) for x in gmaster.get("guides", [])] |
| 196 |
|
| 197 |
kernmaster = None |
| 198 |
if self._custom_parameter(gmaster, "Link Metrics With First Master"): |
| 199 |
kernmaster = self.glyphs["fontMaster"][0]["id"] |
| 200 |
elif self._custom_parameter(gmaster, "Link Metrics With Master"): |
| 201 |
kernmaster_name = self._custom_parameter( |
| 202 |
gmaster, "Link Metrics With Master" |
| 203 |
) |
| 204 |
for m in self.glyphs["fontMaster"]: |
| 205 |
name = self._get_master_name(m) |
| 206 |
if name == kernmaster_name: |
| 207 |
kernmaster = m["id"] |
| 208 |
else: |
| 209 |
kernmaster = master.id |
| 210 |
kerntable = self.glyphs.get("kerning", {}).get(kernmaster, {}) |
| 211 |
master.kerning = self._load_kerning(kerntable) |
| 212 |
|
| 213 |
_stash(master, gmaster) |
| 214 |
return master |
| 215 |
|
| 216 |
def _get_codepoint(self, gglyph): |
| 217 |
cp = gglyph.get("unicode") |
| 218 |
if not cp: |
| 219 |
return [] |
| 220 |
if isinstance(cp, int): |
| 221 |
return [int("%04i" % cp, 16)] |
| 222 |
return [int(x, 16) for x in cp.split(",")] |
| 223 |
|
| 224 |
def _load_glyph(self, gglyph): |
| 225 |
name = gglyph["glyphname"] |
| 226 |
c = gglyph.get("category") |
| 227 |
sc = gglyph.get("subCategory") |
| 228 |
if sc == "Ligature": |
| 229 |
category = "ligature" |
| 230 |
if c == "Mark": |
| 231 |
category = "mark" |
| 232 |
else: |
| 233 |
category = "base" |
| 234 |
cp = self._get_codepoint(gglyph) |
| 235 |
exported = True |
| 236 |
if "export" in gglyph and gglyph["export"] == 0: |
| 237 |
exported = False |
| 238 |
g = Glyph(name=name, codepoints=cp or [], category=category, exported=exported) |
| 239 |
g.production_name = gglyph.pop("production", None) |
| 240 |
|
| 241 |
for layer in gglyph.pop("layers"): |
| 242 |
g.layers.extend(self._load_layer(layer, g)) |
| 243 |
|
| 244 |
_stash(g, gglyph) |
| 245 |
return g |
| 246 |
|
| 247 |
def _load_layer(self, layer, glyph, width=None): |
| 248 |
if width is None: |
| 249 |
width = layer["width"] |
| 250 |
l = Layer(width=width, id=layer.get("layerId"), _font=self.font, _glyph=glyph) |
| 251 |
l.name = layer.get("name") |
| 252 |
if [x for x in self.font.masters if x.id == l.id]: |
| 253 |
l._master = l.id |
| 254 |
else: |
| 255 |
l._master = layer.get("associatedMasterId") |
| 256 |
l.guides = [ |
| 257 |
self._load_guide(x) |
| 258 |
for x in layer.get("guideLines", layer.get("guides", [])) |
| 259 |
] |
| 260 |
l.shapes = [] |
| 261 |
for shape in layer.get("shapes", []): |
| 262 |
l.shapes.append(self._load_shape(shape)) |
| 263 |
for shape in layer.get("paths", []): |
| 264 |
l.shapes.append(self._load_path(shape)) |
| 265 |
for shape in layer.get("components", []): |
| 266 |
l.shapes.append(self._load_component(shape)) |
| 267 |
for anchor in layer.get("anchors", []): |
| 268 |
l.anchors.append(self._load_anchor(anchor)) |
| 269 |
|
| 270 |
returns = [l] |
| 271 |
if "background" in layer: |
| 272 |
(background,) = self._load_layer(layer["background"], glyph, width=l.width) |
| 273 |
# If it doesn't have an ID, we need to generate one |
| 274 |
background.id = background.id or str(uuid.uuid1()) |
| 275 |
background.isBackground = True |
| 276 |
|
| 277 |
l.background = background.id |
| 278 |
returns.append(background) |
| 279 |
# TODO backgroundImage, metricTop/Bottom/etc, vertOrigin, vertWidth. |
| 280 |
for r in returns: |
| 281 |
assert r.valid |
| 282 |
_stash(l, layer) |
| 283 |
|
| 284 |
return returns |
| 285 |
|
| 286 |
def _load_guide(self, gguide): |
| 287 |
pos = gguide.get("position", "{0, 0}") |
| 288 |
m = re.match(r"^\{(\S+), (\S+)\}", pos) |
| 289 |
return Guide(pos=[int(m[1]), int(m[2]), int(gguide.get("angle", 0))]) |
| 290 |
|
| 291 |
def _load_anchor(self, ganchor): |
| 292 |
pos = ganchor.get("position", "{0, 0}") |
| 293 |
m = re.match(r"^\{(\S+), (\S+)\}", pos) |
| 294 |
return Anchor(name=ganchor["name"], x=float(m[1]), y=float(m[2])) |
| 295 |
|
| 296 |
def _load_instance(self, ginstance): |
| 297 |
if ginstance.get("type") == "variable": |
| 298 |
return |
| 299 |
if "axesValues" in ginstance: |
| 300 |
location = ginstance["axesValues"] |
| 301 |
instance_location = {k.tag: v for k, v in zip(self.font.axes, location)} |
| 302 |
elif "instanceInterpolations" in ginstance: |
| 303 |
# All right then. |
| 304 |
instance_location = {k.tag: 0 for k in self.font.axes} |
| 305 |
for mId, factor in ginstance["instanceInterpolations"].items(): |
| 306 |
master_loc = self.font.master(mId).location |
| 307 |
for k in self.font.axes: |
| 308 |
instance_location[k.tag] += master_loc[k.tag] * factor |
| 309 |
else: |
| 310 |
raise ValueError("Need to Synthesize location") |
| 311 |
i = Instance( |
| 312 |
name=ginstance["name"], |
| 313 |
styleName=ginstance["name"], |
| 314 |
location=instance_location, |
| 315 |
) |
| 316 |
c = self._custom_parameter(ginstance, "Axis Location") or [] |
| 317 |
for loc in c: |
| 318 |
ax = self.axis_name_map[loc["Axis"]] |
| 319 |
if not ax.map: |
| 320 |
ax.map = [] |
| 321 |
ax.map.append( |
| 322 |
( |
| 323 |
int(loc["Location"]), |
| 324 |
instance_location[ax.tag], |
| 325 |
) |
| 326 |
) |
| 327 |
|
| 328 |
_stash(i, ginstance, ["customParameters"]) |
| 329 |
return i |
| 330 |
|
| 331 |
def _load_path(self, path): |
| 332 |
shape = Shape() |
| 333 |
shape.nodes = [] |
| 334 |
for n in path["nodes"]: |
| 335 |
m = re.match(r"(\S+) (\S+) (\S+)( SMOOTH)?(.*)", n) |
| 336 |
ntype = m[3][0].lower() |
| 337 |
if m[4]: |
| 338 |
ntype = ntype + "s" |
| 339 |
n = Node(x=float(m[1]), y=float(m[2]), type=ntype) |
| 340 |
shape.nodes.append(n) |
| 341 |
shape.closed = bool(path["closed"]) |
| 342 |
_stash(shape, path, ["attr"]) |
| 343 |
return shape |
| 344 |
|
| 345 |
def _load_component(self, shape): |
| 346 |
glyphname = shape.get("ref", shape.get("name")) |
| 347 |
transform = shape.get("transform") |
| 348 |
if isinstance(transform, str): |
| 349 |
m = re.match(r"^\{(\S+), (\S+), (\S+), (\S+), (\S+), (\S+)\}", transform) |
| 350 |
transform = Transform(*[float(g) for g in m.groups()]) |
| 351 |
c = Shape(ref=glyphname) |
| 352 |
|
| 353 |
if not transform: |
| 354 |
translate = Transform().translate(*shape.get("pos", (0, 0))) |
| 355 |
scale = Transform().scale(*shape.get("scale", (1, 1))) |
| 356 |
rotation = Transform().rotate(math.radians(shape.get("angle", 0))) |
| 357 |
# Compute transform... |
| 358 |
transform = translate.transform(scale).transform(rotation) |
| 359 |
|
| 360 |
c.transform = transform |
| 361 |
_stash( |
| 362 |
c, |
| 363 |
shape, |
| 364 |
[ |
| 365 |
"alignment", |
| 366 |
"anchorTo", |
| 367 |
"attr", |
| 368 |
"locked", |
| 369 |
"orientation", |
| 370 |
"piece", |
| 371 |
"userData", |
| 372 |
], |
| 373 |
) |
| 374 |
return c |
| 375 |
|
| 376 |
def _load_kern_groups(self, glyphs): |
| 377 |
kerngroups = {} |
| 378 |
for g in glyphs: |
| 379 |
l_class = g.get("leftKerningGroup", g["glyphname"]) |
| 380 |
r_class = g.get("rightKerningGroup", g["glyphname"]) |
| 381 |
# DAMMIT GLYPHS |
| 382 |
kerngroups.setdefault("MMK_R_" + l_class, []).append(g["glyphname"]) |
| 383 |
kerngroups.setdefault("MMK_L_" + r_class, []).append(g["glyphname"]) |
| 384 |
for k, v in kerngroups.items(): |
| 385 |
self.font.features.classes[k] = tuple(v) |
| 386 |
|
| 387 |
def _load_kerning(self, kerndict): |
| 388 |
return { |
| 389 |
(l, r): value |
| 390 |
for l, level2 in kerndict.items() |
| 391 |
for r, value in level2.items() |
| 392 |
} |
| 393 |
|
| 394 |
def _load_metadata(self): |
| 395 |
self.font.upm = self.glyphs["unitsPerEm"] |
| 396 |
self.font.version = (self.glyphs["versionMajor"], self.glyphs["versionMinor"]) |
| 397 |
self.font.names.familyName.set_default(self.glyphs["familyName"]) |
| 398 |
|
| 399 |
# This is very glyphs 3 |
| 400 |
props = {} |
| 401 |
for prop in self.glyphs.get("properties", []): |
| 402 |
if "value" in prop: |
| 403 |
props[prop["key"]] = prop["value"] |
| 404 |
else: |
| 405 |
props[prop["key"]] = {p["language"]: p["value"] for p in prop["values"]} |
| 406 |
|
| 407 |
if props: |
| 408 |
interestingProps = { |
| 409 |
"copyrights": "copyright", |
| 410 |
"designer": "designer", |
| 411 |
"designerURL": "designerURL", |
| 412 |
} # Etc |
| 413 |
for glyphsname, attrname in interestingProps.items(): |
| 414 |
thing = props.get(glyphsname, "") |
| 415 |
if isinstance(thing, dict): |
| 416 |
getattr(self.font.names, attrname).copy_in(thing) |
| 417 |
else: |
| 418 |
getattr(self.font.names, attrname).set_default(thing) |
| 419 |
# Do other properties here |
| 420 |
|
| 421 |
# Any customparameters in the default master which look like |
| 422 |
# custom OT values need to move there. |
| 423 |
# cp = self.font.default_master._formatspecific.get("com.glyphsapp", {}).get( |
| 424 |
# "customParameters", {} |
| 425 |
# ) |
| 426 |
# for param in cp: |
| 427 |
# ot_param = opentype_custom_parameters.get(param["name"]) |
| 428 |
# if not ot_param: |
| 429 |
# continue |
| 430 |
# self.font.customOpenTypeValues.append( |
| 431 |
# OTValue(ot_param[0], ot_param[1], param["value"]) |
| 432 |
# ) |
| 433 |
|
| 434 |
self.font.note = self.glyphs.get("note") |
| 435 |
self.font.date = datetime.datetime.strptime( |
| 436 |
self.glyphs.get("date"), "%Y-%m-%d %H:%M:%S +0000" |
| 437 |
) |
| 438 |
_stash(self.font, self.glyphs) |
| 439 |
|
| 440 |
def _load_features(self): |
| 441 |
for c in self.glyphs.get("classes", []): |
| 442 |
self.font.features.classes[c["name"]] = tuple(c["code"].split()) |
| 443 |
|
| 444 |
# featurefile = "" |
| 445 |
# for f in self.glyphs.get("featurePrefixes", []): |
| 446 |
# featurefile = featurefile + f.get("code") |
| 447 |
# for f in self.glyphs.get("features", []): |
| 448 |
# tag = f.get("tag", f.get("name", "")) |
| 449 |
# feacode = "feature %s { %s\n} %s;" % (tag, f["code"], tag) |
| 450 |
# featurefile = featurefile + feacode |
| 451 |
|
| 452 |
# glyphNames = {g.name for g in self.font.glyphs} |
| 453 |
# feaparser = FeaParser(featurefile, glyphNames=glyphNames) |
| 454 |
# ast = feaparser.parser.ast |
| 455 |
# for name, members in self.font.features.classes.items(): |
| 456 |
# glyphclass = ast.GlyphClassDefinition( |
| 457 |
# name, ast.GlyphClass([m for m in members]) |
| 458 |
# ) |
| 459 |
# feaparser.parser.glyphclasses_.define(name, glyphclass) |
| 460 |
# feaparser.parse() |
| 461 |
# self.font.features += feaparser.ff |