| 1 |
import datetime |
| 2 |
import math |
| 3 |
import re |
| 4 |
import uuid |
| 5 |
from collections import OrderedDict |
| 6 |
from typing import List |
| 7 |
|
| 8 |
import openstep_plist |
| 9 |
|
| 10 |
from babelfont import ( |
| 11 |
Anchor, |
| 12 |
Axis, |
| 13 |
Features, |
| 14 |
Glyph, |
| 15 |
Guide, |
| 16 |
Instance, |
| 17 |
Layer, |
| 18 |
Master, |
| 19 |
Node, |
| 20 |
Shape, |
| 21 |
Transform, |
| 22 |
) |
| 23 |
from babelfont.convertors import BaseConvertor |
| 24 |
from babelfont.convertors.glyphs.utils import ( |
| 25 |
_copyattrs, |
| 26 |
_custom_parameter, |
| 27 |
_g, |
| 28 |
_glyphs_metrics_to_ours, |
| 29 |
_metrics_dict_to_name, |
| 30 |
_metrics_name_to_dict, |
| 31 |
_moveformatspecific, |
| 32 |
_stash, |
| 33 |
_stashed_cp, |
| 34 |
glyphs_i18ndict, |
| 35 |
labels_to_feature, |
| 36 |
to_bitfield, |
| 37 |
custom_parameter_metrics, |
| 38 |
) |
| 39 |
from babelfont.Master import CORE_METRICS |
| 40 |
|
| 41 |
|
| 42 |
class GlyphsThree(BaseConvertor): |
| 43 |
suffix = ".glyphs" |
| 44 |
LOAD_FILTERS = ["glyphData", "intermediateLayers"] |
| 45 |
|
| 46 |
@classmethod |
| 47 |
def is_suitable_plist(cls, convertor): |
| 48 |
return ( |
| 49 |
".formatVersion" in convertor.scratch["plist"] |
| 50 |
and convertor.scratch["plist"][".formatVersion"] >= 3 |
| 51 |
) |
| 52 |
|
| 53 |
@classmethod |
| 54 |
def can_load(cls, convertor): |
| 55 |
if not super().can_load(convertor): |
| 56 |
return False |
| 57 |
if "plist" not in convertor.scratch: |
| 58 |
convertor.scratch["plist"] = openstep_plist.load( |
| 59 |
open(convertor.filename, "r"), use_numbers=True |
| 60 |
) |
| 61 |
return cls.is_suitable_plist(convertor) |
| 62 |
|
| 63 |
@classmethod |
| 64 |
def can_save(cls, convertor, **kwargs): |
| 65 |
if not convertor.filename.endswith(".glyphs"): |
| 66 |
return False |
| 67 |
if "format" in kwargs: |
| 68 |
return kwargs["format"] == 3 |
| 69 |
return True |
| 70 |
|
| 71 |
def _load(self): |
| 72 |
font = self.font |
| 73 |
glyphs = self.scratch["plist"] |
| 74 |
|
| 75 |
for axis in glyphs.pop("axes", []): |
| 76 |
font.axes.append(self.load_axis(axis)) |
| 77 |
|
| 78 |
for master in glyphs.pop("fontMaster"): |
| 79 |
font.masters.append(self.load_master(master)) |
| 80 |
|
| 81 |
for glyph in glyphs.pop("glyphs"): |
| 82 |
font.glyphs.append(self.load_glyph(glyph)) |
| 83 |
|
| 84 |
for instance in glyphs.pop("instances", []): |
| 85 |
instance = self.load_instance(instance) |
| 86 |
if instance: |
| 87 |
font.instances.append(instance) |
| 88 |
|
| 89 |
self.load_metadata() |
| 90 |
|
| 91 |
_stash(font, glyphs) |
| 92 |
|
| 93 |
# Things that start with "interpret" should pop their |
| 94 |
# format-specific values, and will generally need |
| 95 |
# another method to de-interpret them on save |
| 96 |
|
| 97 |
self.interpret_metrics() |
| 98 |
self.interpret_axes() |
| 99 |
self.interpret_axis_mappings() |
| 100 |
# Oops, we put the axes in designspace coordinates |
| 101 |
for axis in self.font.axes: |
| 102 |
axis.default = axis.designspace_to_userspace(axis.default) |
| 103 |
axis.min = axis.designspace_to_userspace(axis.min) |
| 104 |
axis.max = axis.designspace_to_userspace(axis.max) |
| 105 |
|
| 106 |
self.interpret_linked_kerning() |
| 107 |
assert self.font.default_master |
| 108 |
self.interpret_kern_groups() |
| 109 |
self.interpret_master_custom_parameters() |
| 110 |
self.interpret_font_custom_parameters() |
| 111 |
self.interpret_features() |
| 112 |
return font |
| 113 |
|
| 114 |
def load_metadata(self): |
| 115 |
glyphs = self.scratch["plist"] |
| 116 |
self.font.upm = glyphs.pop("unitsPerEm") |
| 117 |
self.font.version = (glyphs.pop("versionMajor"), glyphs.pop("versionMinor")) |
| 118 |
self.font.names.familyName.set_default(glyphs.pop("familyName")) |
| 119 |
|
| 120 |
# This is very glyphs 3 |
| 121 |
props = {} |
| 122 |
for prop in glyphs.get("properties", []): |
| 123 |
if "value" in prop: |
| 124 |
props[prop["key"]] = prop["value"] |
| 125 |
else: |
| 126 |
props[prop["key"]] = {p["language"]: p["value"] for p in prop["values"]} |
| 127 |
|
| 128 |
if props: |
| 129 |
interestingProps = { |
| 130 |
"copyrights": "copyright", |
| 131 |
"designers": "designer", |
| 132 |
"designerURL": "designerURL", |
| 133 |
"trademarks": "trademark", |
| 134 |
"descriptions": "description", |
| 135 |
"licenses": "license", |
| 136 |
"licenseURL": "licenseURL", |
| 137 |
"manufacturers": "manufacturer", |
| 138 |
"manufacturerURL": "manufacturerURL", |
| 139 |
} # Etc |
| 140 |
for glyphsname, attrname in interestingProps.items(): |
| 141 |
thing = props.get(glyphsname, "") |
| 142 |
if isinstance(thing, dict): |
| 143 |
getattr(self.font.names, attrname).copy_in(thing) |
| 144 |
else: |
| 145 |
getattr(self.font.names, attrname).set_default(thing) |
| 146 |
# Do other properties here |
| 147 |
if "vendorID" in props: |
| 148 |
self.font.custom_opentype_values[("OS/2", "achVendID")] = props[ |
| 149 |
"vendorID" |
| 150 |
] |
| 151 |
|
| 152 |
self.font.note = glyphs.pop("note", "") |
| 153 |
self.font.date = datetime.datetime.strptime( |
| 154 |
glyphs.pop("date"), "%Y-%m-%d %H:%M:%S +0000" |
| 155 |
) |
| 156 |
|
| 157 |
def load_axis(self, gaxis): |
| 158 |
axis = Axis(name=gaxis["name"], tag=gaxis["tag"]) |
| 159 |
_stash(axis, gaxis, include=["hidden"]) |
| 160 |
return axis |
| 161 |
|
| 162 |
def load_master(self, gmaster): |
| 163 |
glyphs = self.scratch["plist"] |
| 164 |
master = Master( |
| 165 |
name=gmaster["name"], |
| 166 |
id=gmaster["id"], |
| 167 |
font=self.font, |
| 168 |
guides=[self.load_guide(x) for x in gmaster.pop("guides", [])], |
| 169 |
) |
| 170 |
location = gmaster.pop("axesValues", []) |
| 171 |
master.location = {k.tag: v for k, v in zip(self.font.axes, location)} |
| 172 |
|
| 173 |
kernmaster = master.id |
| 174 |
kerntable = glyphs.get("kerningLTR", {}).get(kernmaster, {}) |
| 175 |
|
| 176 |
master.kerning = self.load_kerning(kerntable) |
| 177 |
# XXX support RTL kerning etc. |
| 178 |
|
| 179 |
_stash(master, gmaster) |
| 180 |
assert master.valid |
| 181 |
return master |
| 182 |
|
| 183 |
def load_glyph(self, gglyph: dict): |
| 184 |
name = gglyph["glyphname"] |
| 185 |
c = gglyph.get("category") |
| 186 |
sc = gglyph.get("subCategory") |
| 187 |
category = None |
| 188 |
if sc == "Ligature": |
| 189 |
category = "ligature" |
| 190 |
if c == "Mark" and sc == "Nonspacing": |
| 191 |
category = "mark" |
| 192 |
cp = self.get_codepoint(gglyph) |
| 193 |
exported = True |
| 194 |
if "export" in gglyph and gglyph.pop("export") == 0: |
| 195 |
exported = False |
| 196 |
g = Glyph(name=name, codepoints=cp or [], category=category, exported=exported) |
| 197 |
g.production_name = gglyph.pop("production", None) |
| 198 |
|
| 199 |
for layer in gglyph.pop("layers", []): |
| 200 |
g.layers.extend(self.load_layer(layer, g)) |
| 201 |
|
| 202 |
_stash(g, gglyph) |
| 203 |
|
| 204 |
return g |
| 205 |
|
| 206 |
def load_layer(self, gslayer: dict, glyph: Glyph, width=None) -> List[Layer]: |
| 207 |
if width is None and "width" in gslayer: |
| 208 |
width = gslayer.pop("width") |
| 209 |
layer = Layer( |
| 210 |
width=width, id=gslayer.pop("layerId", ""), _font=self.font, _glyph=glyph |
| 211 |
) |
| 212 |
layer.vertWidth = gslayer.pop("vertWidth", None) |
| 213 |
layer.name = gslayer.pop("name", "") |
| 214 |
if [x for x in self.font.masters if x.id == layer.id]: |
| 215 |
layer._master = layer.id |
| 216 |
else: |
| 217 |
layer._master = gslayer.pop("associatedMasterId", None) |
| 218 |
layer.guides = [ |
| 219 |
self.load_guide(x) |
| 220 |
for x in gslayer.pop("guideLines", gslayer.pop("guides", [])) |
| 221 |
] |
| 222 |
layer.shapes = [] |
| 223 |
for shape in gslayer.pop("shapes", []): |
| 224 |
layer.shapes.append(self.load_shape(shape)) |
| 225 |
for shape in gslayer.pop("paths", []): |
| 226 |
layer.shapes.append(self.load_path(shape)) |
| 227 |
for shape in gslayer.pop("components", []): |
| 228 |
layer.shapes.append(self.load_component(shape)) |
| 229 |
for anchor in gslayer.pop("anchors", []): |
| 230 |
layer.anchors.append(self.load_anchor(anchor)) |
| 231 |
|
| 232 |
returns = [layer] |
| 233 |
layer.glyph = glyph |
| 234 |
if "background" in gslayer: |
| 235 |
(background,) = self.load_layer( |
| 236 |
gslayer["background"], glyph, width=layer.width |
| 237 |
) |
| 238 |
# If it doesn't have an ID, we need to generate one |
| 239 |
background.id = background.id or str(uuid.uuid1()) |
| 240 |
background.isBackground = True |
| 241 |
|
| 242 |
layer.background = background.id |
| 243 |
returns.append(background) |
| 244 |
for r in returns: |
| 245 |
assert r.valid |
| 246 |
|
| 247 |
_stash(layer, gslayer) |
| 248 |
return returns |
| 249 |
|
| 250 |
def load_guide(self, gguide): |
| 251 |
g = Guide( |
| 252 |
pos=[*gguide.get("pos", (0, 0)), gguide.get("angle", 0)], |
| 253 |
name=gguide.get("name", None), |
| 254 |
) |
| 255 |
if gguide.get("locked"): |
| 256 |
if g.name is None: |
| 257 |
g.name = "" |
| 258 |
g.name += " [locked]" |
| 259 |
_stash(g, gguide) |
| 260 |
return g |
| 261 |
|
| 262 |
def load_anchor(self, ganchor): |
| 263 |
x, y = ganchor.get("pos", (0, 0)) |
| 264 |
return Anchor(name=ganchor["name"], x=x, y=y) |
| 265 |
|
| 266 |
def load_component(self, shape): |
| 267 |
glyphname = shape.pop("ref") |
| 268 |
transform = shape.pop("transform", None) |
| 269 |
if isinstance(transform, str): |
| 270 |
m = re.match(r"^\{(\S+), (\S+), (\S+), (\S+), (\S+), (\S+)\}", transform) |
| 271 |
transform = Transform(*[float(g) for g in m.groups()]) |
| 272 |
c = Shape(ref=glyphname) |
| 273 |
|
| 274 |
if not transform: |
| 275 |
translate = Transform().translate(*shape.pop("pos", (0, 0))) |
| 276 |
scale = Transform().scale(*shape.pop("scale", (1, 1))) |
| 277 |
rotation = Transform().rotate(math.radians(shape.pop("angle", 0))) |
| 278 |
# Compute transform... |
| 279 |
transform = translate.transform(scale).transform(rotation) |
| 280 |
|
| 281 |
c.transform = transform |
| 282 |
_stash(c, shape) |
| 283 |
return c |
| 284 |
|
| 285 |
def load_shape(self, shape): |
| 286 |
if "nodes" in shape: # It's a path |
| 287 |
return self.load_path(shape) |
| 288 |
else: |
| 289 |
return self.load_component(shape) |
| 290 |
|
| 291 |
def load_instance(self, ginstance): |
| 292 |
if ginstance.get("type") == "variable": |
| 293 |
return |
| 294 |
if "axesValues" in ginstance: |
| 295 |
location = ginstance.pop("axesValues") |
| 296 |
instance_location = {k.tag: v for k, v in zip(self.font.axes, location)} |
| 297 |
elif "instanceInterpolations" in ginstance: |
| 298 |
# All right then. |
| 299 |
instance_location = {k.tag: 0 for k in self.font.axes} |
| 300 |
for mId, factor in ginstance.get("instanceInterpolations").items(): |
| 301 |
master_loc = self.font.master(mId).location |
| 302 |
for k in self.font.axes: |
| 303 |
instance_location[k.tag] += master_loc[k.tag] * factor |
| 304 |
else: |
| 305 |
raise ValueError("Need to Synthesize location") |
| 306 |
name = ginstance.pop("name") |
| 307 |
i = Instance( |
| 308 |
name=name, |
| 309 |
styleName=name, |
| 310 |
location=instance_location, |
| 311 |
) |
| 312 |
props = ginstance.pop("properties", []) |
| 313 |
for prop in props: |
| 314 |
if prop["key"] == "familyNames": |
| 315 |
for value in prop["values"]: |
| 316 |
i.familyName[value["language"]] = value["value"] |
| 317 |
|
| 318 |
_stash(i, ginstance) |
| 319 |
return i |
| 320 |
|
| 321 |
def load_path(self, path): |
| 322 |
shape = Shape() |
| 323 |
shape.nodes = [Node(*n) for n in path["nodes"]] |
| 324 |
shape.closed = path["closed"] |
| 325 |
_stash(shape, path) |
| 326 |
if len(shape.nodes): |
| 327 |
# Bring it to front |
| 328 |
shape.nodes = shape.nodes[-1:] + shape.nodes[:-1] |
| 329 |
return shape |
| 330 |
|
| 331 |
def get_codepoint(self, gglyph): |
| 332 |
cp = gglyph.pop("unicode", None) |
| 333 |
if cp is not None and not isinstance(cp, list): |
| 334 |
cp = [cp] |
| 335 |
if cp: |
| 336 |
return [int(x) for x in cp] |
| 337 |
|
| 338 |
def interpret_kern_groups(self): |
| 339 |
for g in self.font.glyphs: |
| 340 |
left_group = _g(g, "kernLeft", pop=True) |
| 341 |
if left_group: |
| 342 |
self.font.second_kern_groups.setdefault(left_group, []).append(g.name) |
| 343 |
|
| 344 |
right_group = _g(g, "kernRight", pop=True) |
| 345 |
if right_group: |
| 346 |
self.font.first_kern_groups.setdefault(right_group, []).append(g.name) |
| 347 |
|
| 348 |
def interpret_linked_kerning(self): |
| 349 |
name_to_master = {m.name.get_default(): m for m in self.font.masters} |
| 350 |
for master in self.font.masters: |
| 351 |
kernmaster = None |
| 352 |
if _stashed_cp(master, "Link Metrics With First Master"): |
| 353 |
master.kerning = self.font.masters[0].kerning |
| 354 |
elif _stashed_cp(master, "Link Metrics With Master"): |
| 355 |
kernmaster_name = _stashed_cp(master, "Link Metrics With Master") |
| 356 |
kernmaster = name_to_master.get(kernmaster_name) |
| 357 |
if kernmaster: |
| 358 |
master.kerning = kernmaster.kerning |
| 359 |
|
| 360 |
def load_kerning(self, kerndict): |
| 361 |
def ungroup(groupname): |
| 362 |
if groupname[0] != "@": |
| 363 |
return groupname |
| 364 |
return groupname.replace("@MMK_L", "@first_group").replace( |
| 365 |
"@MMK_R", "@second_group" |
| 366 |
) |
| 367 |
|
| 368 |
return { |
| 369 |
(ungroup(left), ungroup(right)): value |
| 370 |
for left, level2 in kerndict.items() |
| 371 |
for right, value in level2.items() |
| 372 |
} |
| 373 |
|
| 374 |
def interpret_metrics(self): |
| 375 |
metrics = _g(self.font, "metrics", []) # Keep stashed |
| 376 |
metric_types = [_metrics_dict_to_name(k) for k in metrics] |
| 377 |
for master in self.font.masters: |
| 378 |
# Glyphs has these values as defaults: |
| 379 |
master.metrics["underlinePosition"] = -100 |
| 380 |
master.metrics["underlineThickness"] = 50 |
| 381 |
|
| 382 |
metric_values = _g(master, "metricValues", [], pop=True) |
| 383 |
master.metrics["italicAngle"] = 0 |
| 384 |
for k, v in zip(metric_types, metric_values): |
| 385 |
pos = v.get("pos", 0) |
| 386 |
master.metrics[k] = pos |
| 387 |
if v.get("over"): |
| 388 |
master.metrics["%s overshoot" % _glyphs_metrics_to_ours(k)] = v[ |
| 389 |
"over" |
| 390 |
] |
| 391 |
|
| 392 |
def interpret_axes(self): |
| 393 |
# The default master in glyphs is either the first master or the |
| 394 |
# one selected by the Variable Font Origin custom parameter |
| 395 |
vfo = _stashed_cp(self.font, "Variable Font Origin") |
| 396 |
if not vfo: |
| 397 |
vfo = self.font.masters[0].id |
| 398 |
|
| 399 |
for master in self.font.masters: |
| 400 |
for axis in self.font.axes: |
| 401 |
thisLoc = master.location[axis.tag] |
| 402 |
if axis.min is None or thisLoc < axis.min: |
| 403 |
axis.min = thisLoc |
| 404 |
if master.id == vfo: |
| 405 |
axis.default = master.location[axis.tag] |
| 406 |
if axis.max is None or thisLoc > axis.max: |
| 407 |
axis.max = thisLoc |
| 408 |
|
| 409 |
def interpret_axis_mappings(self): |
| 410 |
# There may be a "Axis Mappings" custom parameter, if so use that |
| 411 |
axes_by_name = {a.name.get_default(): a for a in self.font.axes} |
| 412 |
|
| 413 |
if mapping := _stashed_cp(self.font, "Axis Mappings"): |
| 414 |
axes_by_tag = {a.tag: a for a in self.font.axes} |
| 415 |
for axistag, axismap in mapping.items(): |
| 416 |
ax = axes_by_tag[axistag] |
| 417 |
ax.map = [] |
| 418 |
for designspace, userspace in axismap.items(): |
| 419 |
ax.map.append((userspace, float(designspace))) |
| 420 |
return |
| 421 |
|
| 422 |
for instance in self.font.instances: |
| 423 |
# instance.location is in designspace |
| 424 |
# The Axis Location custom parameter is in userspace, use |
| 425 |
# this to make the map |
| 426 |
c = ( |
| 427 |
_custom_parameter( |
| 428 |
instance._formatspecific.get("com.glyphsapp", {}), "Axis Location" |
| 429 |
) |
| 430 |
or [] |
| 431 |
) |
| 432 |
# If there isn't an Axis Location, use the weightclass and widthclass |
| 433 |
if not c: |
| 434 |
weightclass = instance._formatspecific.get("com.glyphsapp", {}).get( |
| 435 |
"weightClass", 400 |
| 436 |
) |
| 437 |
if weightclass is not None: |
| 438 |
c.append({"Axis": "Weight", "Location": weightclass}) |
| 439 |
widthclass = instance._formatspecific.get("com.glyphsapp", {}).get( |
| 440 |
"widthClass", 5 |
| 441 |
) |
| 442 |
if widthclass is not None: |
| 443 |
c.append({"Axis": "Width", "Location": widthclass}) |
| 444 |
for loc in c: |
| 445 |
ax = axes_by_name.get(loc["Axis"]) |
| 446 |
if not ax: |
| 447 |
# Maybe we don't have a weight or width but we don't have |
| 448 |
# an axis location either so we synthesised those locations |
| 449 |
continue |
| 450 |
if not ax.map: |
| 451 |
ax.map = [] |
| 452 |
ax.map.append( |
| 453 |
( |
| 454 |
int(loc["Location"]), # The instances location in user space |
| 455 |
instance.location[ax.tag], |
| 456 |
) |
| 457 |
) |
| 458 |
|
| 459 |
def interpret_master_custom_parameters(self): |
| 460 |
for master in self.font.masters: |
| 461 |
cps = _g(master, "customParameters", []) |
| 462 |
new_cps = [] |
| 463 |
for param in cps: |
| 464 |
if param["name"] in CORE_METRICS: |
| 465 |
master.metrics[param["name"]] = param["value"] |
| 466 |
else: |
| 467 |
new_cps.append(param) |
| 468 |
_stash(master, {"customParameters": new_cps}) |
| 469 |
|
| 470 |
def interpret_font_custom_parameters(self): |
| 471 |
cps = _g(self.font, "customParameters", []) |
| 472 |
new_cps = [] |
| 473 |
for param in cps: |
| 474 |
if param["name"] == "panose": |
| 475 |
self.font.custom_opentype_values[("OS/2", "panose")] = param["value"] |
| 476 |
# elif param["name"] == "fsType": |
| 477 |
# self.font.custom_opentype_values[("OS/2", "fsType")] = int( |
| 478 |
# param["value"] |
| 479 |
# ) |
| 480 |
elif param["name"] == "fsSelection": |
| 481 |
self.font.custom_opentype_values[("OS/2", "fsSelection")] = int( |
| 482 |
param["value"] |
| 483 |
) |
| 484 |
else: |
| 485 |
new_cps.append(param) |
| 486 |
_stash(self.font, {"customParameters": new_cps}) |
| 487 |
|
| 488 |
def interpret_features(self): |
| 489 |
self.font.features = Features() |
| 490 |
|
| 491 |
def code_with_notes(feature): |
| 492 |
code = feature["code"] |
| 493 |
if "disabled" in feature: |
| 494 |
code = "# Disabled\n# " + code.replace("\n", "\n# ") |
| 495 |
if "automatic" in feature: |
| 496 |
code = "# Automatic\n" + code |
| 497 |
if "labels" in feature: |
| 498 |
code += "\n".join(labels_to_feature(feature["labels"])) |
| 499 |
|
| 500 |
return code |
| 501 |
|
| 502 |
for glyphclass in _g(self.font, "classes", [], pop=True): |
| 503 |
# Beware of tokens XXX |
| 504 |
self.font.features.classes[glyphclass["name"]] = glyphclass["code"].split() |
| 505 |
for prefix in _g(self.font, "featurePrefixes", [], pop=True): |
| 506 |
self.font.features.prefixes[prefix["name"]] = code_with_notes(prefix) |
| 507 |
for feature in _g(self.font, "features", [], pop=True): |
| 508 |
tag = feature.get("tag", feature.get("name")) |
| 509 |
self.font.features.features.append((tag, code_with_notes(feature))) |
| 510 |
|
| 511 |
def _save(self): |
| 512 |
font = self.font |
| 513 |
out = _moveformatspecific(font) |
| 514 |
self.glyphs = out |
| 515 |
out["versionMajor"], out["versionMinor"] = font.version |
| 516 |
out[".formatVersion"] = 3 |
| 517 |
out["unitsPerEm"] = font.upm |
| 518 |
if font.note: |
| 519 |
out["note"] = font.note |
| 520 |
if font.date: |
| 521 |
out["date"] = font.date.strftime("%Y-%m-%d %H:%M:%S +0000") |
| 522 |
out["familyName"] = font.names.familyName.default_or_dict() |
| 523 |
out["axes"] = [self.save_axis(ax) for ax in self.font.axes] |
| 524 |
|
| 525 |
# Sort out the metrics order, using "my" names |
| 526 |
metrics_order = _g(font, "metrics", []) |
| 527 |
# Ensure we have all the metrics |
| 528 |
for m in font.masters: |
| 529 |
for k in m.metrics.keys(): |
| 530 |
if k in custom_parameter_metrics: |
| 531 |
continue |
| 532 |
if k.endswith(" overshoot"): |
| 533 |
continue # We'll write it into the other metric |
| 534 |
k = _metrics_name_to_dict(k) |
| 535 |
if k not in metrics_order: |
| 536 |
metrics_order.append(k) |
| 537 |
|
| 538 |
out["metrics"] = metrics_order |
| 539 |
|
| 540 |
out["fontMaster"] = [self.save_master(m) for m in self.font.masters] |
| 541 |
out["glyphs"] = [self.save_glyph(g) for g in self.font.glyphs] |
| 542 |
instances = [self.save_instance(i) for i in self.font.instances] |
| 543 |
if instances: |
| 544 |
out["instances"] = instances |
| 545 |
|
| 546 |
kerntables = OrderedDict() |
| 547 |
for master in self.font.masters: |
| 548 |
table = self.save_kerning(master.kerning) |
| 549 |
if table: |
| 550 |
kerntables[master.id] = table |
| 551 |
if kerntables: |
| 552 |
out["kerningLTR"] = kerntables |
| 553 |
|
| 554 |
self.save_metadata(out) |
| 555 |
self.save_custom_parameters(out) |
| 556 |
self.save_features(out) |
| 557 |
|
| 558 |
with open(self.filename, "wb") as file: |
| 559 |
openstep_plist.dump(out, file, indent=0, single_line_tuples=True) |
| 560 |
file.write(b"\n") |
| 561 |
|
| 562 |
def save_axis(self, axis): |
| 563 |
gaxis = _moveformatspecific(axis) |
| 564 |
_copyattrs(axis, gaxis, ["name", "tag"]) |
| 565 |
return gaxis |
| 566 |
|
| 567 |
def save_kerning(self, kerntable): |
| 568 |
newtable = {} |
| 569 |
for (left, right), val in kerntable.items(): |
| 570 |
left = left.replace("@first_group", "@MMK_L").replace( |
| 571 |
"@second_group", "@MMK_R" |
| 572 |
) |
| 573 |
right = right.replace("@first_group", "@MMK_L").replace( |
| 574 |
"@second_group", "@MMK_R" |
| 575 |
) |
| 576 |
newtable.setdefault(left, {})[right] = val |
| 577 |
return newtable |
| 578 |
|
| 579 |
def save_master(self, master): |
| 580 |
gmaster = _moveformatspecific(master) |
| 581 |
if master.location: |
| 582 |
gmaster["axesValues"] = list(master.location.values()) |
| 583 |
gmaster["metricValues"] = [] |
| 584 |
if "customParameters" not in gmaster: |
| 585 |
gmaster["customParameters"] = [] |
| 586 |
for metric in custom_parameter_metrics: |
| 587 |
if metric in self.font.default_master.metrics: |
| 588 |
gmaster["customParameters"].append( |
| 589 |
{ |
| 590 |
"name": metric, |
| 591 |
"value": self.font.default_master.metrics[metric], |
| 592 |
} |
| 593 |
) |
| 594 |
if not gmaster["customParameters"]: |
| 595 |
del gmaster["customParameters"] |
| 596 |
|
| 597 |
for k in self.glyphs["metrics"]: |
| 598 |
metric = {} |
| 599 |
pos = master.metrics.get(_metrics_dict_to_name(k)) |
| 600 |
over = master.metrics.get(_metrics_dict_to_name(k) + " overshoot") |
| 601 |
if pos: |
| 602 |
metric["pos"] = pos |
| 603 |
if over: |
| 604 |
metric["over"] = over |
| 605 |
gmaster["metricValues"].append(metric) |
| 606 |
if master.guides: |
| 607 |
gmaster["guides"] = [self.save_guide(g) for g in master.guides] |
| 608 |
_copyattrs(master, gmaster, ["name", "id"], convertor=str) |
| 609 |
return gmaster |
| 610 |
|
| 611 |
def save_guide(self, guide): |
| 612 |
gguide = _moveformatspecific(guide) |
| 613 |
gguide["pos"] = tuple(guide.pos[0:2]) |
| 614 |
if guide.pos[2]: |
| 615 |
gguide["angle"] = guide.pos[2] |
| 616 |
return gguide |
| 617 |
|
| 618 |
def save_glyph(self, glyph): |
| 619 |
gglyph = _moveformatspecific(glyph) |
| 620 |
gglyph["glyphname"] = glyph.name |
| 621 |
if len(glyph.codepoints) == 1: |
| 622 |
# if glyph.codepoints[0] < 256: |
| 623 |
gglyph["unicode"] = glyph.codepoints[0] |
| 624 |
# else: |
| 625 |
# gglyph["unicode"] = "%04x" % glyph.codepoints[0] |
| 626 |
elif len(glyph.codepoints) > 1: |
| 627 |
gglyph["unicode"] = glyph.codepoints |
| 628 |
gglyph["layers"] = [ |
| 629 |
self.save_layer(layer) for layer in glyph.layers if not layer.isBackground |
| 630 |
] |
| 631 |
if glyph.production_name is not None and glyph.production_name != glyph.name: |
| 632 |
gglyph["production"] = glyph.production_name |
| 633 |
if not glyph.exported: |
| 634 |
gglyph["export"] = 0 |
| 635 |
# Check for kern groups |
| 636 |
for group, members in self.font.second_kern_groups.items(): |
| 637 |
if glyph.name in members: |
| 638 |
gglyph["kernLeft"] = group |
| 639 |
for group, members in self.font.first_kern_groups.items(): |
| 640 |
if glyph.name in members: |
| 641 |
gglyph["kernRight"] = group |
| 642 |
# XXX |
| 643 |
return gglyph |
| 644 |
|
| 645 |
def save_layer(self, layer): |
| 646 |
glayer = _moveformatspecific(layer) |
| 647 |
_copyattrs(layer, glayer, ["width", "name"]) |
| 648 |
if layer.vertWidth is not None: |
| 649 |
glayer["vertWidth"] = layer.vertWidth |
| 650 |
glayer["layerId"] = str(layer.id) |
| 651 |
if layer.guides: |
| 652 |
glayer["guides"] = [self.save_guide(g) for g in layer.guides] |
| 653 |
if layer.shapes: |
| 654 |
glayer["shapes"] = [self.save_shape(s) for s in layer.shapes] |
| 655 |
if layer._master and layer._master != layer.id: |
| 656 |
glayer["associatedMasterId"] = layer._master |
| 657 |
if layer.anchors: |
| 658 |
glayer["anchors"] = [self.save_anchor(a) for a in layer.anchors] |
| 659 |
if layer.background: |
| 660 |
glayer["background"] = self.save_layer(layer._background_layer()) |
| 661 |
if "width" in glayer["background"]: |
| 662 |
del glayer["background"]["width"] |
| 663 |
if "layerId" in glayer["background"]: |
| 664 |
del glayer["background"]["layerId"] |
| 665 |
return glayer |
| 666 |
|
| 667 |
def save_shape(self, shape): |
| 668 |
gshape = _moveformatspecific(shape) |
| 669 |
if shape.is_path: |
| 670 |
gshape["closed"] = shape.closed |
| 671 |
outputnodes = [] |
| 672 |
if len(shape.nodes): |
| 673 |
# Put front back at end |
| 674 |
outputnodes = shape.nodes[1:] + [shape.nodes[0]] |
| 675 |
|
| 676 |
gshape["nodes"] = [self.save_node(n) for n in outputnodes] |
| 677 |
else: |
| 678 |
_copyattrs(shape, gshape, ["ref", "angle"]) |
| 679 |
if shape.pos != (0, 0): |
| 680 |
_copyattrs(shape, gshape, ["pos"]) |
| 681 |
if shape.scale != (1, 1): |
| 682 |
_copyattrs(shape, gshape, ["scale"]) |
| 683 |
return gshape |
| 684 |
|
| 685 |
def save_node(self, node): |
| 686 |
if node.userdata: |
| 687 |
return (node.x, node.y, node.type, node.userdata) |
| 688 |
else: |
| 689 |
return (node.x, node.y, node.type) |
| 690 |
|
| 691 |
def save_instance(self, instance): |
| 692 |
ginstance = _moveformatspecific(instance) |
| 693 |
ginstance["name"] = instance.name.get_default() |
| 694 |
ginstance["axesValues"] = [instance.location[ax.tag] for ax in self.font.axes] |
| 695 |
|
| 696 |
return ginstance |
| 697 |
|
| 698 |
def save_anchor(self, anchor): |
| 699 |
ganchor = _moveformatspecific(anchor) |
| 700 |
ganchor["name"] = anchor.name |
| 701 |
ganchor["pos"] = (anchor.x, anchor.y) |
| 702 |
return ganchor |
| 703 |
|
| 704 |
def save_metadata(self, out): |
| 705 |
if self.font.note: |
| 706 |
out["note"] = self.font.note |
| 707 |
if self.font.version: |
| 708 |
out["versionMajor"], out["versionMinor"] = self.font.version |
| 709 |
if "properties" not in out: |
| 710 |
out["properties"] = [] |
| 711 |
props = out["properties"] |
| 712 |
alreadydone = {p["key"] for p in props} |
| 713 |
if self.font.names.copyright and "copyrights" not in alreadydone: |
| 714 |
props.append( |
| 715 |
{ |
| 716 |
"key": "copyrights", |
| 717 |
"values": glyphs_i18ndict(self.font.names.copyright), |
| 718 |
} |
| 719 |
) |
| 720 |
if self.font.names.designer and "designer" not in alreadydone: |
| 721 |
props.append( |
| 722 |
{"key": "designer", "values": glyphs_i18ndict(self.font.names.designer)} |
| 723 |
) |
| 724 |
if self.font.names.designerURL and "designerURL" not in alreadydone: |
| 725 |
props.append( |
| 726 |
{ |
| 727 |
"key": "designerURL", |
| 728 |
"values": glyphs_i18ndict(self.font.names.designerURL), |
| 729 |
} |
| 730 |
) |
| 731 |
if self.font.custom_opentype_values.get(("OS/2", "achVendID")): |
| 732 |
props.append( |
| 733 |
{ |
| 734 |
"key": "vendorID", |
| 735 |
"value": self.font.custom_opentype_values[("OS/2", "achVendID")], |
| 736 |
} |
| 737 |
) |
| 738 |
if not props: |
| 739 |
del out["properties"] |
| 740 |
|
| 741 |
def save_custom_parameters(self, out): |
| 742 |
if "customParameters" not in out: |
| 743 |
out["customParameters"] = [] |
| 744 |
for (table, field), value in self.font.custom_opentype_values.items(): |
| 745 |
if table == "OS/2" and field == "fsType": |
| 746 |
out["customParameters"].append( |
| 747 |
{"name": "fsType", "value": to_bitfield(int(value))} |
| 748 |
) |
| 749 |
if table == "OS/2" and field == "fsSelection": |
| 750 |
if value & (1 << 7): |
| 751 |
out["customParameters"].append( |
| 752 |
{"name": "Use Typo Metrics", "value": 1} |
| 753 |
) |
| 754 |
if value & (1 << 8): |
| 755 |
out["customParameters"].append( |
| 756 |
{"name": "Has WWS Names", "value": 1} |
| 757 |
) |
| 758 |
if not out["customParameters"]: |
| 759 |
del out["customParameters"] |
| 760 |
|
| 761 |
def save_features(self, out): |
| 762 |
# In truth we should probably steal glyphsLib.builder.features._process_feature_block |
| 763 |
def _save_item(key, value, name): |
| 764 |
item = {} |
| 765 |
item[name] = key |
| 766 |
if value.startswith("# Automatic\n"): |
| 767 |
item["automatic"] = True |
| 768 |
value = re.sub("^# Automatic\n", "", value, flags=re.MULTILINE) |
| 769 |
if value.startswith("# Disabled\n"): |
| 770 |
item["disabled"] = True |
| 771 |
value = re.sub("^#", "", value[10:], flags=re.MULTILINE) |
| 772 |
item["code"] = value |
| 773 |
return item |
| 774 |
|
| 775 |
if self.font.features: |
| 776 |
out["classes"] = [ |
| 777 |
{"name": k, "code": " ".join(v)} |
| 778 |
for k, v in self.font.features.classes.items() |
| 779 |
] |
| 780 |
out["featurePrefixes"] = [ |
| 781 |
_save_item(k, v, "name") for k, v in self.font.features.prefixes.items() |
| 782 |
] |
| 783 |
out["features"] = [ |
| 784 |
_save_item(k, v, "tag") for k, v in self.font.features.features |
| 785 |
] |
| 786 |
else: |
| 787 |
out["classes"] = [] |
| 788 |
out["featurePrefixes"] = [] |
| 789 |
out["features"] = [] |
| 790 |
if not out["classes"]: |
| 791 |
del out["classes"] |
| 792 |
if not out["featurePrefixes"]: |
| 793 |
del out["featurePrefixes"] |
| 794 |
if not out["features"]: |
| 795 |
del out["features"] |