| 1 |
import re |
| 2 |
from fontFeatures import ( |
| 3 |
FontFeatures, |
| 4 |
Chaining, |
| 5 |
Routine, |
| 6 |
Substitution, |
| 7 |
Positioning, |
| 8 |
Attachment, |
| 9 |
) |
| 10 |
from fontTools.ttLib import TTFont |
| 11 |
from collections import OrderedDict |
| 12 |
from fontTools.feaLib.ast import ValueRecord |
| 13 |
import warnings |
| 14 |
|
| 15 |
|
| 16 |
class FontDameParser: |
| 17 |
"""Convert layout files in Monotype's FontDame format to fontFeatures. |
| 18 |
|
| 19 |
Args: |
| 20 |
lines: An array of strings containing the FontDame file, one line per string. |
| 21 |
config: A dictionary of glyph class names. |
| 22 |
glyphset: A list of glyph names in the font. |
| 23 |
""" |
| 24 |
|
| 25 |
def __init__(self, lines, config={}, glyphset=()): |
| 26 |
self.all_languages = [] |
| 27 |
self.lines = lines |
| 28 |
self.script_applications = {} |
| 29 |
self.features = {} |
| 30 |
self.lookups = OrderedDict() |
| 31 |
self.dependencies = {} |
| 32 |
self.classes = [] |
| 33 |
self.config = config |
| 34 |
self.glyphset = glyphset |
| 35 |
self.current_lookup = None |
| 36 |
self.state = "doing_nothing" |
| 37 |
self.ff = FontFeatures() |
| 38 |
self.resetContexts() |
| 39 |
|
| 40 |
def resetContexts(self): |
| 41 |
self.classContexts = {} |
| 42 |
self.backtrackclassContexts = {} |
| 43 |
self.lookaheadclassContexts = {} |
| 44 |
|
| 45 |
def parse(self): |
| 46 |
"""Parses the font file, creating a fontFeatures object. |
| 47 |
|
| 48 |
Returns: A fontFeatures object containing the rules in the FontDame file.""" |
| 49 |
# Parse lookups |
| 50 |
for line in self.lines: |
| 51 |
self.parse_line(line) |
| 52 |
|
| 53 |
# Tidy up lookups |
| 54 |
for lid, lu in self.lookups.items(): |
| 55 |
for rule in lu.rules: |
| 56 |
if not isinstance(rule, Chaining): |
| 57 |
continue |
| 58 |
pretendlookups = rule.lookups |
| 59 |
reallookups = [None] * len(rule.input) |
| 60 |
for i in pretendlookups: |
| 61 |
m = re.match("\\s*(\\S+),\\s*(\\S+)", i) |
| 62 |
if not m: |
| 63 |
raise ValueError("Unparsable lookup chain %s" % i) |
| 64 |
if lid not in self.dependencies: |
| 65 |
self.dependencies[lid] = [] |
| 66 |
self.dependencies[lid].append(m[2]) |
| 67 |
if not reallookups[int(m[1]) - 1]: |
| 68 |
reallookups[int(m[1]) - 1] = [] |
| 69 |
reallookups[int(m[1]) - 1].append(self.lookups[m[2]]) |
| 70 |
rule.lookups = reallookups |
| 71 |
|
| 72 |
# Tie features to languages |
| 73 |
for k, v in self.features.items(): |
| 74 |
v["languages_and_scripts"] = self.script_applications[int(k)] |
| 75 |
|
| 76 |
# Rearrange into features |
| 77 |
self.base_lu_for_feature = {} |
| 78 |
self.toplevel_lookups = set() |
| 79 |
for i in sorted(self.features.keys()): |
| 80 |
feat = self.features[i] |
| 81 |
tag = feat["tag"] |
| 82 |
if "DFLT/default" in feat["languages_and_scripts"]: |
| 83 |
self.base_lu_for_feature[tag] = set(feat["lookups"]) |
| 84 |
lookups = [self.lookups[x] for x in feat["lookups"]] |
| 85 |
else: |
| 86 |
# Set difference |
| 87 |
if tag in self.base_lu_for_feature: |
| 88 |
feat["lookups"] = [ |
| 89 |
item |
| 90 |
for item in feat["lookups"] |
| 91 |
if item not in self.base_lu_for_feature[tag] |
| 92 |
] |
| 93 |
lookups = [self.lookups[x] for x in feat["lookups"]] |
| 94 |
langcode = [ |
| 95 |
self.format_langcode(x.split("/")) |
| 96 |
for x in feat["languages_and_scripts"] |
| 97 |
] |
| 98 |
# Clone the routines just in case |
| 99 |
lookups = [ |
| 100 |
Routine(languages=langcode, rules=lu.rules, flags=lu.flags) |
| 101 |
for lu in lookups |
| 102 |
] |
| 103 |
|
| 104 |
self.ff.addFeature(tag, lookups) |
| 105 |
for lu in feat["lookups"]: |
| 106 |
self.toplevel_lookups.add(lu) |
| 107 |
|
| 108 |
# Delete toplevel lookups from lookup table |
| 109 |
for lookup in self.toplevel_lookups: |
| 110 |
del self.lookups[lookup] |
| 111 |
|
| 112 |
# Rearrange lookups into dependency order |
| 113 |
done = {} |
| 114 |
|
| 115 |
def dolookup(lid): |
| 116 |
if lid in done: |
| 117 |
return |
| 118 |
if lid in self.dependencies: |
| 119 |
for x in self.dependencies[lid]: |
| 120 |
dolookup(x) |
| 121 |
self.ff.routines.append(self.lookups[lid]) |
| 122 |
done[lid] = True |
| 123 |
|
| 124 |
for i in self.lookups.keys(): |
| 125 |
dolookup(i) |
| 126 |
return self.ff |
| 127 |
|
| 128 |
def format_langcode(self, code): |
| 129 |
script, lang = code |
| 130 |
if lang == "default": |
| 131 |
return (script, "dflt") |
| 132 |
return (script, lang) |
| 133 |
|
| 134 |
def parse_line(self, line): |
| 135 |
if line == "\n": |
| 136 |
return |
| 137 |
elif line == "script table begin\n": |
| 138 |
self.state = "reading_script_table" |
| 139 |
return |
| 140 |
elif line == "feature table begin\n": |
| 141 |
self.state = "reading_feature_table" |
| 142 |
return |
| 143 |
elif line == "class definition begin\n": |
| 144 |
self.state = "reading_class_definition" |
| 145 |
return |
| 146 |
elif line == "backtrackclass definition begin\n": |
| 147 |
self.state = "reading_backtrackclass_definition" |
| 148 |
return |
| 149 |
elif line == "lookaheadclass definition begin\n": |
| 150 |
self.state = "reading_lookaheadclass_definition" |
| 151 |
return |
| 152 |
|
| 153 |
elif line == "class definition end\n": |
| 154 |
self.state = "parsing_lookup" |
| 155 |
return |
| 156 |
elif line == "feature table end\n": |
| 157 |
self.state = "doing_nothing" |
| 158 |
return |
| 159 |
elif line.startswith("lookup end"): |
| 160 |
self.end_lookup() |
| 161 |
self.state = "doing_nothing" |
| 162 |
return |
| 163 |
elif line == "script table end\n": |
| 164 |
self.state = "doing_nothing" |
| 165 |
return |
| 166 |
elif line.startswith("lookup"): |
| 167 |
self.parse_lookup_header(line) |
| 168 |
self.state = "parsing_lookup" |
| 169 |
return |
| 170 |
if line.startswith("#") or line.startswith("%"): |
| 171 |
return |
| 172 |
|
| 173 |
if self.state == "reading_script_table": |
| 174 |
self.add_to_script_table(line) |
| 175 |
elif self.state == "reading_feature_table": |
| 176 |
self.add_to_feature_table(line) |
| 177 |
elif self.state == "parsing_lookup": |
| 178 |
self.add_to_lookup(line) |
| 179 |
elif self.state == "reading_class_definition": |
| 180 |
self.add_to_class_definition("class", line) |
| 181 |
elif self.state == "reading_backtrackclass_definition": |
| 182 |
self.add_to_class_definition("backtrackclass", line) |
| 183 |
elif self.state == "reading_lookaheadclass_definition": |
| 184 |
self.add_to_class_definition("lookaheadclass", line) |
| 185 |
|
| 186 |
def add_to_script_table(self, line): |
| 187 |
m = re.match(r"^(\w+)\s+(\w+)\s+(.*)$", line) |
| 188 |
lang = m[1] + "/" + m[2] |
| 189 |
self.all_languages.append(lang) |
| 190 |
for f in re.split(r",\s*", m[3]): |
| 191 |
f = int(f) |
| 192 |
if f not in self.script_applications: |
| 193 |
self.script_applications[f] = [] |
| 194 |
self.script_applications[f].append(lang) |
| 195 |
|
| 196 |
def add_to_feature_table(self, line): |
| 197 |
m = re.match(r"^(\w+)\s+(\w+)\s+(.*)$", line) |
| 198 |
self.features[int(m[1])] = { |
| 199 |
"tag": m[2], |
| 200 |
"lookups": re.split(r",\s*", m[3]), |
| 201 |
} |
| 202 |
|
| 203 |
def end_lookup(self): |
| 204 |
# print("Parsed lookup %s" % self.current_lookup.name) |
| 205 |
# Optimizer().optimize_routine(self.current_lookup) |
| 206 |
self.current_lookup = None |
| 207 |
self.resetContexts() |
| 208 |
|
| 209 |
def parse_lookup_header(self, line): |
| •210 |
m = re.match(r"^lookup\s+([\w-]+)\s+(.*)$", line) |
| 211 |
if not m: |
| 212 |
raise ValueError("Unparsable lookup header: |%s|" % line) |
| 213 |
self.current_lookup = Routine(name="lookup_%s" % m[1]) |
| 214 |
self.lookups[m[1]] = self.current_lookup |
| 215 |
self.current_lookup_type = m[2] |
| 216 |
|
| 217 |
def get_class(self, cid, lookup): |
| 218 |
res = lookup["classes"][cid] |
| 219 |
if len(res) == 1: |
| 220 |
return res[0] |
| 221 |
if len(res) > 5: |
| 222 |
if tuple(res) not in self.classes: |
| 223 |
self.classes.append(tuple(res)) |
| 224 |
classname = "@class%i" % self.classes.index(tuple(res)) |
| 225 |
if classname in self.config: |
| 226 |
return self.config[classname] |
| 227 |
return classname |
| 228 |
|
| 229 |
return res |
| 230 |
|
| 231 |
def append_lookup_flag(self, flag): |
| 232 |
if flag == "IgnoreMarks": |
| 233 |
parsedflag = 8 |
| 234 |
elif flag == "IgnoreLigatures": |
| 235 |
parsedflag = 4 |
| 236 |
elif flag == "IgnoreBaseGlyphs": |
| 237 |
parsedflag = 2 |
| 238 |
elif flag == "RightToLeft": |
| 239 |
parsedflag = 1 |
| 240 |
elif re.match("^mat(\\d+)$", flag): |
| 241 |
parsedflag = int(flag[3:]) << 8 |
| 242 |
else: |
| 243 |
print("Unknown flag %s" % flag) |
| 244 |
self.current_lookup.flags = self.current_lookup.flags | parsedflag |
| 245 |
|
| 246 |
def add_subst(self, in_, out_): |
| 247 |
self.current_lookup.addRule(Substitution(in_, out_)) |
| 248 |
|
| 249 |
def add_chain_simple(self, context, lookups): |
| 250 |
self.current_lookup.addRule(Chaining(context, lookups=lookups)) |
| 251 |
|
| 252 |
def add_cursive(self, entryexit, glyph, pos): |
| 253 |
if len(self.current_lookup.rules) == 0: |
| 254 |
self.current_lookup.addRule(Attachment("cursive_entry", "")) |
| 255 |
rule = self.current_lookup.rules[-1] |
| 256 |
if entryexit == "entry": |
| 257 |
rule.bases[glyph] = pos |
| 258 |
else: |
| 259 |
rule.marks[glyph] = pos |
| 260 |
|
| 261 |
def add_single_pos_x(self, glyph, xa): |
| 262 |
self.current_lookup.addRule(Positioning([[glyph]], [ValueRecord(xAdvance=xa)])) |
| 263 |
|
| 264 |
def add_single_pos_x_placement(self, glyph, xp): |
| 265 |
self.current_lookup.addRule( |
| 266 |
Positioning([[glyph]], [ValueRecord(xPlacement=xp)]) |
| 267 |
) |
| 268 |
|
| 269 |
def add_single_pos_y_placement(self, glyph, yp): |
| 270 |
self.current_lookup.addRule( |
| 271 |
Positioning([[glyph]], [ValueRecord(xPlacement=yp)]) |
| 272 |
) |
| 273 |
|
| 274 |
def add_pair(self, glyph1, glyph2, xa): |
| 275 |
self.current_lookup.addRule( |
| 276 |
Positioning( |
| 277 |
[[glyph1], [glyph2]], [ValueRecord(xPlacement=xa), ValueRecord()] |
| 278 |
) |
| 279 |
) |
| 280 |
|
| 281 |
def add_attach(self, entryexit, glyph, pos): |
| 282 |
if len(self.current_lookup.rules) == 0: |
| 283 |
self.current_lookup.addRule( |
| 284 |
Attachment( |
| 285 |
self.current_lookup.name + "_BS", self.current_lookup.name + "_MK" |
| 286 |
) |
| 287 |
) |
| 288 |
rule = self.current_lookup.rules[-1] |
| 289 |
if entryexit == "base": |
| 290 |
rule.bases[glyph] = pos |
| 291 |
else: |
| 292 |
rule.marks[glyph] = pos |
| 293 |
|
| 294 |
def add_to_lookup(self, line): |
| •295 |
m = re.match(r"(\w+)\s+(yes|no)", line) |
| 296 |
if m: |
| 297 |
if m[2] == "yes": |
| 298 |
self.append_lookup_flag(m[1]) |
| 299 |
return |
| •300 |
m = re.match(r"MarkAttachmentType\s+(\d+)", line, flags=re.IGNORECASE) |
| 301 |
if m: |
| 302 |
self.append_lookup_flag("mat" + m[1]) |
| 303 |
return |
| 304 |
|
| 305 |
if self.current_lookup_type == "single": |
| 306 |
m = re.match(r"x advance\s+([\w\.-]+)\s+(-?\d+)\n", line) |
| 307 |
if m: |
| 308 |
self.add_single_pos_x(m[1], int(m[2])) |
| 309 |
return |
| 310 |
m = re.match(r"y placement\s+([\w\.-]+)\s+(-?\d+)\n", line) |
| 311 |
if m: |
| 312 |
self.add_single_pos_y_placement(m[1], int(m[2])) |
| 313 |
return |
| 314 |
m = re.match(r"x placement\s+([\w\.-]+)\s+(-?\d+)\n", line) |
| 315 |
if m: |
| 316 |
self.add_single_pos_x_placement(m[1], int(m[2])) |
| 317 |
return |
| •318 |
m = re.match(r"([\w.-]+)\s+([\w\\.-]+)\n", line) |
| 319 |
if not m: |
| 320 |
warnings.warn("Odd single lookup: %s" % line) |
| 321 |
# import code |
| 322 |
|
| 323 |
# code.interact(local=locals()) |
| 324 |
else: |
| 325 |
self.add_subst([[m[1]]], [[m[2]]]) |
| 326 |
elif self.current_lookup_type == "pair": |
| 327 |
m = re.match(r"left x advance\s+([\w\.-]+)\s+([\w\.-]+)\s+(-?\d+)\n", line) |
| 328 |
if not m: |
| 329 |
warnings.warn("Odd pair lookup: %s" % line) |
| 330 |
else: |
| 331 |
self.add_pair(m[1], m[2], int(m[3])) |
| 332 |
|
| 333 |
elif self.current_lookup_type == "multiple": |
| •334 |
m = re.match(r"([\w\\.-]+)\s+(.*)\n", line) |
| 335 |
self.add_subst([[m[1]]], [[x] for x in m[2].split("\t")]) |
| 336 |
|
| 337 |
elif self.current_lookup_type == "ligature": |
| •338 |
m = re.match(r"([\w\\.-]+)\s(.*)\n", line) |
| 339 |
if not m: |
| 340 |
raise ValueError("Unparsable line '%s'" % line) |
| 341 |
self.add_subst([[m[2]]], [m[1].split("\t")]) |
| 342 |
|
| 343 |
elif self.current_lookup_type == "cursive": |
| 344 |
m = re.match(r"(entry|exit)\s+(\S+)\s+(-?\d+),(-?\d+).*\n", line) |
| 345 |
if not m: |
| 346 |
raise ValueError("Unparsable cursive '%s'" % line) |
| 347 |
self.add_cursive(m[1], m[2], (int(m[3]), int(m[4]))) |
| 348 |
|
| 349 |
elif ( |
| 350 |
self.current_lookup_type == "mark to base" |
| 351 |
or self.current_lookup_type == "mark to mark" |
| 352 |
): |
| 353 |
m = re.match(r"(mark|base)\s+(\S+)\s+\S+\s+(-?\d+),(-?\d+).*\n", line) |
| 354 |
if not m: |
| 355 |
raise ValueError("Unparsable mark '%s'" % line) |
| 356 |
self.add_attach(m[1], m[2], (int(m[3]), int(m[4]))) |
| 357 |
|
| 358 |
elif self.current_lookup_type == "mark to ligature": |
| 359 |
warnings.warn("Mark to ligature not yet supported") |
| 360 |
|
| 361 |
elif self.current_lookup_type == "context": |
| 362 |
if line.startswith("glyph"): |
| 363 |
m = line.rstrip().split("\t") |
| 364 |
context = [[x] for x in re.split(r",\s*", m[1])] |
| 365 |
self.add_chain_simple(context, m[2:]) |
| 366 |
elif line.startswith("class"): |
| 367 |
m = line.rstrip().split("\t") |
| 368 |
m[1] = m[1].replace(" ", "") |
| 369 |
context = self.make_context(re.split(r",\s*", m[1]), self.classContexts) |
| 370 |
self.add_chain_simple(context, m[2:]) |
| 371 |
elif self.current_lookup_type == "chained": |
| 372 |
if line.startswith("class-chain"): |
| 373 |
m = re.match("class-chain\t([^\t]*)\t([^\t]*)\t([^\t]*)\t(.*)$", line) |
| 374 |
precontext = [] |
| 375 |
if m[1]: |
| 376 |
precontext = self.make_context( |
| 377 |
re.split(r",\s*", m[1]), self.backtrackclassContexts |
| 378 |
) |
| 379 |
precontext = list(reversed(precontext)) |
| 380 |
context = self.make_context(re.split(r",\s*", m[2]), self.classContexts) |
| 381 |
postcontext = [] |
| 382 |
if m[3]: |
| 383 |
postcontext = self.make_context( |
| 384 |
re.split(r",\s*", m[3]), self.lookaheadclassContexts |
| 385 |
) |
| 386 |
lookups = m[4].rstrip().split("\t") |
| 387 |
# print("Lookup %s, lookups = %s" % (self.current_lookup.name, lookups)) |
| 388 |
self.current_lookup.addRule( |
| 389 |
Chaining( |
| 390 |
context, |
| 391 |
precontext=precontext, |
| 392 |
postcontext=postcontext, |
| 393 |
lookups=lookups, |
| 394 |
) |
| 395 |
) |
| 396 |
elif line.startswith("glyph"): |
| 397 |
raise ValueError("GSUB6.1 not supported yet") |
| 398 |
else: |
| 399 |
raise ValueError("Unsupported lookup type |%s|" % self.current_lookup_type) |
| 400 |
|
| 401 |
def make_context(self, classlist, which): |
| 402 |
context = [] |
| 403 |
for x in classlist: |
| 404 |
x = x.strip() |
| 405 |
if x == "0": |
| 406 |
if not self.glyphset: |
| 407 |
raise ValueError( |
| 408 |
"Class 0 in contextual (%s) but I don't know the glyphset" |
| 409 |
% self.current_lookup.name |
| 410 |
) |
| 411 |
else: |
| 412 |
# Class 0 is everything that's not mentioned elsewhere |
| 413 |
members = set(self.glyphset) |
| 414 |
for c in which.values(): |
| 415 |
members = members - set(c) |
| 416 |
else: |
| 417 |
if x not in which: |
| 418 |
print( |
| 419 |
"Couldn't find a class definition for class %s in lookup %s" |
| 420 |
% (x, self.current_lookup.name) |
| 421 |
) |
| 422 |
members = which[x] |
| 423 |
context.append(members) |
| 424 |
return context |
| 425 |
|
| 426 |
def add_to_class_definition(self, which, line): |
| •427 |
m = re.match(r"([\w\.]+)\s+(\d+)", line) |
| 428 |
if not m: |
| 429 |
raise ValueError("Unparsable line '%s'" % line) |
| 430 |
if which == "class": |
| 431 |
which = self.classContexts |
| 432 |
elif which == "backtrackclass": |
| 433 |
which = self.backtrackclassContexts |
| 434 |
elif which == "lookaheadclass": |
| 435 |
which = self.lookaheadclassContexts |
| 436 |
|
| 437 |
if m[2] not in which: |
| 438 |
which[m[2]] = [] |
| 439 |
which[m[2]].append(m[1]) |
| 440 |
|
| 441 |
|
| 442 |
def unparse(filename, config={}, font=None): |
| 443 |
if config: |
| 444 |
import json |
| 445 |
|
| 446 |
with open(config) as f: |
| 447 |
config = json.load(f) |
| 448 |
else: |
| 449 |
config = {} |
| 450 |
if font: |
| 451 |
glyphset = TTFont(font).getGlyphSet().keys() |
| 452 |
else: |
| 453 |
glyphset = () |
| 454 |
with open(filename) as file_in: |
| 455 |
parser = FontDameParser(file_in, config, glyphset) |
| 456 |
parser.parse() |
| 457 |
return parser.ff |