merger.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. """
  2. Merge OpenType Layout tables (GDEF / GPOS / GSUB).
  3. """
  4. import os
  5. import copy
  6. import enum
  7. from operator import ior
  8. import logging
  9. from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache
  10. from fontTools.misc import classifyTools
  11. from fontTools.misc.roundTools import otRound
  12. from fontTools.misc.treeTools import build_n_ary_tree
  13. from fontTools.ttLib.tables import otTables as ot
  14. from fontTools.ttLib.tables import otBase as otBase
  15. from fontTools.ttLib.tables.otConverters import BaseFixedValue
  16. from fontTools.ttLib.tables.otTraverse import dfs_base_table
  17. from fontTools.ttLib.tables.DefaultTable import DefaultTable
  18. from fontTools.varLib import builder, models, varStore
  19. from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList
  20. from fontTools.varLib.varStore import VarStoreInstancer
  21. from functools import reduce
  22. from fontTools.otlLib.builder import buildSinglePos
  23. from fontTools.otlLib.optimize.gpos import (
  24. _compression_level_from_env,
  25. compact_pair_pos,
  26. )
  27. log = logging.getLogger("fontTools.varLib.merger")
  28. from .errors import (
  29. ShouldBeConstant,
  30. FoundANone,
  31. MismatchedTypes,
  32. NotANone,
  33. LengthsDiffer,
  34. KeysDiffer,
  35. InconsistentGlyphOrder,
  36. InconsistentExtensions,
  37. InconsistentFormats,
  38. UnsupportedFormat,
  39. VarLibMergeError,
  40. )
  41. class Merger(object):
  42. def __init__(self, font=None):
  43. self.font = font
  44. # mergeTables populates this from the parent's master ttfs
  45. self.ttfs = None
  46. @classmethod
  47. def merger(celf, clazzes, attrs=(None,)):
  48. assert celf != Merger, "Subclass Merger instead."
  49. if "mergers" not in celf.__dict__:
  50. celf.mergers = {}
  51. if type(clazzes) in (type, enum.EnumMeta):
  52. clazzes = (clazzes,)
  53. if type(attrs) == str:
  54. attrs = (attrs,)
  55. def wrapper(method):
  56. assert method.__name__ == "merge"
  57. done = []
  58. for clazz in clazzes:
  59. if clazz in done:
  60. continue # Support multiple names of a clazz
  61. done.append(clazz)
  62. mergers = celf.mergers.setdefault(clazz, {})
  63. for attr in attrs:
  64. assert attr not in mergers, (
  65. "Oops, class '%s' has merge function for '%s' defined already."
  66. % (clazz.__name__, attr)
  67. )
  68. mergers[attr] = method
  69. return None
  70. return wrapper
  71. @classmethod
  72. def mergersFor(celf, thing, _default={}):
  73. typ = type(thing)
  74. for celf in celf.mro():
  75. mergers = getattr(celf, "mergers", None)
  76. if mergers is None:
  77. break
  78. m = celf.mergers.get(typ, None)
  79. if m is not None:
  80. return m
  81. return _default
  82. def mergeObjects(self, out, lst, exclude=()):
  83. if hasattr(out, "ensureDecompiled"):
  84. out.ensureDecompiled(recurse=False)
  85. for item in lst:
  86. if hasattr(item, "ensureDecompiled"):
  87. item.ensureDecompiled(recurse=False)
  88. keys = sorted(vars(out).keys())
  89. if not all(keys == sorted(vars(v).keys()) for v in lst):
  90. raise KeysDiffer(
  91. self, expected=keys, got=[sorted(vars(v).keys()) for v in lst]
  92. )
  93. mergers = self.mergersFor(out)
  94. defaultMerger = mergers.get("*", self.__class__.mergeThings)
  95. try:
  96. for key in keys:
  97. if key in exclude:
  98. continue
  99. value = getattr(out, key)
  100. values = [getattr(table, key) for table in lst]
  101. mergerFunc = mergers.get(key, defaultMerger)
  102. mergerFunc(self, value, values)
  103. except VarLibMergeError as e:
  104. e.stack.append("." + key)
  105. raise
  106. def mergeLists(self, out, lst):
  107. if not allEqualTo(out, lst, len):
  108. raise LengthsDiffer(self, expected=len(out), got=[len(x) for x in lst])
  109. for i, (value, values) in enumerate(zip(out, zip(*lst))):
  110. try:
  111. self.mergeThings(value, values)
  112. except VarLibMergeError as e:
  113. e.stack.append("[%d]" % i)
  114. raise
  115. def mergeThings(self, out, lst):
  116. if not allEqualTo(out, lst, type):
  117. raise MismatchedTypes(
  118. self, expected=type(out).__name__, got=[type(x).__name__ for x in lst]
  119. )
  120. mergerFunc = self.mergersFor(out).get(None, None)
  121. if mergerFunc is not None:
  122. mergerFunc(self, out, lst)
  123. elif isinstance(out, enum.Enum):
  124. # need to special-case Enums as have __dict__ but are not regular 'objects',
  125. # otherwise mergeObjects/mergeThings get trapped in a RecursionError
  126. if not allEqualTo(out, lst):
  127. raise ShouldBeConstant(self, expected=out, got=lst)
  128. elif hasattr(out, "__dict__"):
  129. self.mergeObjects(out, lst)
  130. elif isinstance(out, list):
  131. self.mergeLists(out, lst)
  132. else:
  133. if not allEqualTo(out, lst):
  134. raise ShouldBeConstant(self, expected=out, got=lst)
  135. def mergeTables(self, font, master_ttfs, tableTags):
  136. for tag in tableTags:
  137. if tag not in font:
  138. continue
  139. try:
  140. self.ttfs = master_ttfs
  141. self.mergeThings(font[tag], [m.get(tag) for m in master_ttfs])
  142. except VarLibMergeError as e:
  143. e.stack.append(tag)
  144. raise
  145. #
  146. # Aligning merger
  147. #
  148. class AligningMerger(Merger):
  149. pass
  150. @AligningMerger.merger(ot.GDEF, "GlyphClassDef")
  151. def merge(merger, self, lst):
  152. if self is None:
  153. if not allNone(lst):
  154. raise NotANone(merger, expected=None, got=lst)
  155. return
  156. lst = [l.classDefs for l in lst]
  157. self.classDefs = {}
  158. # We only care about the .classDefs
  159. self = self.classDefs
  160. allKeys = set()
  161. allKeys.update(*[l.keys() for l in lst])
  162. for k in allKeys:
  163. allValues = nonNone(l.get(k) for l in lst)
  164. if not allEqual(allValues):
  165. raise ShouldBeConstant(
  166. merger, expected=allValues[0], got=lst, stack=["." + k]
  167. )
  168. if not allValues:
  169. self[k] = None
  170. else:
  171. self[k] = allValues[0]
  172. def _SinglePosUpgradeToFormat2(self):
  173. if self.Format == 2:
  174. return self
  175. ret = ot.SinglePos()
  176. ret.Format = 2
  177. ret.Coverage = self.Coverage
  178. ret.ValueFormat = self.ValueFormat
  179. ret.Value = [self.Value for _ in ret.Coverage.glyphs]
  180. ret.ValueCount = len(ret.Value)
  181. return ret
  182. def _merge_GlyphOrders(font, lst, values_lst=None, default=None):
  183. """Takes font and list of glyph lists (must be sorted by glyph id), and returns
  184. two things:
  185. - Combined glyph list,
  186. - If values_lst is None, return input glyph lists, but padded with None when a glyph
  187. was missing in a list. Otherwise, return values_lst list-of-list, padded with None
  188. to match combined glyph lists.
  189. """
  190. if values_lst is None:
  191. dict_sets = [set(l) for l in lst]
  192. else:
  193. dict_sets = [{g: v for g, v in zip(l, vs)} for l, vs in zip(lst, values_lst)]
  194. combined = set()
  195. combined.update(*dict_sets)
  196. sortKey = font.getReverseGlyphMap().__getitem__
  197. order = sorted(combined, key=sortKey)
  198. # Make sure all input glyphsets were in proper order
  199. if not all(sorted(vs, key=sortKey) == vs for vs in lst):
  200. raise InconsistentGlyphOrder()
  201. del combined
  202. paddedValues = None
  203. if values_lst is None:
  204. padded = [
  205. [glyph if glyph in dict_set else default for glyph in order]
  206. for dict_set in dict_sets
  207. ]
  208. else:
  209. assert len(lst) == len(values_lst)
  210. padded = [
  211. [dict_set[glyph] if glyph in dict_set else default for glyph in order]
  212. for dict_set in dict_sets
  213. ]
  214. return order, padded
  215. @AligningMerger.merger(otBase.ValueRecord)
  216. def merge(merger, self, lst):
  217. # Code below sometimes calls us with self being
  218. # a new object. Copy it from lst and recurse.
  219. self.__dict__ = lst[0].__dict__.copy()
  220. merger.mergeObjects(self, lst)
  221. @AligningMerger.merger(ot.Anchor)
  222. def merge(merger, self, lst):
  223. # Code below sometimes calls us with self being
  224. # a new object. Copy it from lst and recurse.
  225. self.__dict__ = lst[0].__dict__.copy()
  226. merger.mergeObjects(self, lst)
  227. def _Lookup_SinglePos_get_effective_value(merger, subtables, glyph):
  228. for self in subtables:
  229. if (
  230. self is None
  231. or type(self) != ot.SinglePos
  232. or self.Coverage is None
  233. or glyph not in self.Coverage.glyphs
  234. ):
  235. continue
  236. if self.Format == 1:
  237. return self.Value
  238. elif self.Format == 2:
  239. return self.Value[self.Coverage.glyphs.index(glyph)]
  240. else:
  241. raise UnsupportedFormat(merger, subtable="single positioning lookup")
  242. return None
  243. def _Lookup_PairPos_get_effective_value_pair(
  244. merger, subtables, firstGlyph, secondGlyph
  245. ):
  246. for self in subtables:
  247. if (
  248. self is None
  249. or type(self) != ot.PairPos
  250. or self.Coverage is None
  251. or firstGlyph not in self.Coverage.glyphs
  252. ):
  253. continue
  254. if self.Format == 1:
  255. ps = self.PairSet[self.Coverage.glyphs.index(firstGlyph)]
  256. pvr = ps.PairValueRecord
  257. for rec in pvr: # TODO Speed up
  258. if rec.SecondGlyph == secondGlyph:
  259. return rec
  260. continue
  261. elif self.Format == 2:
  262. klass1 = self.ClassDef1.classDefs.get(firstGlyph, 0)
  263. klass2 = self.ClassDef2.classDefs.get(secondGlyph, 0)
  264. return self.Class1Record[klass1].Class2Record[klass2]
  265. else:
  266. raise UnsupportedFormat(merger, subtable="pair positioning lookup")
  267. return None
  268. @AligningMerger.merger(ot.SinglePos)
  269. def merge(merger, self, lst):
  270. self.ValueFormat = valueFormat = reduce(int.__or__, [l.ValueFormat for l in lst], 0)
  271. if not (len(lst) == 1 or (valueFormat & ~0xF == 0)):
  272. raise UnsupportedFormat(merger, subtable="single positioning lookup")
  273. # If all have same coverage table and all are format 1,
  274. coverageGlyphs = self.Coverage.glyphs
  275. if all(v.Format == 1 for v in lst) and all(
  276. coverageGlyphs == v.Coverage.glyphs for v in lst
  277. ):
  278. self.Value = otBase.ValueRecord(valueFormat, self.Value)
  279. if valueFormat != 0:
  280. # If v.Value is None, it means a kerning of 0; we want
  281. # it to participate in the model still.
  282. # https://github.com/fonttools/fonttools/issues/3111
  283. merger.mergeThings(
  284. self.Value,
  285. [v.Value if v.Value is not None else otBase.ValueRecord() for v in lst],
  286. )
  287. self.ValueFormat = self.Value.getFormat()
  288. return
  289. # Upgrade everything to Format=2
  290. self.Format = 2
  291. lst = [_SinglePosUpgradeToFormat2(v) for v in lst]
  292. # Align them
  293. glyphs, padded = _merge_GlyphOrders(
  294. merger.font, [v.Coverage.glyphs for v in lst], [v.Value for v in lst]
  295. )
  296. self.Coverage.glyphs = glyphs
  297. self.Value = [otBase.ValueRecord(valueFormat) for _ in glyphs]
  298. self.ValueCount = len(self.Value)
  299. for i, values in enumerate(padded):
  300. for j, glyph in enumerate(glyphs):
  301. if values[j] is not None:
  302. continue
  303. # Fill in value from other subtables
  304. # Note!!! This *might* result in behavior change if ValueFormat2-zeroedness
  305. # is different between used subtable and current subtable!
  306. # TODO(behdad) Check and warn if that happens?
  307. v = _Lookup_SinglePos_get_effective_value(
  308. merger, merger.lookup_subtables[i], glyph
  309. )
  310. if v is None:
  311. v = otBase.ValueRecord(valueFormat)
  312. values[j] = v
  313. merger.mergeLists(self.Value, padded)
  314. # Merge everything else; though, there shouldn't be anything else. :)
  315. merger.mergeObjects(
  316. self, lst, exclude=("Format", "Coverage", "Value", "ValueCount", "ValueFormat")
  317. )
  318. self.ValueFormat = reduce(
  319. int.__or__, [v.getEffectiveFormat() for v in self.Value], 0
  320. )
  321. @AligningMerger.merger(ot.PairSet)
  322. def merge(merger, self, lst):
  323. # Align them
  324. glyphs, padded = _merge_GlyphOrders(
  325. merger.font,
  326. [[v.SecondGlyph for v in vs.PairValueRecord] for vs in lst],
  327. [vs.PairValueRecord for vs in lst],
  328. )
  329. self.PairValueRecord = pvrs = []
  330. for glyph in glyphs:
  331. pvr = ot.PairValueRecord()
  332. pvr.SecondGlyph = glyph
  333. pvr.Value1 = (
  334. otBase.ValueRecord(merger.valueFormat1) if merger.valueFormat1 else None
  335. )
  336. pvr.Value2 = (
  337. otBase.ValueRecord(merger.valueFormat2) if merger.valueFormat2 else None
  338. )
  339. pvrs.append(pvr)
  340. self.PairValueCount = len(self.PairValueRecord)
  341. for i, values in enumerate(padded):
  342. for j, glyph in enumerate(glyphs):
  343. # Fill in value from other subtables
  344. v = ot.PairValueRecord()
  345. v.SecondGlyph = glyph
  346. if values[j] is not None:
  347. vpair = values[j]
  348. else:
  349. vpair = _Lookup_PairPos_get_effective_value_pair(
  350. merger, merger.lookup_subtables[i], self._firstGlyph, glyph
  351. )
  352. if vpair is None:
  353. v1, v2 = None, None
  354. else:
  355. v1 = getattr(vpair, "Value1", None)
  356. v2 = getattr(vpair, "Value2", None)
  357. v.Value1 = (
  358. otBase.ValueRecord(merger.valueFormat1, src=v1)
  359. if merger.valueFormat1
  360. else None
  361. )
  362. v.Value2 = (
  363. otBase.ValueRecord(merger.valueFormat2, src=v2)
  364. if merger.valueFormat2
  365. else None
  366. )
  367. values[j] = v
  368. del self._firstGlyph
  369. merger.mergeLists(self.PairValueRecord, padded)
  370. def _PairPosFormat1_merge(self, lst, merger):
  371. assert allEqual(
  372. [l.ValueFormat2 == 0 for l in lst if l.PairSet]
  373. ), "Report bug against fonttools."
  374. # Merge everything else; makes sure Format is the same.
  375. merger.mergeObjects(
  376. self,
  377. lst,
  378. exclude=("Coverage", "PairSet", "PairSetCount", "ValueFormat1", "ValueFormat2"),
  379. )
  380. empty = ot.PairSet()
  381. empty.PairValueRecord = []
  382. empty.PairValueCount = 0
  383. # Align them
  384. glyphs, padded = _merge_GlyphOrders(
  385. merger.font,
  386. [v.Coverage.glyphs for v in lst],
  387. [v.PairSet for v in lst],
  388. default=empty,
  389. )
  390. self.Coverage.glyphs = glyphs
  391. self.PairSet = [ot.PairSet() for _ in glyphs]
  392. self.PairSetCount = len(self.PairSet)
  393. for glyph, ps in zip(glyphs, self.PairSet):
  394. ps._firstGlyph = glyph
  395. merger.mergeLists(self.PairSet, padded)
  396. def _ClassDef_invert(self, allGlyphs=None):
  397. if isinstance(self, dict):
  398. classDefs = self
  399. else:
  400. classDefs = self.classDefs if self and self.classDefs else {}
  401. m = max(classDefs.values()) if classDefs else 0
  402. ret = []
  403. for _ in range(m + 1):
  404. ret.append(set())
  405. for k, v in classDefs.items():
  406. ret[v].add(k)
  407. # Class-0 is special. It's "everything else".
  408. if allGlyphs is None:
  409. ret[0] = None
  410. else:
  411. # Limit all classes to glyphs in allGlyphs.
  412. # Collect anything without a non-zero class into class=zero.
  413. ret[0] = class0 = set(allGlyphs)
  414. for s in ret[1:]:
  415. s.intersection_update(class0)
  416. class0.difference_update(s)
  417. return ret
  418. def _ClassDef_merge_classify(lst, allGlyphses=None):
  419. self = ot.ClassDef()
  420. self.classDefs = classDefs = {}
  421. allGlyphsesWasNone = allGlyphses is None
  422. if allGlyphsesWasNone:
  423. allGlyphses = [None] * len(lst)
  424. classifier = classifyTools.Classifier()
  425. for classDef, allGlyphs in zip(lst, allGlyphses):
  426. sets = _ClassDef_invert(classDef, allGlyphs)
  427. if allGlyphs is None:
  428. sets = sets[1:]
  429. classifier.update(sets)
  430. classes = classifier.getClasses()
  431. if allGlyphsesWasNone:
  432. classes.insert(0, set())
  433. for i, classSet in enumerate(classes):
  434. if i == 0:
  435. continue
  436. for g in classSet:
  437. classDefs[g] = i
  438. return self, classes
  439. def _PairPosFormat2_align_matrices(self, lst, font, transparent=False):
  440. matrices = [l.Class1Record for l in lst]
  441. # Align first classes
  442. self.ClassDef1, classes = _ClassDef_merge_classify(
  443. [l.ClassDef1 for l in lst], [l.Coverage.glyphs for l in lst]
  444. )
  445. self.Class1Count = len(classes)
  446. new_matrices = []
  447. for l, matrix in zip(lst, matrices):
  448. nullRow = None
  449. coverage = set(l.Coverage.glyphs)
  450. classDef1 = l.ClassDef1.classDefs
  451. class1Records = []
  452. for classSet in classes:
  453. exemplarGlyph = next(iter(classSet))
  454. if exemplarGlyph not in coverage:
  455. # Follow-up to e6125b353e1f54a0280ded5434b8e40d042de69f,
  456. # Fixes https://github.com/googlei18n/fontmake/issues/470
  457. # Again, revert 8d441779e5afc664960d848f62c7acdbfc71d7b9
  458. # when merger becomes selfless.
  459. nullRow = None
  460. if nullRow is None:
  461. nullRow = ot.Class1Record()
  462. class2records = nullRow.Class2Record = []
  463. # TODO: When merger becomes selfless, revert e6125b353e1f54a0280ded5434b8e40d042de69f
  464. for _ in range(l.Class2Count):
  465. if transparent:
  466. rec2 = None
  467. else:
  468. rec2 = ot.Class2Record()
  469. rec2.Value1 = (
  470. otBase.ValueRecord(self.ValueFormat1)
  471. if self.ValueFormat1
  472. else None
  473. )
  474. rec2.Value2 = (
  475. otBase.ValueRecord(self.ValueFormat2)
  476. if self.ValueFormat2
  477. else None
  478. )
  479. class2records.append(rec2)
  480. rec1 = nullRow
  481. else:
  482. klass = classDef1.get(exemplarGlyph, 0)
  483. rec1 = matrix[klass] # TODO handle out-of-range?
  484. class1Records.append(rec1)
  485. new_matrices.append(class1Records)
  486. matrices = new_matrices
  487. del new_matrices
  488. # Align second classes
  489. self.ClassDef2, classes = _ClassDef_merge_classify([l.ClassDef2 for l in lst])
  490. self.Class2Count = len(classes)
  491. new_matrices = []
  492. for l, matrix in zip(lst, matrices):
  493. classDef2 = l.ClassDef2.classDefs
  494. class1Records = []
  495. for rec1old in matrix:
  496. oldClass2Records = rec1old.Class2Record
  497. rec1new = ot.Class1Record()
  498. class2Records = rec1new.Class2Record = []
  499. for classSet in classes:
  500. if not classSet: # class=0
  501. rec2 = oldClass2Records[0]
  502. else:
  503. exemplarGlyph = next(iter(classSet))
  504. klass = classDef2.get(exemplarGlyph, 0)
  505. rec2 = oldClass2Records[klass]
  506. class2Records.append(copy.deepcopy(rec2))
  507. class1Records.append(rec1new)
  508. new_matrices.append(class1Records)
  509. matrices = new_matrices
  510. del new_matrices
  511. return matrices
  512. def _PairPosFormat2_merge(self, lst, merger):
  513. assert allEqual(
  514. [l.ValueFormat2 == 0 for l in lst if l.Class1Record]
  515. ), "Report bug against fonttools."
  516. merger.mergeObjects(
  517. self,
  518. lst,
  519. exclude=(
  520. "Coverage",
  521. "ClassDef1",
  522. "Class1Count",
  523. "ClassDef2",
  524. "Class2Count",
  525. "Class1Record",
  526. "ValueFormat1",
  527. "ValueFormat2",
  528. ),
  529. )
  530. # Align coverages
  531. glyphs, _ = _merge_GlyphOrders(merger.font, [v.Coverage.glyphs for v in lst])
  532. self.Coverage.glyphs = glyphs
  533. # Currently, if the coverage of PairPosFormat2 subtables are different,
  534. # we do NOT bother walking down the subtable list when filling in new
  535. # rows for alignment. As such, this is only correct if current subtable
  536. # is the last subtable in the lookup. Ensure that.
  537. #
  538. # Note that our canonicalization process merges trailing PairPosFormat2's,
  539. # so in reality this is rare.
  540. for l, subtables in zip(lst, merger.lookup_subtables):
  541. if l.Coverage.glyphs != glyphs:
  542. assert l == subtables[-1]
  543. matrices = _PairPosFormat2_align_matrices(self, lst, merger.font)
  544. self.Class1Record = list(matrices[0]) # TODO move merger to be selfless
  545. merger.mergeLists(self.Class1Record, matrices)
  546. @AligningMerger.merger(ot.PairPos)
  547. def merge(merger, self, lst):
  548. merger.valueFormat1 = self.ValueFormat1 = reduce(
  549. int.__or__, [l.ValueFormat1 for l in lst], 0
  550. )
  551. merger.valueFormat2 = self.ValueFormat2 = reduce(
  552. int.__or__, [l.ValueFormat2 for l in lst], 0
  553. )
  554. if self.Format == 1:
  555. _PairPosFormat1_merge(self, lst, merger)
  556. elif self.Format == 2:
  557. _PairPosFormat2_merge(self, lst, merger)
  558. else:
  559. raise UnsupportedFormat(merger, subtable="pair positioning lookup")
  560. del merger.valueFormat1, merger.valueFormat2
  561. # Now examine the list of value records, and update to the union of format values,
  562. # as merge might have created new values.
  563. vf1 = 0
  564. vf2 = 0
  565. if self.Format == 1:
  566. for pairSet in self.PairSet:
  567. for pairValueRecord in pairSet.PairValueRecord:
  568. pv1 = getattr(pairValueRecord, "Value1", None)
  569. if pv1 is not None:
  570. vf1 |= pv1.getFormat()
  571. pv2 = getattr(pairValueRecord, "Value2", None)
  572. if pv2 is not None:
  573. vf2 |= pv2.getFormat()
  574. elif self.Format == 2:
  575. for class1Record in self.Class1Record:
  576. for class2Record in class1Record.Class2Record:
  577. pv1 = getattr(class2Record, "Value1", None)
  578. if pv1 is not None:
  579. vf1 |= pv1.getFormat()
  580. pv2 = getattr(class2Record, "Value2", None)
  581. if pv2 is not None:
  582. vf2 |= pv2.getFormat()
  583. self.ValueFormat1 = vf1
  584. self.ValueFormat2 = vf2
  585. def _MarkBasePosFormat1_merge(self, lst, merger, Mark="Mark", Base="Base"):
  586. self.ClassCount = max(l.ClassCount for l in lst)
  587. MarkCoverageGlyphs, MarkRecords = _merge_GlyphOrders(
  588. merger.font,
  589. [getattr(l, Mark + "Coverage").glyphs for l in lst],
  590. [getattr(l, Mark + "Array").MarkRecord for l in lst],
  591. )
  592. getattr(self, Mark + "Coverage").glyphs = MarkCoverageGlyphs
  593. BaseCoverageGlyphs, BaseRecords = _merge_GlyphOrders(
  594. merger.font,
  595. [getattr(l, Base + "Coverage").glyphs for l in lst],
  596. [getattr(getattr(l, Base + "Array"), Base + "Record") for l in lst],
  597. )
  598. getattr(self, Base + "Coverage").glyphs = BaseCoverageGlyphs
  599. # MarkArray
  600. records = []
  601. for g, glyphRecords in zip(MarkCoverageGlyphs, zip(*MarkRecords)):
  602. allClasses = [r.Class for r in glyphRecords if r is not None]
  603. # TODO Right now we require that all marks have same class in
  604. # all masters that cover them. This is not required.
  605. #
  606. # We can relax that by just requiring that all marks that have
  607. # the same class in a master, have the same class in every other
  608. # master. Indeed, if, say, a sparse master only covers one mark,
  609. # that mark probably will get class 0, which would possibly be
  610. # different from its class in other masters.
  611. #
  612. # We can even go further and reclassify marks to support any
  613. # input. But, since, it's unlikely that two marks being both,
  614. # say, "top" in one master, and one being "top" and other being
  615. # "top-right" in another master, we shouldn't do that, as any
  616. # failures in that case will probably signify mistakes in the
  617. # input masters.
  618. if not allEqual(allClasses):
  619. raise ShouldBeConstant(merger, expected=allClasses[0], got=allClasses)
  620. else:
  621. rec = ot.MarkRecord()
  622. rec.Class = allClasses[0]
  623. allAnchors = [None if r is None else r.MarkAnchor for r in glyphRecords]
  624. if allNone(allAnchors):
  625. anchor = None
  626. else:
  627. anchor = ot.Anchor()
  628. anchor.Format = 1
  629. merger.mergeThings(anchor, allAnchors)
  630. rec.MarkAnchor = anchor
  631. records.append(rec)
  632. array = ot.MarkArray()
  633. array.MarkRecord = records
  634. array.MarkCount = len(records)
  635. setattr(self, Mark + "Array", array)
  636. # BaseArray
  637. records = []
  638. for g, glyphRecords in zip(BaseCoverageGlyphs, zip(*BaseRecords)):
  639. if allNone(glyphRecords):
  640. rec = None
  641. else:
  642. rec = getattr(ot, Base + "Record")()
  643. anchors = []
  644. setattr(rec, Base + "Anchor", anchors)
  645. glyphAnchors = [
  646. [] if r is None else getattr(r, Base + "Anchor") for r in glyphRecords
  647. ]
  648. for l in glyphAnchors:
  649. l.extend([None] * (self.ClassCount - len(l)))
  650. for allAnchors in zip(*glyphAnchors):
  651. if allNone(allAnchors):
  652. anchor = None
  653. else:
  654. anchor = ot.Anchor()
  655. anchor.Format = 1
  656. merger.mergeThings(anchor, allAnchors)
  657. anchors.append(anchor)
  658. records.append(rec)
  659. array = getattr(ot, Base + "Array")()
  660. setattr(array, Base + "Record", records)
  661. setattr(array, Base + "Count", len(records))
  662. setattr(self, Base + "Array", array)
  663. @AligningMerger.merger(ot.MarkBasePos)
  664. def merge(merger, self, lst):
  665. if not allEqualTo(self.Format, (l.Format for l in lst)):
  666. raise InconsistentFormats(
  667. merger,
  668. subtable="mark-to-base positioning lookup",
  669. expected=self.Format,
  670. got=[l.Format for l in lst],
  671. )
  672. if self.Format == 1:
  673. _MarkBasePosFormat1_merge(self, lst, merger)
  674. else:
  675. raise UnsupportedFormat(merger, subtable="mark-to-base positioning lookup")
  676. @AligningMerger.merger(ot.MarkMarkPos)
  677. def merge(merger, self, lst):
  678. if not allEqualTo(self.Format, (l.Format for l in lst)):
  679. raise InconsistentFormats(
  680. merger,
  681. subtable="mark-to-mark positioning lookup",
  682. expected=self.Format,
  683. got=[l.Format for l in lst],
  684. )
  685. if self.Format == 1:
  686. _MarkBasePosFormat1_merge(self, lst, merger, "Mark1", "Mark2")
  687. else:
  688. raise UnsupportedFormat(merger, subtable="mark-to-mark positioning lookup")
  689. def _PairSet_flatten(lst, font):
  690. self = ot.PairSet()
  691. self.Coverage = ot.Coverage()
  692. # Align them
  693. glyphs, padded = _merge_GlyphOrders(
  694. font,
  695. [[v.SecondGlyph for v in vs.PairValueRecord] for vs in lst],
  696. [vs.PairValueRecord for vs in lst],
  697. )
  698. self.Coverage.glyphs = glyphs
  699. self.PairValueRecord = pvrs = []
  700. for values in zip(*padded):
  701. for v in values:
  702. if v is not None:
  703. pvrs.append(v)
  704. break
  705. else:
  706. assert False
  707. self.PairValueCount = len(self.PairValueRecord)
  708. return self
  709. def _Lookup_PairPosFormat1_subtables_flatten(lst, font):
  710. assert allEqual(
  711. [l.ValueFormat2 == 0 for l in lst if l.PairSet]
  712. ), "Report bug against fonttools."
  713. self = ot.PairPos()
  714. self.Format = 1
  715. self.Coverage = ot.Coverage()
  716. self.ValueFormat1 = reduce(int.__or__, [l.ValueFormat1 for l in lst], 0)
  717. self.ValueFormat2 = reduce(int.__or__, [l.ValueFormat2 for l in lst], 0)
  718. # Align them
  719. glyphs, padded = _merge_GlyphOrders(
  720. font, [v.Coverage.glyphs for v in lst], [v.PairSet for v in lst]
  721. )
  722. self.Coverage.glyphs = glyphs
  723. self.PairSet = [
  724. _PairSet_flatten([v for v in values if v is not None], font)
  725. for values in zip(*padded)
  726. ]
  727. self.PairSetCount = len(self.PairSet)
  728. return self
  729. def _Lookup_PairPosFormat2_subtables_flatten(lst, font):
  730. assert allEqual(
  731. [l.ValueFormat2 == 0 for l in lst if l.Class1Record]
  732. ), "Report bug against fonttools."
  733. self = ot.PairPos()
  734. self.Format = 2
  735. self.Coverage = ot.Coverage()
  736. self.ValueFormat1 = reduce(int.__or__, [l.ValueFormat1 for l in lst], 0)
  737. self.ValueFormat2 = reduce(int.__or__, [l.ValueFormat2 for l in lst], 0)
  738. # Align them
  739. glyphs, _ = _merge_GlyphOrders(font, [v.Coverage.glyphs for v in lst])
  740. self.Coverage.glyphs = glyphs
  741. matrices = _PairPosFormat2_align_matrices(self, lst, font, transparent=True)
  742. matrix = self.Class1Record = []
  743. for rows in zip(*matrices):
  744. row = ot.Class1Record()
  745. matrix.append(row)
  746. row.Class2Record = []
  747. row = row.Class2Record
  748. for cols in zip(*list(r.Class2Record for r in rows)):
  749. col = next(iter(c for c in cols if c is not None))
  750. row.append(col)
  751. return self
  752. def _Lookup_PairPos_subtables_canonicalize(lst, font):
  753. """Merge multiple Format1 subtables at the beginning of lst,
  754. and merge multiple consecutive Format2 subtables that have the same
  755. Class2 (ie. were split because of offset overflows). Returns new list."""
  756. lst = list(lst)
  757. l = len(lst)
  758. i = 0
  759. while i < l and lst[i].Format == 1:
  760. i += 1
  761. lst[:i] = [_Lookup_PairPosFormat1_subtables_flatten(lst[:i], font)]
  762. l = len(lst)
  763. i = l
  764. while i > 0 and lst[i - 1].Format == 2:
  765. i -= 1
  766. lst[i:] = [_Lookup_PairPosFormat2_subtables_flatten(lst[i:], font)]
  767. return lst
  768. def _Lookup_SinglePos_subtables_flatten(lst, font, min_inclusive_rec_format):
  769. glyphs, _ = _merge_GlyphOrders(font, [v.Coverage.glyphs for v in lst], None)
  770. num_glyphs = len(glyphs)
  771. new = ot.SinglePos()
  772. new.Format = 2
  773. new.ValueFormat = min_inclusive_rec_format
  774. new.Coverage = ot.Coverage()
  775. new.Coverage.glyphs = glyphs
  776. new.ValueCount = num_glyphs
  777. new.Value = [None] * num_glyphs
  778. for singlePos in lst:
  779. if singlePos.Format == 1:
  780. val_rec = singlePos.Value
  781. for gname in singlePos.Coverage.glyphs:
  782. i = glyphs.index(gname)
  783. new.Value[i] = copy.deepcopy(val_rec)
  784. elif singlePos.Format == 2:
  785. for j, gname in enumerate(singlePos.Coverage.glyphs):
  786. val_rec = singlePos.Value[j]
  787. i = glyphs.index(gname)
  788. new.Value[i] = copy.deepcopy(val_rec)
  789. return [new]
  790. @AligningMerger.merger(ot.CursivePos)
  791. def merge(merger, self, lst):
  792. # Align them
  793. glyphs, padded = _merge_GlyphOrders(
  794. merger.font,
  795. [l.Coverage.glyphs for l in lst],
  796. [l.EntryExitRecord for l in lst],
  797. )
  798. self.Format = 1
  799. self.Coverage = ot.Coverage()
  800. self.Coverage.glyphs = glyphs
  801. self.EntryExitRecord = []
  802. for _ in glyphs:
  803. rec = ot.EntryExitRecord()
  804. rec.EntryAnchor = ot.Anchor()
  805. rec.EntryAnchor.Format = 1
  806. rec.ExitAnchor = ot.Anchor()
  807. rec.ExitAnchor.Format = 1
  808. self.EntryExitRecord.append(rec)
  809. merger.mergeLists(self.EntryExitRecord, padded)
  810. self.EntryExitCount = len(self.EntryExitRecord)
  811. @AligningMerger.merger(ot.EntryExitRecord)
  812. def merge(merger, self, lst):
  813. if all(master.EntryAnchor is None for master in lst):
  814. self.EntryAnchor = None
  815. if all(master.ExitAnchor is None for master in lst):
  816. self.ExitAnchor = None
  817. merger.mergeObjects(self, lst)
  818. @AligningMerger.merger(ot.Lookup)
  819. def merge(merger, self, lst):
  820. subtables = merger.lookup_subtables = [l.SubTable for l in lst]
  821. # Remove Extension subtables
  822. for l, sts in list(zip(lst, subtables)) + [(self, self.SubTable)]:
  823. if not sts:
  824. continue
  825. if sts[0].__class__.__name__.startswith("Extension"):
  826. if not allEqual([st.__class__ for st in sts]):
  827. raise InconsistentExtensions(
  828. merger,
  829. expected="Extension",
  830. got=[st.__class__.__name__ for st in sts],
  831. )
  832. if not allEqual([st.ExtensionLookupType for st in sts]):
  833. raise InconsistentExtensions(merger)
  834. l.LookupType = sts[0].ExtensionLookupType
  835. new_sts = [st.ExtSubTable for st in sts]
  836. del sts[:]
  837. sts.extend(new_sts)
  838. isPairPos = self.SubTable and isinstance(self.SubTable[0], ot.PairPos)
  839. if isPairPos:
  840. # AFDKO and feaLib sometimes generate two Format1 subtables instead of one.
  841. # Merge those before continuing.
  842. # https://github.com/fonttools/fonttools/issues/719
  843. self.SubTable = _Lookup_PairPos_subtables_canonicalize(
  844. self.SubTable, merger.font
  845. )
  846. subtables = merger.lookup_subtables = [
  847. _Lookup_PairPos_subtables_canonicalize(st, merger.font) for st in subtables
  848. ]
  849. else:
  850. isSinglePos = self.SubTable and isinstance(self.SubTable[0], ot.SinglePos)
  851. if isSinglePos:
  852. numSubtables = [len(st) for st in subtables]
  853. if not all([nums == numSubtables[0] for nums in numSubtables]):
  854. # Flatten list of SinglePos subtables to single Format 2 subtable,
  855. # with all value records set to the rec format type.
  856. # We use buildSinglePos() to optimize the lookup after merging.
  857. valueFormatList = [t.ValueFormat for st in subtables for t in st]
  858. # Find the minimum value record that can accomodate all the singlePos subtables.
  859. mirf = reduce(ior, valueFormatList)
  860. self.SubTable = _Lookup_SinglePos_subtables_flatten(
  861. self.SubTable, merger.font, mirf
  862. )
  863. subtables = merger.lookup_subtables = [
  864. _Lookup_SinglePos_subtables_flatten(st, merger.font, mirf)
  865. for st in subtables
  866. ]
  867. flattened = True
  868. else:
  869. flattened = False
  870. merger.mergeLists(self.SubTable, subtables)
  871. self.SubTableCount = len(self.SubTable)
  872. if isPairPos:
  873. # If format-1 subtable created during canonicalization is empty, remove it.
  874. assert len(self.SubTable) >= 1 and self.SubTable[0].Format == 1
  875. if not self.SubTable[0].Coverage.glyphs:
  876. self.SubTable.pop(0)
  877. self.SubTableCount -= 1
  878. # If format-2 subtable created during canonicalization is empty, remove it.
  879. assert len(self.SubTable) >= 1 and self.SubTable[-1].Format == 2
  880. if not self.SubTable[-1].Coverage.glyphs:
  881. self.SubTable.pop(-1)
  882. self.SubTableCount -= 1
  883. # Compact the merged subtables
  884. # This is a good moment to do it because the compaction should create
  885. # smaller subtables, which may prevent overflows from happening.
  886. # Keep reading the value from the ENV until ufo2ft switches to the config system
  887. level = merger.font.cfg.get(
  888. "fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL",
  889. default=_compression_level_from_env(),
  890. )
  891. if level != 0:
  892. log.info("Compacting GPOS...")
  893. self.SubTable = compact_pair_pos(merger.font, level, self.SubTable)
  894. self.SubTableCount = len(self.SubTable)
  895. elif isSinglePos and flattened:
  896. singlePosTable = self.SubTable[0]
  897. glyphs = singlePosTable.Coverage.glyphs
  898. # We know that singlePosTable is Format 2, as this is set
  899. # in _Lookup_SinglePos_subtables_flatten.
  900. singlePosMapping = {
  901. gname: valRecord for gname, valRecord in zip(glyphs, singlePosTable.Value)
  902. }
  903. self.SubTable = buildSinglePos(
  904. singlePosMapping, merger.font.getReverseGlyphMap()
  905. )
  906. merger.mergeObjects(self, lst, exclude=["SubTable", "SubTableCount"])
  907. del merger.lookup_subtables
  908. #
  909. # InstancerMerger
  910. #
  911. class InstancerMerger(AligningMerger):
  912. """A merger that takes multiple master fonts, and instantiates
  913. an instance."""
  914. def __init__(self, font, model, location):
  915. Merger.__init__(self, font)
  916. self.model = model
  917. self.location = location
  918. self.scalars = model.getScalars(location)
  919. @InstancerMerger.merger(ot.CaretValue)
  920. def merge(merger, self, lst):
  921. assert self.Format == 1
  922. Coords = [a.Coordinate for a in lst]
  923. model = merger.model
  924. scalars = merger.scalars
  925. self.Coordinate = otRound(model.interpolateFromMastersAndScalars(Coords, scalars))
  926. @InstancerMerger.merger(ot.Anchor)
  927. def merge(merger, self, lst):
  928. assert self.Format == 1
  929. XCoords = [a.XCoordinate for a in lst]
  930. YCoords = [a.YCoordinate for a in lst]
  931. model = merger.model
  932. scalars = merger.scalars
  933. self.XCoordinate = otRound(model.interpolateFromMastersAndScalars(XCoords, scalars))
  934. self.YCoordinate = otRound(model.interpolateFromMastersAndScalars(YCoords, scalars))
  935. @InstancerMerger.merger(otBase.ValueRecord)
  936. def merge(merger, self, lst):
  937. model = merger.model
  938. scalars = merger.scalars
  939. # TODO Handle differing valueformats
  940. for name, tableName in [
  941. ("XAdvance", "XAdvDevice"),
  942. ("YAdvance", "YAdvDevice"),
  943. ("XPlacement", "XPlaDevice"),
  944. ("YPlacement", "YPlaDevice"),
  945. ]:
  946. assert not hasattr(self, tableName)
  947. if hasattr(self, name):
  948. values = [getattr(a, name, 0) for a in lst]
  949. value = otRound(model.interpolateFromMastersAndScalars(values, scalars))
  950. setattr(self, name, value)
  951. #
  952. # MutatorMerger
  953. #
  954. class MutatorMerger(AligningMerger):
  955. """A merger that takes a variable font, and instantiates
  956. an instance. While there's no "merging" to be done per se,
  957. the operation can benefit from many operations that the
  958. aligning merger does."""
  959. def __init__(self, font, instancer, deleteVariations=True):
  960. Merger.__init__(self, font)
  961. self.instancer = instancer
  962. self.deleteVariations = deleteVariations
  963. @MutatorMerger.merger(ot.CaretValue)
  964. def merge(merger, self, lst):
  965. # Hack till we become selfless.
  966. self.__dict__ = lst[0].__dict__.copy()
  967. if self.Format != 3:
  968. return
  969. instancer = merger.instancer
  970. dev = self.DeviceTable
  971. if merger.deleteVariations:
  972. del self.DeviceTable
  973. if dev:
  974. assert dev.DeltaFormat == 0x8000
  975. varidx = (dev.StartSize << 16) + dev.EndSize
  976. delta = otRound(instancer[varidx])
  977. self.Coordinate += delta
  978. if merger.deleteVariations:
  979. self.Format = 1
  980. @MutatorMerger.merger(ot.Anchor)
  981. def merge(merger, self, lst):
  982. # Hack till we become selfless.
  983. self.__dict__ = lst[0].__dict__.copy()
  984. if self.Format != 3:
  985. return
  986. instancer = merger.instancer
  987. for v in "XY":
  988. tableName = v + "DeviceTable"
  989. if not hasattr(self, tableName):
  990. continue
  991. dev = getattr(self, tableName)
  992. if merger.deleteVariations:
  993. delattr(self, tableName)
  994. if dev is None:
  995. continue
  996. assert dev.DeltaFormat == 0x8000
  997. varidx = (dev.StartSize << 16) + dev.EndSize
  998. delta = otRound(instancer[varidx])
  999. attr = v + "Coordinate"
  1000. setattr(self, attr, getattr(self, attr) + delta)
  1001. if merger.deleteVariations:
  1002. self.Format = 1
  1003. @MutatorMerger.merger(otBase.ValueRecord)
  1004. def merge(merger, self, lst):
  1005. # Hack till we become selfless.
  1006. self.__dict__ = lst[0].__dict__.copy()
  1007. instancer = merger.instancer
  1008. for name, tableName in [
  1009. ("XAdvance", "XAdvDevice"),
  1010. ("YAdvance", "YAdvDevice"),
  1011. ("XPlacement", "XPlaDevice"),
  1012. ("YPlacement", "YPlaDevice"),
  1013. ]:
  1014. if not hasattr(self, tableName):
  1015. continue
  1016. dev = getattr(self, tableName)
  1017. if merger.deleteVariations:
  1018. delattr(self, tableName)
  1019. if dev is None:
  1020. continue
  1021. assert dev.DeltaFormat == 0x8000
  1022. varidx = (dev.StartSize << 16) + dev.EndSize
  1023. delta = otRound(instancer[varidx])
  1024. setattr(self, name, getattr(self, name, 0) + delta)
  1025. #
  1026. # VariationMerger
  1027. #
  1028. class VariationMerger(AligningMerger):
  1029. """A merger that takes multiple master fonts, and builds a
  1030. variable font."""
  1031. def __init__(self, model, axisTags, font):
  1032. Merger.__init__(self, font)
  1033. self.store_builder = varStore.OnlineVarStoreBuilder(axisTags)
  1034. self.setModel(model)
  1035. def setModel(self, model):
  1036. self.model = model
  1037. self.store_builder.setModel(model)
  1038. def mergeThings(self, out, lst):
  1039. masterModel = None
  1040. origTTFs = None
  1041. if None in lst:
  1042. if allNone(lst):
  1043. if out is not None:
  1044. raise FoundANone(self, got=lst)
  1045. return
  1046. # temporarily subset the list of master ttfs to the ones for which
  1047. # master values are not None
  1048. origTTFs = self.ttfs
  1049. if self.ttfs:
  1050. self.ttfs = subList([v is not None for v in lst], self.ttfs)
  1051. masterModel = self.model
  1052. model, lst = masterModel.getSubModel(lst)
  1053. self.setModel(model)
  1054. super(VariationMerger, self).mergeThings(out, lst)
  1055. if masterModel:
  1056. self.setModel(masterModel)
  1057. if origTTFs:
  1058. self.ttfs = origTTFs
  1059. def buildVarDevTable(store_builder, master_values):
  1060. if allEqual(master_values):
  1061. return master_values[0], None
  1062. base, varIdx = store_builder.storeMasters(master_values)
  1063. return base, builder.buildVarDevTable(varIdx)
  1064. @VariationMerger.merger(ot.BaseCoord)
  1065. def merge(merger, self, lst):
  1066. if self.Format != 1:
  1067. raise UnsupportedFormat(merger, subtable="a baseline coordinate")
  1068. self.Coordinate, DeviceTable = buildVarDevTable(
  1069. merger.store_builder, [a.Coordinate for a in lst]
  1070. )
  1071. if DeviceTable:
  1072. self.Format = 3
  1073. self.DeviceTable = DeviceTable
  1074. @VariationMerger.merger(ot.CaretValue)
  1075. def merge(merger, self, lst):
  1076. if self.Format != 1:
  1077. raise UnsupportedFormat(merger, subtable="a caret")
  1078. self.Coordinate, DeviceTable = buildVarDevTable(
  1079. merger.store_builder, [a.Coordinate for a in lst]
  1080. )
  1081. if DeviceTable:
  1082. self.Format = 3
  1083. self.DeviceTable = DeviceTable
  1084. @VariationMerger.merger(ot.Anchor)
  1085. def merge(merger, self, lst):
  1086. if self.Format != 1:
  1087. raise UnsupportedFormat(merger, subtable="an anchor")
  1088. self.XCoordinate, XDeviceTable = buildVarDevTable(
  1089. merger.store_builder, [a.XCoordinate for a in lst]
  1090. )
  1091. self.YCoordinate, YDeviceTable = buildVarDevTable(
  1092. merger.store_builder, [a.YCoordinate for a in lst]
  1093. )
  1094. if XDeviceTable or YDeviceTable:
  1095. self.Format = 3
  1096. self.XDeviceTable = XDeviceTable
  1097. self.YDeviceTable = YDeviceTable
  1098. @VariationMerger.merger(otBase.ValueRecord)
  1099. def merge(merger, self, lst):
  1100. for name, tableName in [
  1101. ("XAdvance", "XAdvDevice"),
  1102. ("YAdvance", "YAdvDevice"),
  1103. ("XPlacement", "XPlaDevice"),
  1104. ("YPlacement", "YPlaDevice"),
  1105. ]:
  1106. if hasattr(self, name):
  1107. value, deviceTable = buildVarDevTable(
  1108. merger.store_builder, [getattr(a, name, 0) for a in lst]
  1109. )
  1110. setattr(self, name, value)
  1111. if deviceTable:
  1112. setattr(self, tableName, deviceTable)
  1113. class COLRVariationMerger(VariationMerger):
  1114. """A specialized VariationMerger that takes multiple master fonts containing
  1115. COLRv1 tables, and builds a variable COLR font.
  1116. COLR tables are special in that variable subtables can be associated with
  1117. multiple delta-set indices (via VarIndexBase).
  1118. They also contain tables that must change their type (not simply the Format)
  1119. as they become variable (e.g. Affine2x3 -> VarAffine2x3) so this merger takes
  1120. care of that too.
  1121. """
  1122. def __init__(self, model, axisTags, font, allowLayerReuse=True):
  1123. VariationMerger.__init__(self, model, axisTags, font)
  1124. # maps {tuple(varIdxes): VarIndexBase} to facilitate reuse of VarIndexBase
  1125. # between variable tables with same varIdxes.
  1126. self.varIndexCache = {}
  1127. # flat list of all the varIdxes generated while merging
  1128. self.varIdxes = []
  1129. # set of id()s of the subtables that contain variations after merging
  1130. # and need to be upgraded to the associated VarType.
  1131. self.varTableIds = set()
  1132. # we keep these around for rebuilding a LayerList while merging PaintColrLayers
  1133. self.layers = []
  1134. self.layerReuseCache = None
  1135. if allowLayerReuse:
  1136. self.layerReuseCache = LayerReuseCache()
  1137. # flag to ensure BaseGlyphList is fully merged before LayerList gets processed
  1138. self._doneBaseGlyphs = False
  1139. def mergeTables(self, font, master_ttfs, tableTags=("COLR",)):
  1140. if "COLR" in tableTags and "COLR" in font:
  1141. # The merger modifies the destination COLR table in-place. If this contains
  1142. # multiple PaintColrLayers referencing the same layers from LayerList, it's
  1143. # a problem because we may risk modifying the same paint more than once, or
  1144. # worse, fail while attempting to do that.
  1145. # We don't know whether the master COLR table was built with layer reuse
  1146. # disabled, thus to be safe we rebuild its LayerList so that it contains only
  1147. # unique layers referenced from non-overlapping PaintColrLayers throughout
  1148. # the base paint graphs.
  1149. self.expandPaintColrLayers(font["COLR"].table)
  1150. VariationMerger.mergeTables(self, font, master_ttfs, tableTags)
  1151. def checkFormatEnum(self, out, lst, validate=lambda _: True):
  1152. fmt = out.Format
  1153. formatEnum = out.formatEnum
  1154. ok = False
  1155. try:
  1156. fmt = formatEnum(fmt)
  1157. except ValueError:
  1158. pass
  1159. else:
  1160. ok = validate(fmt)
  1161. if not ok:
  1162. raise UnsupportedFormat(self, subtable=type(out).__name__, value=fmt)
  1163. expected = fmt
  1164. got = []
  1165. for v in lst:
  1166. fmt = getattr(v, "Format", None)
  1167. try:
  1168. fmt = formatEnum(fmt)
  1169. except ValueError:
  1170. pass
  1171. got.append(fmt)
  1172. if not allEqualTo(expected, got):
  1173. raise InconsistentFormats(
  1174. self,
  1175. subtable=type(out).__name__,
  1176. expected=expected,
  1177. got=got,
  1178. )
  1179. return expected
  1180. def mergeSparseDict(self, out, lst):
  1181. for k in out.keys():
  1182. try:
  1183. self.mergeThings(out[k], [v.get(k) for v in lst])
  1184. except VarLibMergeError as e:
  1185. e.stack.append(f"[{k!r}]")
  1186. raise
  1187. def mergeAttrs(self, out, lst, attrs):
  1188. for attr in attrs:
  1189. value = getattr(out, attr)
  1190. values = [getattr(item, attr) for item in lst]
  1191. try:
  1192. self.mergeThings(value, values)
  1193. except VarLibMergeError as e:
  1194. e.stack.append(f".{attr}")
  1195. raise
  1196. def storeMastersForAttr(self, out, lst, attr):
  1197. master_values = [getattr(item, attr) for item in lst]
  1198. # VarStore treats deltas for fixed-size floats as integers, so we
  1199. # must convert master values to int before storing them in the builder
  1200. # then back to float.
  1201. is_fixed_size_float = False
  1202. conv = out.getConverterByName(attr)
  1203. if isinstance(conv, BaseFixedValue):
  1204. is_fixed_size_float = True
  1205. master_values = [conv.toInt(v) for v in master_values]
  1206. baseValue = master_values[0]
  1207. varIdx = ot.NO_VARIATION_INDEX
  1208. if not allEqual(master_values):
  1209. baseValue, varIdx = self.store_builder.storeMasters(master_values)
  1210. if is_fixed_size_float:
  1211. baseValue = conv.fromInt(baseValue)
  1212. return baseValue, varIdx
  1213. def storeVariationIndices(self, varIdxes) -> int:
  1214. # try to reuse an existing VarIndexBase for the same varIdxes, or else
  1215. # create a new one
  1216. key = tuple(varIdxes)
  1217. varIndexBase = self.varIndexCache.get(key)
  1218. if varIndexBase is None:
  1219. # scan for a full match anywhere in the self.varIdxes
  1220. for i in range(len(self.varIdxes) - len(varIdxes) + 1):
  1221. if self.varIdxes[i : i + len(varIdxes)] == varIdxes:
  1222. self.varIndexCache[key] = varIndexBase = i
  1223. break
  1224. if varIndexBase is None:
  1225. # try find a partial match at the end of the self.varIdxes
  1226. for n in range(len(varIdxes) - 1, 0, -1):
  1227. if self.varIdxes[-n:] == varIdxes[:n]:
  1228. varIndexBase = len(self.varIdxes) - n
  1229. self.varIndexCache[key] = varIndexBase
  1230. self.varIdxes.extend(varIdxes[n:])
  1231. break
  1232. if varIndexBase is None:
  1233. # no match found, append at the end
  1234. self.varIndexCache[key] = varIndexBase = len(self.varIdxes)
  1235. self.varIdxes.extend(varIdxes)
  1236. return varIndexBase
  1237. def mergeVariableAttrs(self, out, lst, attrs) -> int:
  1238. varIndexBase = ot.NO_VARIATION_INDEX
  1239. varIdxes = []
  1240. for attr in attrs:
  1241. baseValue, varIdx = self.storeMastersForAttr(out, lst, attr)
  1242. setattr(out, attr, baseValue)
  1243. varIdxes.append(varIdx)
  1244. if any(v != ot.NO_VARIATION_INDEX for v in varIdxes):
  1245. varIndexBase = self.storeVariationIndices(varIdxes)
  1246. return varIndexBase
  1247. @classmethod
  1248. def convertSubTablesToVarType(cls, table):
  1249. for path in dfs_base_table(
  1250. table,
  1251. skip_root=True,
  1252. predicate=lambda path: (
  1253. getattr(type(path[-1].value), "VarType", None) is not None
  1254. ),
  1255. ):
  1256. st = path[-1]
  1257. subTable = st.value
  1258. varType = type(subTable).VarType
  1259. newSubTable = varType()
  1260. newSubTable.__dict__.update(subTable.__dict__)
  1261. newSubTable.populateDefaults()
  1262. parent = path[-2].value
  1263. if st.index is not None:
  1264. getattr(parent, st.name)[st.index] = newSubTable
  1265. else:
  1266. setattr(parent, st.name, newSubTable)
  1267. @staticmethod
  1268. def expandPaintColrLayers(colr):
  1269. """Rebuild LayerList without PaintColrLayers reuse.
  1270. Each base paint graph is fully DFS-traversed (with exception of PaintColrGlyph
  1271. which are irrelevant for this); any layers referenced via PaintColrLayers are
  1272. collected into a new LayerList and duplicated when reuse is detected, to ensure
  1273. that all paints are distinct objects at the end of the process.
  1274. PaintColrLayers's FirstLayerIndex/NumLayers are updated so that no overlap
  1275. is left. Also, any consecutively nested PaintColrLayers are flattened.
  1276. The COLR table's LayerList is replaced with the new unique layers.
  1277. A side effect is also that any layer from the old LayerList which is not
  1278. referenced by any PaintColrLayers is dropped.
  1279. """
  1280. if not colr.LayerList:
  1281. # if no LayerList, there's nothing to expand
  1282. return
  1283. uniqueLayerIDs = set()
  1284. newLayerList = []
  1285. for rec in colr.BaseGlyphList.BaseGlyphPaintRecord:
  1286. frontier = [rec.Paint]
  1287. while frontier:
  1288. paint = frontier.pop()
  1289. if paint.Format == ot.PaintFormat.PaintColrGlyph:
  1290. # don't traverse these, we treat them as constant for merging
  1291. continue
  1292. elif paint.Format == ot.PaintFormat.PaintColrLayers:
  1293. # de-treeify any nested PaintColrLayers, append unique copies to
  1294. # the new layer list and update PaintColrLayers index/count
  1295. children = list(_flatten_layers(paint, colr))
  1296. first_layer_index = len(newLayerList)
  1297. for layer in children:
  1298. if id(layer) in uniqueLayerIDs:
  1299. layer = copy.deepcopy(layer)
  1300. assert id(layer) not in uniqueLayerIDs
  1301. newLayerList.append(layer)
  1302. uniqueLayerIDs.add(id(layer))
  1303. paint.FirstLayerIndex = first_layer_index
  1304. paint.NumLayers = len(children)
  1305. else:
  1306. children = paint.getChildren(colr)
  1307. frontier.extend(reversed(children))
  1308. # sanity check all the new layers are distinct objects
  1309. assert len(newLayerList) == len(uniqueLayerIDs)
  1310. colr.LayerList.Paint = newLayerList
  1311. colr.LayerList.LayerCount = len(newLayerList)
  1312. @COLRVariationMerger.merger(ot.BaseGlyphList)
  1313. def merge(merger, self, lst):
  1314. # ignore BaseGlyphCount, allow sparse glyph sets across masters
  1315. out = {rec.BaseGlyph: rec for rec in self.BaseGlyphPaintRecord}
  1316. masters = [{rec.BaseGlyph: rec for rec in m.BaseGlyphPaintRecord} for m in lst]
  1317. for i, g in enumerate(out.keys()):
  1318. try:
  1319. # missing base glyphs don't participate in the merge
  1320. merger.mergeThings(out[g], [v.get(g) for v in masters])
  1321. except VarLibMergeError as e:
  1322. e.stack.append(f".BaseGlyphPaintRecord[{i}]")
  1323. e.cause["location"] = f"base glyph {g!r}"
  1324. raise
  1325. merger._doneBaseGlyphs = True
  1326. @COLRVariationMerger.merger(ot.LayerList)
  1327. def merge(merger, self, lst):
  1328. # nothing to merge for LayerList, assuming we have already merged all PaintColrLayers
  1329. # found while traversing the paint graphs rooted at BaseGlyphPaintRecords.
  1330. assert merger._doneBaseGlyphs, "BaseGlyphList must be merged before LayerList"
  1331. # Simply flush the final list of layers and go home.
  1332. self.LayerCount = len(merger.layers)
  1333. self.Paint = merger.layers
  1334. def _flatten_layers(root, colr):
  1335. assert root.Format == ot.PaintFormat.PaintColrLayers
  1336. for paint in root.getChildren(colr):
  1337. if paint.Format == ot.PaintFormat.PaintColrLayers:
  1338. yield from _flatten_layers(paint, colr)
  1339. else:
  1340. yield paint
  1341. def _merge_PaintColrLayers(self, out, lst):
  1342. # we only enforce that the (flat) number of layers is the same across all masters
  1343. # but we allow FirstLayerIndex to differ to acommodate for sparse glyph sets.
  1344. out_layers = list(_flatten_layers(out, self.font["COLR"].table))
  1345. # sanity check ttfs are subset to current values (see VariationMerger.mergeThings)
  1346. # before matching each master PaintColrLayers to its respective COLR by position
  1347. assert len(self.ttfs) == len(lst)
  1348. master_layerses = [
  1349. list(_flatten_layers(lst[i], self.ttfs[i]["COLR"].table))
  1350. for i in range(len(lst))
  1351. ]
  1352. try:
  1353. self.mergeLists(out_layers, master_layerses)
  1354. except VarLibMergeError as e:
  1355. # NOTE: This attribute doesn't actually exist in PaintColrLayers but it's
  1356. # handy to have it in the stack trace for debugging.
  1357. e.stack.append(".Layers")
  1358. raise
  1359. # following block is very similar to LayerListBuilder._beforeBuildPaintColrLayers
  1360. # but I couldn't find a nice way to share the code between the two...
  1361. if self.layerReuseCache is not None:
  1362. # successful reuse can make the list smaller
  1363. out_layers = self.layerReuseCache.try_reuse(out_layers)
  1364. # if the list is still too big we need to tree-fy it
  1365. is_tree = len(out_layers) > MAX_PAINT_COLR_LAYER_COUNT
  1366. out_layers = build_n_ary_tree(out_layers, n=MAX_PAINT_COLR_LAYER_COUNT)
  1367. # We now have a tree of sequences with Paint leaves.
  1368. # Convert the sequences into PaintColrLayers.
  1369. def listToColrLayers(paint):
  1370. if isinstance(paint, list):
  1371. layers = [listToColrLayers(l) for l in paint]
  1372. paint = ot.Paint()
  1373. paint.Format = int(ot.PaintFormat.PaintColrLayers)
  1374. paint.NumLayers = len(layers)
  1375. paint.FirstLayerIndex = len(self.layers)
  1376. self.layers.extend(layers)
  1377. if self.layerReuseCache is not None:
  1378. self.layerReuseCache.add(layers, paint.FirstLayerIndex)
  1379. return paint
  1380. out_layers = [listToColrLayers(l) for l in out_layers]
  1381. if len(out_layers) == 1 and out_layers[0].Format == ot.PaintFormat.PaintColrLayers:
  1382. # special case when the reuse cache finds a single perfect PaintColrLayers match
  1383. # (it can only come from a successful reuse, _flatten_layers has gotten rid of
  1384. # all nested PaintColrLayers already); we assign it directly and avoid creating
  1385. # an extra table
  1386. out.NumLayers = out_layers[0].NumLayers
  1387. out.FirstLayerIndex = out_layers[0].FirstLayerIndex
  1388. else:
  1389. out.NumLayers = len(out_layers)
  1390. out.FirstLayerIndex = len(self.layers)
  1391. self.layers.extend(out_layers)
  1392. # Register our parts for reuse provided we aren't a tree
  1393. # If we are a tree the leaves registered for reuse and that will suffice
  1394. if self.layerReuseCache is not None and not is_tree:
  1395. self.layerReuseCache.add(out_layers, out.FirstLayerIndex)
  1396. @COLRVariationMerger.merger((ot.Paint, ot.ClipBox))
  1397. def merge(merger, self, lst):
  1398. fmt = merger.checkFormatEnum(self, lst, lambda fmt: not fmt.is_variable())
  1399. if fmt is ot.PaintFormat.PaintColrLayers:
  1400. _merge_PaintColrLayers(merger, self, lst)
  1401. return
  1402. varFormat = fmt.as_variable()
  1403. varAttrs = ()
  1404. if varFormat is not None:
  1405. varAttrs = otBase.getVariableAttrs(type(self), varFormat)
  1406. staticAttrs = (c.name for c in self.getConverters() if c.name not in varAttrs)
  1407. merger.mergeAttrs(self, lst, staticAttrs)
  1408. varIndexBase = merger.mergeVariableAttrs(self, lst, varAttrs)
  1409. subTables = [st.value for st in self.iterSubTables()]
  1410. # Convert table to variable if itself has variations or any subtables have
  1411. isVariable = varIndexBase != ot.NO_VARIATION_INDEX or any(
  1412. id(table) in merger.varTableIds for table in subTables
  1413. )
  1414. if isVariable:
  1415. if varAttrs:
  1416. # Some PaintVar* don't have any scalar attributes that can vary,
  1417. # only indirect offsets to other variable subtables, thus have
  1418. # no VarIndexBase of their own (e.g. PaintVarTransform)
  1419. self.VarIndexBase = varIndexBase
  1420. if subTables:
  1421. # Convert Affine2x3 -> VarAffine2x3, ColorLine -> VarColorLine, etc.
  1422. merger.convertSubTablesToVarType(self)
  1423. assert varFormat is not None
  1424. self.Format = int(varFormat)
  1425. @COLRVariationMerger.merger((ot.Affine2x3, ot.ColorStop))
  1426. def merge(merger, self, lst):
  1427. varType = type(self).VarType
  1428. varAttrs = otBase.getVariableAttrs(varType)
  1429. staticAttrs = (c.name for c in self.getConverters() if c.name not in varAttrs)
  1430. merger.mergeAttrs(self, lst, staticAttrs)
  1431. varIndexBase = merger.mergeVariableAttrs(self, lst, varAttrs)
  1432. if varIndexBase != ot.NO_VARIATION_INDEX:
  1433. self.VarIndexBase = varIndexBase
  1434. # mark as having variations so the parent table will convert to Var{Type}
  1435. merger.varTableIds.add(id(self))
  1436. @COLRVariationMerger.merger(ot.ColorLine)
  1437. def merge(merger, self, lst):
  1438. merger.mergeAttrs(self, lst, (c.name for c in self.getConverters()))
  1439. if any(id(stop) in merger.varTableIds for stop in self.ColorStop):
  1440. merger.convertSubTablesToVarType(self)
  1441. merger.varTableIds.add(id(self))
  1442. @COLRVariationMerger.merger(ot.ClipList, "clips")
  1443. def merge(merger, self, lst):
  1444. # 'sparse' in that we allow non-default masters to omit ClipBox entries
  1445. # for some/all glyphs (i.e. they don't participate)
  1446. merger.mergeSparseDict(self, lst)