| 1 |
#!/usr/bin/env python |
| 2 |
import logging |
| 3 |
import os |
| 4 |
import sys |
| 5 |
import re |
| 6 |
from argparse import ArgumentParser |
| 7 |
from collections import OrderedDict |
| 8 |
|
| 9 |
import fontTools.feaLib.ast as feaast |
| 10 |
import glyphsLib |
| 11 |
from fontTools.ttLib import TTFont |
| 12 |
from glyphsLib.classes import GSAnchor, GSClass, GSFeature, GSFeaturePrefix, Point |
| 13 |
from lxml import etree |
| 14 |
|
| 15 |
import fontFeatures |
| 16 |
from fontFeatures.feaLib.FontFeatures import add_language_system_statements |
| 17 |
from fontFeatures.ttLib import unparse |
| 18 |
from fontFeatures.ttLib.GDEFUnparser import GDEFUnparser |
| 19 |
|
| 20 |
LOGLEVEL = os.environ.get("LOGLEVEL", "WARNING").upper() |
| 21 |
logging.basicConfig(level=LOGLEVEL) |
| 22 |
|
| 23 |
import warnings |
| 24 |
|
| 25 |
|
| 26 |
def warning_on_one_line(message, category, filename, lineno, file=None, line=None): |
| 27 |
return "# [warning] %s\n" % (message) |
| 28 |
|
| 29 |
|
| 30 |
warnings.formatwarning = warning_on_one_line |
| 31 |
|
| 32 |
def main(args=None): |
| 33 |
parser = ArgumentParser() |
| 34 |
parser.add_argument("source", help="source file to process", metavar="SOURCE") |
| 35 |
parser.add_argument("firstmaster", help="binary font file to process", metavar="TTF") |
| 36 |
parser.add_argument("--no-kerning", help="Don't try to convert kerning", action="store_true") |
| 37 |
parser.add_argument( |
| 38 |
"-o", |
| 39 |
"--output", |
| 40 |
dest="output", |
| 41 |
help="Output source file (defaults to overwriting original)", |
| 42 |
) |
| 43 |
parser.add_argument( |
| 44 |
"--config", default=None, help="config file to process", metavar="CONFIG" |
| 45 |
) |
| 46 |
parser.add_argument("othermasters", help="additional binary masters", metavar="TTF", nargs="*") |
| 47 |
|
| 48 |
args = parser.parse_args(args) |
| 49 |
|
| 50 |
config = {} |
| 51 |
if args.config: |
| 52 |
import json |
| 53 |
|
| 54 |
with open(args.config) as f: |
| 55 |
config = json.load(f) |
| 56 |
|
| 57 |
class Layout2Glyphs: |
| 58 |
def __init__(self, gsfont, ff, args, master=0): |
| 59 |
self.gsfont = gsfont |
| 60 |
self.ff = ff |
| 61 |
self.master = master |
| 62 |
self.args = args |
| 63 |
|
| 64 |
def process(self): |
| 65 |
self.process_gpos() |
| 66 |
|
| 67 |
self.fix_gdef_classes() |
| 68 |
self.add_named_classes() |
| 69 |
self.add_routines_to_feature_prefix() |
| 70 |
self.ensure_mark_mkmk() |
| 71 |
self.add_features_to_glyphs() |
| 72 |
self.add_language_systems() |
| 73 |
self.fix_duplicate_anchors() |
| 74 |
|
| 75 |
def process_gpos(self): |
| 76 |
for feature in ["mark", "mkmk", "abvm", "blwm", "dist"]: |
| 77 |
if feature in self.ff.features: |
| 78 |
self.add_anchors(feature) |
| 79 |
for feature in ["kern", "dist"]: |
| 80 |
if feature in ff.features and not args.no_kerning: |
| 81 |
self.add_kerning(feature) |
| 82 |
|
| 83 |
|
| 84 |
def add_anchor_to_glyph(self, glyphname, anchor_name, pos): |
| 85 |
anchor = GSAnchor(name=anchor_name, position=Point(*pos)) |
| 86 |
glyph = self.gsfont.glyphs[glyphname] |
| 87 |
glyph.layers[self.master].anchors.append(anchor) |
| 88 |
return anchor |
| 89 |
|
| 90 |
def add_anchors(self, feature): |
| 91 |
mark = self.ff.features[feature] |
| 92 |
new_mark = [] |
| 93 |
for rr in mark: |
| 94 |
routine = rr.routine |
| 95 |
delete_me = False |
| 96 |
if "MarkToLigature" in routine.name: |
| 97 |
self.add_mark_lig_anchors(routine.name, routine.comments[2:-1]) |
| 98 |
delete_me = True |
| 99 |
else: |
| 100 |
delete_me = self.add_anchors_routine(routine) |
| 101 |
if not delete_me: |
| 102 |
new_mark.append(rr) |
| 103 |
else: |
| 104 |
del self.ff.routines[self.ff.routines.index(routine)] |
| 105 |
self.ff.features[feature] = new_mark |
| 106 |
|
| 107 |
def add_anchors_routine(self, routine): |
| 108 |
delete_me = False |
| 109 |
for rule in routine.rules: |
| 110 |
if isinstance(rule, fontFeatures.Attachment): |
| 111 |
delete_me = True |
| 112 |
if "Cursive" in routine.name: |
| 113 |
anchor_name = "entry" |
| 114 |
else: |
| 115 |
anchor_name = rule.base_name |
| 116 |
for base, pos in rule.bases.items(): |
| 117 |
self.add_anchor_to_glyph(base, anchor_name, pos) |
| 118 |
if "Cursive" in routine.name: |
| 119 |
anchor_name = "exit" |
| 120 |
else: |
| 121 |
anchor_name = "_"+rule.base_name |
| 122 |
for mark, pos in rule.marks.items(): |
| 123 |
self.add_anchor_to_glyph(mark, anchor_name, pos) |
| 124 |
return delete_me |
| 125 |
|
| 126 |
def add_kern(self, left, right, val): |
| 127 |
old_val = self.gsfont.kerningForPair( |
| 128 |
self.gsfont.masters[self.master].id, |
| 129 |
left, |
| 130 |
right, |
| 131 |
) |
| 132 |
if old_val == self.gsfont.EMPTY_KERNING_VALUE: |
| 133 |
old_val = 0 |
| 134 |
else: |
| 135 |
print("Adding %i to existing kern %s/%s=%i" % (val, left, right, old_val)) |
| 136 |
if not val: |
| 137 |
return |
| 138 |
self.gsfont.setKerningForPair( |
| 139 |
self.gsfont.masters[self.master].id, |
| 140 |
left, |
| 141 |
right, |
| 142 |
old_val + val |
| 143 |
) |
| 144 |
|
| 145 |
def add_kerning(self, feature): |
| 146 |
kern = self.ff.features[feature] |
| 147 |
new_kern = [] |
| 148 |
for rr in kern: |
| 149 |
routine = rr.routine |
| 150 |
delete_me = False |
| 151 |
pairs = set() |
| 152 |
for rule in routine.rules: |
| 153 |
if isinstance(rule, fontFeatures.Positioning): |
| 154 |
# Is it pair positioning |
| 155 |
if len(rule.glyphs) != 2: |
| 156 |
break |
| 157 |
# Is it a simple kern? |
| 158 |
if not (rule.valuerecords[0] and not rule.valuerecords[1]): |
| 159 |
continue |
| 160 |
if not rule.valuerecords[0].xAdvance: |
| 161 |
continue |
| 162 |
if rule.valuerecords[0].xPlacement or rule.valuerecords[0].yPlacement: |
| 163 |
continue |
| 164 |
for left in rule.glyphs[0]: |
| 165 |
for right in rule.glyphs[1]: |
| 166 |
if (left, right) in pairs: |
| 167 |
continue |
| 168 |
pairs.add((left,right)) |
| 169 |
self.add_kern(left, right, rule.valuerecords[0].xAdvance) |
| 170 |
print( |
| 171 |
"# Kerning %s %s = %i" |
| 172 |
% (left, right, rule.valuerecords[0].xAdvance) |
| 173 |
) |
| 174 |
delete_me = True |
| 175 |
|
| 176 |
if not delete_me: |
| 177 |
new_kern.append(rr) |
| 178 |
elif routine in ff.routines: |
| 179 |
del ff.routines[ff.routines.index(routine)] |
| 180 |
ff.features[feature] = new_kern |
| 181 |
|
| 182 |
def add_mark_lig_anchors(self, name, xml): |
| 183 |
xml = "\n".join([re.sub(r"#\s+", "", c) for c in xml]) |
| 184 |
tree = etree.fromstring(xml) |
| 185 |
marks = [x.get("value") for x in tree.xpath("//*/MarkCoverage/Glyph")] |
| 186 |
ligs = [x.get("value") for x in tree.xpath("//*/LigatureCoverage/Glyph")] |
| 187 |
array = tree.xpath("//*/LigatureArray")[0] |
| 188 |
for ligature, attach in zip(ligs, array.iter("LigatureAttach")): |
| 189 |
for ix, cr in enumerate(attach.iter("ComponentRecord")): |
| 190 |
for markclass, anchor in enumerate(cr.iter("LigatureAnchor")): |
| 191 |
x = int(anchor.xpath(".//XCoordinate")[0].get("value")) |
| 192 |
y = int(anchor.xpath(".//YCoordinate")[0].get("value")) |
| 193 |
anchor_name = name+f"_class{markclass}_"+str(1 + ix) |
| 194 |
self.add_anchor_to_glyph(ligature, anchor_name, (x,y)) |
| 195 |
|
| 196 |
array = tree.xpath("//*/MarkArray")[0] |
| 197 |
for mark, attach in zip(marks, array.iter("MarkRecord")): |
| 198 |
markclass = int(attach.find("Class").get("value")) |
| 199 |
anchor_name = "_"+name+f"_class{markclass}" |
| 200 |
x = int(attach.xpath(".//XCoordinate")[0].get("value")) |
| 201 |
y = int(attach.xpath(".//YCoordinate")[0].get("value")) |
| 202 |
anchor = self.add_anchor_to_glyph(mark, anchor_name, (x,y)) |
| 203 |
|
| 204 |
def fix_gdef_classes(self): |
| 205 |
for glyph, cat in self.ff.glyphclasses.items(): |
| 206 |
if cat == "mark": |
| 207 |
self.gsfont.glyphs[glyph].category = "Mark" |
| 208 |
if self.gsfont.glyphs[glyph].layers[0].width == 0: |
| 209 |
self.gsfont.glyphs[glyph].subCategory = "Nonspacing" |
| 210 |
else: |
| 211 |
self.gsfont.glyphs[glyph].subCategory = "Spacing Combining" |
| 212 |
if cat == "ligature": |
| 213 |
self.gsfont.glyphs[glyph].category = "Letter" |
| 214 |
self.gsfont.glyphs[glyph].subCategory = "Ligature" |
| 215 |
|
| 216 |
def add_named_classes(self): |
| 217 |
ff.asFea() |
| 218 |
for cls, members in self.ff.namedClasses.items(): |
| 219 |
self.gsfont.classes.append(GSClass(name=cls, code=" ".join(members))) |
| 220 |
|
| 221 |
def add_feature_prefix(self, routine): |
| 222 |
self.gsfont.featurePrefixes.append( |
| 223 |
GSFeaturePrefix(name=routine.name, code=routine.asFea()) |
| 224 |
) |
| 225 |
|
| 226 |
def add_routines_to_feature_prefix(self): |
| 227 |
# Lookups go into prefix, in order of dependency |
| 228 |
queue = list(self.ff.routines) |
| 229 |
seen = {} |
| 230 |
while queue: |
| 231 |
for dep in queue[0].dependencies: |
| 232 |
if dep not in seen: |
| 233 |
queue.insert(0, dep) |
| 234 |
routine = queue.pop(0) |
| 235 |
if routine not in seen: |
| 236 |
self.add_feature_prefix(routine) |
| 237 |
seen[routine] = True |
| 238 |
|
| 239 |
def ensure_mark_mkmk(self): |
| 240 |
# Work around https://github.com/googlefonts/ufo2ft/issues/506 |
| 241 |
if "mark" not in self.ff.features and "mkmk" in self.ff.features: |
| 242 |
newfeatures = OrderedDict() |
| 243 |
for k, v in self.ff.features.items(): |
| 244 |
if k == "mkmk": |
| 245 |
newfeatures["mark"] = [] |
| 246 |
newfeatures[k] = v |
| 247 |
self.ff.features = newfeatures |
| 248 |
|
| 249 |
def add_features_to_glyphs(self): |
| 250 |
for featuretag, routines in self.ff.features.items(): |
| 251 |
code = "\n".join([ |
| 252 |
f"# {routine.languages}\n"+ |
| 253 |
routine.asFea() for routine in routines |
| 254 |
]) |
| 255 |
if featuretag in ["mark", "mkmk", "dist", "kern", "abvm", "blwm"]: |
| 256 |
code = "# Automatic Code Start\n" + code |
| 257 |
self.gsfont.features.append(GSFeature(name=featuretag, code=code)) |
| 258 |
|
| 259 |
def add_language_systems(self): |
| 260 |
code = "" |
| 261 |
for script, langs in self.ff.scripts_and_languages.items(): |
| 262 |
for lang in langs: |
| 263 |
code += f"languagesystem {script} {lang};\n" |
| 264 |
self.gsfont.featurePrefixes.append(GSFeaturePrefix(name="Languagesystems", code=code)) |
| 265 |
|
| 266 |
def fix_duplicate_anchors(self): |
| 267 |
# Get names of all anchors |
| 268 |
glyphs_with_anchor = {} |
| 269 |
for g in self.gsfont.glyphs: |
| 270 |
for l in g.layers: |
| 271 |
for a in l.anchors: |
| 272 |
glyphs_with_anchor.setdefault(a.name, set()).add(g.name) |
| 273 |
|
| 274 |
our_anchors = [a for a in glyphs_with_anchor.keys() if "Anchor" in a] |
| 275 |
their_anchors = [a for a in glyphs_with_anchor.keys() if "Anchor" not in a] |
| 276 |
drop_anchors = set() |
| 277 |
if their_anchors: |
| 278 |
for theirs in their_anchors: |
| 279 |
for ours in our_anchors: |
| 280 |
if glyphs_with_anchor[theirs] != glyphs_with_anchor[ours]: |
| 281 |
continue |
| 282 |
same = True |
| 283 |
for g in glyphs_with_anchor[theirs]: |
| 284 |
for l in self.gsfont.glyphs[g].layers: |
| 285 |
if not l.anchors[theirs]: |
| 286 |
print("Bad anchor %s in %s" % (theirs, l)) |
| 287 |
same = False |
| 288 |
elif not l.anchors[ours]: |
| 289 |
print("Bad anchor %s in %s" % (ours, l)) |
| 290 |
same = False |
| 291 |
elif l.anchors[theirs].position != l.anchors[ours].position: |
| 292 |
same = False |
| 293 |
if not same: |
| 294 |
continue |
| 295 |
print("Our anchor '%s' was duplicate of original source '%s'" % (ours, theirs)) |
| 296 |
drop_anchors.add(ours) |
| 297 |
break |
| 298 |
|
| 299 |
for to_drop in drop_anchors: |
| 300 |
for glyph in glyphs_with_anchor[to_drop]: |
| 301 |
for l in self.gsfont.glyphs[glyph].layers: |
| 302 |
del l.anchors[to_drop] |
| 303 |
|
| 304 |
gsfont = glyphsLib.load(open(args.source)) |
| 305 |
|
| 306 |
font = TTFont(args.firstmaster) |
| 307 |
|
| 308 |
ff = unparse(font, do_gdef=True, doLookups=True, config=config) |
| 309 |
|
| 310 |
Layout2Glyphs(gsfont, ff, args).process() |
| 311 |
|
| 312 |
for ix, master in enumerate(args.othermasters): |
| 313 |
print("%s -> %i" % (master, ix+1)) |
| 314 |
font = TTFont(master) |
| 315 |
ff = unparse(font, do_gdef=True, doLookups=True, config=config) |
| 316 |
Layout2Glyphs(gsfont, ff, args, master=ix+1).process_gpos() |
| 317 |
|
| 318 |
if not args.output: |
| 319 |
args.output = args.source |
| 320 |
gsfont.save(args.output) |
| 321 |
print(f"Saved {args.output}") |
| 322 |
|
| 323 |
if __name__ == "__main__": |
| 324 |
main() |