id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
175,262
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def nonNone(lst): def allNone(lst): def allEqual(lst, mapper=None): class ShouldBeConstant(VarLibMergeError): def details(self): class NotANone(VarLibMergeError): def offender(self): def details(self): def merge(merger, self, lst): if self is None: if not allNone(lst): raise NotANone(merger, expected=None, got=lst) return lst = [l.classDefs for l in lst] self.classDefs = {} # We only care about the .classDefs self = self.classDefs allKeys = set() allKeys.update(*[l.keys() for l in lst]) for k in allKeys: allValues = nonNone(l.get(k) for l in lst) if not allEqual(allValues): raise ShouldBeConstant( merger, expected=allValues[0], got=lst, stack=["." + k] ) if not allValues: self[k] = None else: self[k] = allValues[0]
null
175,263
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def _SinglePosUpgradeToFormat2(self): if self.Format == 2: return self ret = ot.SinglePos() ret.Format = 2 ret.Coverage = self.Coverage ret.ValueFormat = self.ValueFormat ret.Value = [self.Value for _ in ret.Coverage.glyphs] ret.ValueCount = len(ret.Value) return ret def _merge_GlyphOrders(font, lst, values_lst=None, default=None): """Takes font and list of glyph lists (must be sorted by glyph id), and returns two things: - Combined glyph list, - If values_lst is None, return input glyph lists, but padded with None when a glyph was missing in a list. Otherwise, return values_lst list-of-list, padded with None to match combined glyph lists. """ if values_lst is None: dict_sets = [set(l) for l in lst] else: dict_sets = [{g: v for g, v in zip(l, vs)} for l, vs in zip(lst, values_lst)] combined = set() combined.update(*dict_sets) sortKey = font.getReverseGlyphMap().__getitem__ order = sorted(combined, key=sortKey) # Make sure all input glyphsets were in proper order if not all(sorted(vs, key=sortKey) == vs for vs in lst): raise InconsistentGlyphOrder() del combined paddedValues = None if values_lst is None: padded = [ [glyph if glyph in dict_set else default for glyph in order] for dict_set in dict_sets ] else: assert len(lst) == len(values_lst) padded = [ [dict_set[glyph] if glyph in dict_set else default for glyph in order] for dict_set in dict_sets ] return order, padded def _Lookup_SinglePos_get_effective_value(merger, subtables, glyph): for self in subtables: if ( self is None or type(self) != ot.SinglePos or self.Coverage is None or glyph not in self.Coverage.glyphs ): continue if self.Format == 1: return self.Value elif self.Format == 2: return self.Value[self.Coverage.glyphs.index(glyph)] else: raise UnsupportedFormat(merger, subtable="single positioning lookup") return None def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... class UnsupportedFormat(VarLibMergeError): """an OpenType subtable (%s) had a format I didn't expect""" def __init__(self, merger=None, **kwargs): super().__init__(merger, **kwargs) if not self.stack: self.stack = [".Format"] def reason(self): s = self.__doc__ % self.cause["subtable"] if "value" in self.cause: s += f" ({self.cause['value']!r})" return s def merge(merger, self, lst): self.ValueFormat = valueFormat = reduce(int.__or__, [l.ValueFormat for l in lst], 0) if not (len(lst) == 1 or (valueFormat & ~0xF == 0)): raise UnsupportedFormat(merger, subtable="single positioning lookup") # If all have same coverage table and all are format 1, coverageGlyphs = self.Coverage.glyphs if all(v.Format == 1 for v in lst) and all( coverageGlyphs == v.Coverage.glyphs for v in lst ): self.Value = otBase.ValueRecord(valueFormat, self.Value) if valueFormat != 0: merger.mergeThings(self.Value, [v.Value for v in lst]) self.ValueFormat = self.Value.getFormat() return # Upgrade everything to Format=2 self.Format = 2 lst = [_SinglePosUpgradeToFormat2(v) for v in lst] # Align them glyphs, padded = _merge_GlyphOrders( merger.font, [v.Coverage.glyphs for v in lst], [v.Value for v in lst] ) self.Coverage.glyphs = glyphs self.Value = [otBase.ValueRecord(valueFormat) for _ in glyphs] self.ValueCount = len(self.Value) for i, values in enumerate(padded): for j, glyph in enumerate(glyphs): if values[j] is not None: continue # Fill in value from other subtables # Note!!! This *might* result in behavior change if ValueFormat2-zeroedness # is different between used subtable and current subtable! # TODO(behdad) Check and warn if that happens? v = _Lookup_SinglePos_get_effective_value( merger, merger.lookup_subtables[i], glyph ) if v is None: v = otBase.ValueRecord(valueFormat) values[j] = v merger.mergeLists(self.Value, padded) # Merge everything else; though, there shouldn't be anything else. :) merger.mergeObjects( self, lst, exclude=("Format", "Coverage", "Value", "ValueCount", "ValueFormat") ) self.ValueFormat = reduce( int.__or__, [v.getEffectiveFormat() for v in self.Value], 0 )
null
175,264
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def _merge_GlyphOrders(font, lst, values_lst=None, default=None): """Takes font and list of glyph lists (must be sorted by glyph id), and returns two things: - Combined glyph list, - If values_lst is None, return input glyph lists, but padded with None when a glyph was missing in a list. Otherwise, return values_lst list-of-list, padded with None to match combined glyph lists. """ if values_lst is None: dict_sets = [set(l) for l in lst] else: dict_sets = [{g: v for g, v in zip(l, vs)} for l, vs in zip(lst, values_lst)] combined = set() combined.update(*dict_sets) sortKey = font.getReverseGlyphMap().__getitem__ order = sorted(combined, key=sortKey) # Make sure all input glyphsets were in proper order if not all(sorted(vs, key=sortKey) == vs for vs in lst): raise InconsistentGlyphOrder() del combined paddedValues = None if values_lst is None: padded = [ [glyph if glyph in dict_set else default for glyph in order] for dict_set in dict_sets ] else: assert len(lst) == len(values_lst) padded = [ [dict_set[glyph] if glyph in dict_set else default for glyph in order] for dict_set in dict_sets ] return order, padded def _Lookup_PairPos_get_effective_value_pair( merger, subtables, firstGlyph, secondGlyph ): for self in subtables: if ( self is None or type(self) != ot.PairPos or self.Coverage is None or firstGlyph not in self.Coverage.glyphs ): continue if self.Format == 1: ps = self.PairSet[self.Coverage.glyphs.index(firstGlyph)] pvr = ps.PairValueRecord for rec in pvr: # TODO Speed up if rec.SecondGlyph == secondGlyph: return rec continue elif self.Format == 2: klass1 = self.ClassDef1.classDefs.get(firstGlyph, 0) klass2 = self.ClassDef2.classDefs.get(secondGlyph, 0) return self.Class1Record[klass1].Class2Record[klass2] else: raise UnsupportedFormat(merger, subtable="pair positioning lookup") return None def merge(merger, self, lst): # Align them glyphs, padded = _merge_GlyphOrders( merger.font, [[v.SecondGlyph for v in vs.PairValueRecord] for vs in lst], [vs.PairValueRecord for vs in lst], ) self.PairValueRecord = pvrs = [] for glyph in glyphs: pvr = ot.PairValueRecord() pvr.SecondGlyph = glyph pvr.Value1 = ( otBase.ValueRecord(merger.valueFormat1) if merger.valueFormat1 else None ) pvr.Value2 = ( otBase.ValueRecord(merger.valueFormat2) if merger.valueFormat2 else None ) pvrs.append(pvr) self.PairValueCount = len(self.PairValueRecord) for i, values in enumerate(padded): for j, glyph in enumerate(glyphs): # Fill in value from other subtables v = ot.PairValueRecord() v.SecondGlyph = glyph if values[j] is not None: vpair = values[j] else: vpair = _Lookup_PairPos_get_effective_value_pair( merger, merger.lookup_subtables[i], self._firstGlyph, glyph ) if vpair is None: v1, v2 = None, None else: v1 = getattr(vpair, "Value1", None) v2 = getattr(vpair, "Value2", None) v.Value1 = ( otBase.ValueRecord(merger.valueFormat1, src=v1) if merger.valueFormat1 else None ) v.Value2 = ( otBase.ValueRecord(merger.valueFormat2, src=v2) if merger.valueFormat2 else None ) values[j] = v del self._firstGlyph merger.mergeLists(self.PairValueRecord, padded)
null
175,265
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def _PairPosFormat1_merge(self, lst, merger): assert allEqual( [l.ValueFormat2 == 0 for l in lst if l.PairSet] ), "Report bug against fonttools." # Merge everything else; makes sure Format is the same. merger.mergeObjects( self, lst, exclude=("Coverage", "PairSet", "PairSetCount", "ValueFormat1", "ValueFormat2"), ) empty = ot.PairSet() empty.PairValueRecord = [] empty.PairValueCount = 0 # Align them glyphs, padded = _merge_GlyphOrders( merger.font, [v.Coverage.glyphs for v in lst], [v.PairSet for v in lst], default=empty, ) self.Coverage.glyphs = glyphs self.PairSet = [ot.PairSet() for _ in glyphs] self.PairSetCount = len(self.PairSet) for glyph, ps in zip(glyphs, self.PairSet): ps._firstGlyph = glyph merger.mergeLists(self.PairSet, padded) def _PairPosFormat2_merge(self, lst, merger): assert allEqual( [l.ValueFormat2 == 0 for l in lst if l.Class1Record] ), "Report bug against fonttools." merger.mergeObjects( self, lst, exclude=( "Coverage", "ClassDef1", "Class1Count", "ClassDef2", "Class2Count", "Class1Record", "ValueFormat1", "ValueFormat2", ), ) # Align coverages glyphs, _ = _merge_GlyphOrders(merger.font, [v.Coverage.glyphs for v in lst]) self.Coverage.glyphs = glyphs # Currently, if the coverage of PairPosFormat2 subtables are different, # we do NOT bother walking down the subtable list when filling in new # rows for alignment. As such, this is only correct if current subtable # is the last subtable in the lookup. Ensure that. # # Note that our canonicalization process merges trailing PairPosFormat2's, # so in reality this is rare. for l, subtables in zip(lst, merger.lookup_subtables): if l.Coverage.glyphs != glyphs: assert l == subtables[-1] matrices = _PairPosFormat2_align_matrices(self, lst, merger.font) self.Class1Record = list(matrices[0]) # TODO move merger to be selfless merger.mergeLists(self.Class1Record, matrices) def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... class UnsupportedFormat(VarLibMergeError): """an OpenType subtable (%s) had a format I didn't expect""" def __init__(self, merger=None, **kwargs): super().__init__(merger, **kwargs) if not self.stack: self.stack = [".Format"] def reason(self): s = self.__doc__ % self.cause["subtable"] if "value" in self.cause: s += f" ({self.cause['value']!r})" return s def merge(merger, self, lst): merger.valueFormat1 = self.ValueFormat1 = reduce( int.__or__, [l.ValueFormat1 for l in lst], 0 ) merger.valueFormat2 = self.ValueFormat2 = reduce( int.__or__, [l.ValueFormat2 for l in lst], 0 ) if self.Format == 1: _PairPosFormat1_merge(self, lst, merger) elif self.Format == 2: _PairPosFormat2_merge(self, lst, merger) else: raise UnsupportedFormat(merger, subtable="pair positioning lookup") del merger.valueFormat1, merger.valueFormat2 # Now examine the list of value records, and update to the union of format values, # as merge might have created new values. vf1 = 0 vf2 = 0 if self.Format == 1: for pairSet in self.PairSet: for pairValueRecord in pairSet.PairValueRecord: pv1 = getattr(pairValueRecord, "Value1", None) if pv1 is not None: vf1 |= pv1.getFormat() pv2 = getattr(pairValueRecord, "Value2", None) if pv2 is not None: vf2 |= pv2.getFormat() elif self.Format == 2: for class1Record in self.Class1Record: for class2Record in class1Record.Class2Record: pv1 = getattr(class2Record, "Value1", None) if pv1 is not None: vf1 |= pv1.getFormat() pv2 = getattr(class2Record, "Value2", None) if pv2 is not None: vf2 |= pv2.getFormat() self.ValueFormat1 = vf1 self.ValueFormat2 = vf2
null
175,266
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def _MarkBasePosFormat1_merge(self, lst, merger, Mark="Mark", Base="Base"): self.ClassCount = max(l.ClassCount for l in lst) MarkCoverageGlyphs, MarkRecords = _merge_GlyphOrders( merger.font, [getattr(l, Mark + "Coverage").glyphs for l in lst], [getattr(l, Mark + "Array").MarkRecord for l in lst], ) getattr(self, Mark + "Coverage").glyphs = MarkCoverageGlyphs BaseCoverageGlyphs, BaseRecords = _merge_GlyphOrders( merger.font, [getattr(l, Base + "Coverage").glyphs for l in lst], [getattr(getattr(l, Base + "Array"), Base + "Record") for l in lst], ) getattr(self, Base + "Coverage").glyphs = BaseCoverageGlyphs # MarkArray records = [] for g, glyphRecords in zip(MarkCoverageGlyphs, zip(*MarkRecords)): allClasses = [r.Class for r in glyphRecords if r is not None] # TODO Right now we require that all marks have same class in # all masters that cover them. This is not required. # # We can relax that by just requiring that all marks that have # the same class in a master, have the same class in every other # master. Indeed, if, say, a sparse master only covers one mark, # that mark probably will get class 0, which would possibly be # different from its class in other masters. # # We can even go further and reclassify marks to support any # input. But, since, it's unlikely that two marks being both, # say, "top" in one master, and one being "top" and other being # "top-right" in another master, we shouldn't do that, as any # failures in that case will probably signify mistakes in the # input masters. if not allEqual(allClasses): raise ShouldBeConstant(merger, expected=allClasses[0], got=allClasses) else: rec = ot.MarkRecord() rec.Class = allClasses[0] allAnchors = [None if r is None else r.MarkAnchor for r in glyphRecords] if allNone(allAnchors): anchor = None else: anchor = ot.Anchor() anchor.Format = 1 merger.mergeThings(anchor, allAnchors) rec.MarkAnchor = anchor records.append(rec) array = ot.MarkArray() array.MarkRecord = records array.MarkCount = len(records) setattr(self, Mark + "Array", array) # BaseArray records = [] for g, glyphRecords in zip(BaseCoverageGlyphs, zip(*BaseRecords)): if allNone(glyphRecords): rec = None else: rec = getattr(ot, Base + "Record")() anchors = [] setattr(rec, Base + "Anchor", anchors) glyphAnchors = [ [] if r is None else getattr(r, Base + "Anchor") for r in glyphRecords ] for l in glyphAnchors: l.extend([None] * (self.ClassCount - len(l))) for allAnchors in zip(*glyphAnchors): if allNone(allAnchors): anchor = None else: anchor = ot.Anchor() anchor.Format = 1 merger.mergeThings(anchor, allAnchors) anchors.append(anchor) records.append(rec) array = getattr(ot, Base + "Array")() setattr(array, Base + "Record", records) setattr(array, Base + "Count", len(records)) setattr(self, Base + "Array", array) def allEqualTo(ref, lst, mapper=None): if mapper is None: return all(ref == item for item in lst) mapped = mapper(ref) return all(mapped == mapper(item) for item in lst) class UnsupportedFormat(VarLibMergeError): """an OpenType subtable (%s) had a format I didn't expect""" def __init__(self, merger=None, **kwargs): super().__init__(merger, **kwargs) if not self.stack: self.stack = [".Format"] def reason(self): s = self.__doc__ % self.cause["subtable"] if "value" in self.cause: s += f" ({self.cause['value']!r})" return s class InconsistentFormats(UnsupportedFormat): """an OpenType subtable (%s) had inconsistent formats between masters""" def merge(merger, self, lst): if not allEqualTo(self.Format, (l.Format for l in lst)): raise InconsistentFormats( merger, subtable="mark-to-base positioning lookup", expected=self.Format, got=[l.Format for l in lst], ) if self.Format == 1: _MarkBasePosFormat1_merge(self, lst, merger) else: raise UnsupportedFormat(merger, subtable="mark-to-base positioning lookup")
null
175,267
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def _MarkBasePosFormat1_merge(self, lst, merger, Mark="Mark", Base="Base"): self.ClassCount = max(l.ClassCount for l in lst) MarkCoverageGlyphs, MarkRecords = _merge_GlyphOrders( merger.font, [getattr(l, Mark + "Coverage").glyphs for l in lst], [getattr(l, Mark + "Array").MarkRecord for l in lst], ) getattr(self, Mark + "Coverage").glyphs = MarkCoverageGlyphs BaseCoverageGlyphs, BaseRecords = _merge_GlyphOrders( merger.font, [getattr(l, Base + "Coverage").glyphs for l in lst], [getattr(getattr(l, Base + "Array"), Base + "Record") for l in lst], ) getattr(self, Base + "Coverage").glyphs = BaseCoverageGlyphs # MarkArray records = [] for g, glyphRecords in zip(MarkCoverageGlyphs, zip(*MarkRecords)): allClasses = [r.Class for r in glyphRecords if r is not None] # TODO Right now we require that all marks have same class in # all masters that cover them. This is not required. # # We can relax that by just requiring that all marks that have # the same class in a master, have the same class in every other # master. Indeed, if, say, a sparse master only covers one mark, # that mark probably will get class 0, which would possibly be # different from its class in other masters. # # We can even go further and reclassify marks to support any # input. But, since, it's unlikely that two marks being both, # say, "top" in one master, and one being "top" and other being # "top-right" in another master, we shouldn't do that, as any # failures in that case will probably signify mistakes in the # input masters. if not allEqual(allClasses): raise ShouldBeConstant(merger, expected=allClasses[0], got=allClasses) else: rec = ot.MarkRecord() rec.Class = allClasses[0] allAnchors = [None if r is None else r.MarkAnchor for r in glyphRecords] if allNone(allAnchors): anchor = None else: anchor = ot.Anchor() anchor.Format = 1 merger.mergeThings(anchor, allAnchors) rec.MarkAnchor = anchor records.append(rec) array = ot.MarkArray() array.MarkRecord = records array.MarkCount = len(records) setattr(self, Mark + "Array", array) # BaseArray records = [] for g, glyphRecords in zip(BaseCoverageGlyphs, zip(*BaseRecords)): if allNone(glyphRecords): rec = None else: rec = getattr(ot, Base + "Record")() anchors = [] setattr(rec, Base + "Anchor", anchors) glyphAnchors = [ [] if r is None else getattr(r, Base + "Anchor") for r in glyphRecords ] for l in glyphAnchors: l.extend([None] * (self.ClassCount - len(l))) for allAnchors in zip(*glyphAnchors): if allNone(allAnchors): anchor = None else: anchor = ot.Anchor() anchor.Format = 1 merger.mergeThings(anchor, allAnchors) anchors.append(anchor) records.append(rec) array = getattr(ot, Base + "Array")() setattr(array, Base + "Record", records) setattr(array, Base + "Count", len(records)) setattr(self, Base + "Array", array) def allEqualTo(ref, lst, mapper=None): if mapper is None: return all(ref == item for item in lst) mapped = mapper(ref) return all(mapped == mapper(item) for item in lst) class UnsupportedFormat(VarLibMergeError): """an OpenType subtable (%s) had a format I didn't expect""" def __init__(self, merger=None, **kwargs): super().__init__(merger, **kwargs) if not self.stack: self.stack = [".Format"] def reason(self): s = self.__doc__ % self.cause["subtable"] if "value" in self.cause: s += f" ({self.cause['value']!r})" return s class InconsistentFormats(UnsupportedFormat): """an OpenType subtable (%s) had inconsistent formats between masters""" def merge(merger, self, lst): if not allEqualTo(self.Format, (l.Format for l in lst)): raise InconsistentFormats( merger, subtable="mark-to-mark positioning lookup", expected=self.Format, got=[l.Format for l in lst], ) if self.Format == 1: _MarkBasePosFormat1_merge(self, lst, merger, "Mark1", "Mark2") else: raise UnsupportedFormat(merger, subtable="mark-to-mark positioning lookup")
null
175,268
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) log = logging.getLogger("fontTools.varLib.merger") from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def _Lookup_PairPos_subtables_canonicalize(lst, font): """Merge multiple Format1 subtables at the beginning of lst, and merge multiple consecutive Format2 subtables that have the same Class2 (ie. were split because of offset overflows). Returns new list.""" lst = list(lst) l = len(lst) i = 0 while i < l and lst[i].Format == 1: i += 1 lst[:i] = [_Lookup_PairPosFormat1_subtables_flatten(lst[:i], font)] l = len(lst) i = l while i > 0 and lst[i - 1].Format == 2: i -= 1 lst[i:] = [_Lookup_PairPosFormat2_subtables_flatten(lst[i:], font)] return lst def _Lookup_SinglePos_subtables_flatten(lst, font, min_inclusive_rec_format): glyphs, _ = _merge_GlyphOrders(font, [v.Coverage.glyphs for v in lst], None) num_glyphs = len(glyphs) new = ot.SinglePos() new.Format = 2 new.ValueFormat = min_inclusive_rec_format new.Coverage = ot.Coverage() new.Coverage.glyphs = glyphs new.ValueCount = num_glyphs new.Value = [None] * num_glyphs for singlePos in lst: if singlePos.Format == 1: val_rec = singlePos.Value for gname in singlePos.Coverage.glyphs: i = glyphs.index(gname) new.Value[i] = copy.deepcopy(val_rec) elif singlePos.Format == 2: for j, gname in enumerate(singlePos.Coverage.glyphs): val_rec = singlePos.Value[j] i = glyphs.index(gname) new.Value[i] = copy.deepcopy(val_rec) return [new] def ior(__a: Any, __b: Any) -> Any: ... def allEqual(lst, mapper=None): if not lst: return True it = iter(lst) try: first = next(it) except StopIteration: return True return allEqualTo(first, it, mapper=mapper) def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... def buildSinglePos(mapping, glyphMap): """Builds a list of single adjustment (GPOS1) subtables. This builds a list of SinglePos subtables from a dictionary of glyph names and their positioning adjustments. The format of the subtables are determined to optimize the size of the resulting subtables. See also :func:`buildSinglePosSubtable`. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.SinglePosBuilder` instead. Example:: mapping = { "V": buildValue({ "xAdvance" : +5 }), # ... } subtables = buildSinglePos(pairs, font.getReverseGlyphMap()) Args: mapping (dict): A mapping between glyphnames and ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.SinglePos`` objects. """ result, handled = [], set() # In SinglePos format 1, the covered glyphs all share the same ValueRecord. # In format 2, each glyph has its own ValueRecord, but these records # all have the same properties (eg., all have an X but no Y placement). coverages, masks, values = {}, {}, {} for glyph, value in mapping.items(): key = _getSinglePosValueKey(value) coverages.setdefault(key, []).append(glyph) masks.setdefault(key[0], []).append(key) values[key] = value # If a ValueRecord is shared between multiple glyphs, we generate # a SinglePos format 1 subtable; that is the most compact form. for key, glyphs in coverages.items(): # 5 ushorts is the length of introducing another sublookup if len(glyphs) * _getSinglePosValueSize(key) > 5: format1Mapping = {g: values[key] for g in glyphs} result.append(buildSinglePosSubtable(format1Mapping, glyphMap)) handled.add(key) # In the remaining ValueRecords, look for those whose valueFormat # (the set of used properties) is shared between multiple records. # These will get encoded in format 2. for valueFormat, keys in masks.items(): f2 = [k for k in keys if k not in handled] if len(f2) > 1: format2Mapping = {} for k in f2: format2Mapping.update((g, values[k]) for g in coverages[k]) result.append(buildSinglePosSubtable(format2Mapping, glyphMap)) handled.update(f2) # The remaining ValueRecords are only used by a few glyphs, normally # one. We encode these in format 1 again. for key, glyphs in coverages.items(): if key not in handled: for g in glyphs: st = buildSinglePosSubtable({g: values[key]}, glyphMap) result.append(st) # When the OpenType layout engine traverses the subtables, it will # stop after the first matching subtable. Therefore, we sort the # resulting subtables by decreasing coverage size; this increases # the chance that the layout engine can do an early exit. (Of course, # this would only be true if all glyphs were equally frequent, which # is not really the case; but we do not know their distribution). # If two subtables cover the same number of glyphs, we sort them # by glyph ID so that our output is deterministic. result.sort(key=lambda t: _getSinglePosTableKey(t, glyphMap)) return result def _compression_level_from_env() -> int: env_level = GPOS_COMPACT_MODE_DEFAULT if GPOS_COMPACT_MODE_ENV_KEY in os.environ: import warnings warnings.warn( f"'{GPOS_COMPACT_MODE_ENV_KEY}' environment variable is deprecated. " "Please set the 'fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL' option " "in TTFont.cfg.", DeprecationWarning, ) env_level = os.environ[GPOS_COMPACT_MODE_ENV_KEY] if len(env_level) == 1 and env_level in "0123456789": return int(env_level) raise ValueError(f"Bad {GPOS_COMPACT_MODE_ENV_KEY}={env_level}") def compact_pair_pos( font: TTFont, level: int, subtables: Sequence[otTables.PairPos] ) -> Sequence[otTables.PairPos]: new_subtables = [] for subtable in subtables: if subtable.Format == 1: # Not doing anything to Format 1 (yet?) new_subtables.append(subtable) elif subtable.Format == 2: new_subtables.extend(compact_class_pairs(font, level, subtable)) return new_subtables class InconsistentExtensions(VarLibMergeError): """the masters use extension lookups in inconsistent ways""" def merge(merger, self, lst): subtables = merger.lookup_subtables = [l.SubTable for l in lst] # Remove Extension subtables for l, sts in list(zip(lst, subtables)) + [(self, self.SubTable)]: if not sts: continue if sts[0].__class__.__name__.startswith("Extension"): if not allEqual([st.__class__ for st in sts]): raise InconsistentExtensions( merger, expected="Extension", got=[st.__class__.__name__ for st in sts], ) if not allEqual([st.ExtensionLookupType for st in sts]): raise InconsistentExtensions(merger) l.LookupType = sts[0].ExtensionLookupType new_sts = [st.ExtSubTable for st in sts] del sts[:] sts.extend(new_sts) isPairPos = self.SubTable and isinstance(self.SubTable[0], ot.PairPos) if isPairPos: # AFDKO and feaLib sometimes generate two Format1 subtables instead of one. # Merge those before continuing. # https://github.com/fonttools/fonttools/issues/719 self.SubTable = _Lookup_PairPos_subtables_canonicalize( self.SubTable, merger.font ) subtables = merger.lookup_subtables = [ _Lookup_PairPos_subtables_canonicalize(st, merger.font) for st in subtables ] else: isSinglePos = self.SubTable and isinstance(self.SubTable[0], ot.SinglePos) if isSinglePos: numSubtables = [len(st) for st in subtables] if not all([nums == numSubtables[0] for nums in numSubtables]): # Flatten list of SinglePos subtables to single Format 2 subtable, # with all value records set to the rec format type. # We use buildSinglePos() to optimize the lookup after merging. valueFormatList = [t.ValueFormat for st in subtables for t in st] # Find the minimum value record that can accomodate all the singlePos subtables. mirf = reduce(ior, valueFormatList) self.SubTable = _Lookup_SinglePos_subtables_flatten( self.SubTable, merger.font, mirf ) subtables = merger.lookup_subtables = [ _Lookup_SinglePos_subtables_flatten(st, merger.font, mirf) for st in subtables ] flattened = True else: flattened = False merger.mergeLists(self.SubTable, subtables) self.SubTableCount = len(self.SubTable) if isPairPos: # If format-1 subtable created during canonicalization is empty, remove it. assert len(self.SubTable) >= 1 and self.SubTable[0].Format == 1 if not self.SubTable[0].Coverage.glyphs: self.SubTable.pop(0) self.SubTableCount -= 1 # If format-2 subtable created during canonicalization is empty, remove it. assert len(self.SubTable) >= 1 and self.SubTable[-1].Format == 2 if not self.SubTable[-1].Coverage.glyphs: self.SubTable.pop(-1) self.SubTableCount -= 1 # Compact the merged subtables # This is a good moment to do it because the compaction should create # smaller subtables, which may prevent overflows from happening. # Keep reading the value from the ENV until ufo2ft switches to the config system level = merger.font.cfg.get( "fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL", default=_compression_level_from_env(), ) if level != 0: log.info("Compacting GPOS...") self.SubTable = compact_pair_pos(merger.font, level, self.SubTable) self.SubTableCount = len(self.SubTable) elif isSinglePos and flattened: singlePosTable = self.SubTable[0] glyphs = singlePosTable.Coverage.glyphs # We know that singlePosTable is Format 2, as this is set # in _Lookup_SinglePos_subtables_flatten. singlePosMapping = { gname: valRecord for gname, valRecord in zip(glyphs, singlePosTable.Value) } self.SubTable = buildSinglePos( singlePosMapping, merger.font.getReverseGlyphMap() ) merger.mergeObjects(self, lst, exclude=["SubTable", "SubTableCount"]) del merger.lookup_subtables
null
175,269
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def otRound(value): """Round float value to nearest integer towards ``+Infinity``. The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_) defines the required method for converting floating point values to fixed-point. In particular it specifies the following rounding strategy: for fractional values of 0.5 and higher, take the next higher integer; for other fractional values, truncate. This function rounds the floating-point value according to this strategy in preparation for conversion to fixed-point. Args: value (float): The input floating-point value. Returns float: The rounded value. """ # See this thread for how we ended up with this implementation: # https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166 return int(math.floor(value + 0.5)) def merge(merger, self, lst): assert self.Format == 1 Coords = [a.Coordinate for a in lst] model = merger.model scalars = merger.scalars self.Coordinate = otRound(model.interpolateFromMastersAndScalars(Coords, scalars))
null
175,270
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def otRound(value): """Round float value to nearest integer towards ``+Infinity``. The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_) defines the required method for converting floating point values to fixed-point. In particular it specifies the following rounding strategy: for fractional values of 0.5 and higher, take the next higher integer; for other fractional values, truncate. This function rounds the floating-point value according to this strategy in preparation for conversion to fixed-point. Args: value (float): The input floating-point value. Returns float: The rounded value. """ # See this thread for how we ended up with this implementation: # https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166 return int(math.floor(value + 0.5)) def merge(merger, self, lst): assert self.Format == 1 XCoords = [a.XCoordinate for a in lst] YCoords = [a.YCoordinate for a in lst] model = merger.model scalars = merger.scalars self.XCoordinate = otRound(model.interpolateFromMastersAndScalars(XCoords, scalars)) self.YCoordinate = otRound(model.interpolateFromMastersAndScalars(YCoords, scalars))
null
175,271
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def otRound(value): """Round float value to nearest integer towards ``+Infinity``. The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_) defines the required method for converting floating point values to fixed-point. In particular it specifies the following rounding strategy: for fractional values of 0.5 and higher, take the next higher integer; for other fractional values, truncate. This function rounds the floating-point value according to this strategy in preparation for conversion to fixed-point. Args: value (float): The input floating-point value. Returns float: The rounded value. """ # See this thread for how we ended up with this implementation: # https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166 return int(math.floor(value + 0.5)) def merge(merger, self, lst): model = merger.model scalars = merger.scalars # TODO Handle differing valueformats for name, tableName in [ ("XAdvance", "XAdvDevice"), ("YAdvance", "YAdvDevice"), ("XPlacement", "XPlaDevice"), ("YPlacement", "YPlaDevice"), ]: assert not hasattr(self, tableName) if hasattr(self, name): values = [getattr(a, name, 0) for a in lst] value = otRound(model.interpolateFromMastersAndScalars(values, scalars)) setattr(self, name, value)
null
175,272
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def otRound(value): def merge(merger, self, lst): # Hack till we become selfless. self.__dict__ = lst[0].__dict__.copy() if self.Format != 3: return instancer = merger.instancer dev = self.DeviceTable if merger.deleteVariations: del self.DeviceTable if dev: assert dev.DeltaFormat == 0x8000 varidx = (dev.StartSize << 16) + dev.EndSize delta = otRound(instancer[varidx]) self.Coordinate += delta if merger.deleteVariations: self.Format = 1
null
175,273
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def otRound(value): def merge(merger, self, lst): # Hack till we become selfless. self.__dict__ = lst[0].__dict__.copy() if self.Format != 3: return instancer = merger.instancer for v in "XY": tableName = v + "DeviceTable" if not hasattr(self, tableName): continue dev = getattr(self, tableName) if merger.deleteVariations: delattr(self, tableName) if dev is None: continue assert dev.DeltaFormat == 0x8000 varidx = (dev.StartSize << 16) + dev.EndSize delta = otRound(instancer[varidx]) attr = v + "Coordinate" setattr(self, attr, getattr(self, attr) + delta) if merger.deleteVariations: self.Format = 1
null
175,274
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def otRound(value): """Round float value to nearest integer towards ``+Infinity``. The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_) defines the required method for converting floating point values to fixed-point. In particular it specifies the following rounding strategy: for fractional values of 0.5 and higher, take the next higher integer; for other fractional values, truncate. This function rounds the floating-point value according to this strategy in preparation for conversion to fixed-point. Args: value (float): The input floating-point value. Returns float: The rounded value. """ # See this thread for how we ended up with this implementation: # https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166 return int(math.floor(value + 0.5)) def merge(merger, self, lst): # Hack till we become selfless. self.__dict__ = lst[0].__dict__.copy() instancer = merger.instancer for name, tableName in [ ("XAdvance", "XAdvDevice"), ("YAdvance", "YAdvDevice"), ("XPlacement", "XPlaDevice"), ("YPlacement", "YPlaDevice"), ]: if not hasattr(self, tableName): continue dev = getattr(self, tableName) if merger.deleteVariations: delattr(self, tableName) if dev is None: continue assert dev.DeltaFormat == 0x8000 varidx = (dev.StartSize << 16) + dev.EndSize delta = otRound(instancer[varidx]) setattr(self, name, getattr(self, name, 0) + delta)
null
175,275
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def buildVarDevTable(store_builder, master_values): class UnsupportedFormat(VarLibMergeError): def __init__(self, merger=None, **kwargs): def reason(self): def merge(merger, self, lst): if self.Format != 1: raise UnsupportedFormat(merger, subtable="a baseline coordinate") self.Coordinate, DeviceTable = buildVarDevTable( merger.store_builder, [a.Coordinate for a in lst] ) if DeviceTable: self.Format = 3 self.DeviceTable = DeviceTable
null
175,276
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def buildVarDevTable(store_builder, master_values): if allEqual(master_values): return master_values[0], None base, varIdx = store_builder.storeMasters(master_values) return base, builder.buildVarDevTable(varIdx) class UnsupportedFormat(VarLibMergeError): """an OpenType subtable (%s) had a format I didn't expect""" def __init__(self, merger=None, **kwargs): super().__init__(merger, **kwargs) if not self.stack: self.stack = [".Format"] def reason(self): s = self.__doc__ % self.cause["subtable"] if "value" in self.cause: s += f" ({self.cause['value']!r})" return s def merge(merger, self, lst): if self.Format != 1: raise UnsupportedFormat(merger, subtable="a caret") self.Coordinate, DeviceTable = buildVarDevTable( merger.store_builder, [a.Coordinate for a in lst] ) if DeviceTable: self.Format = 3 self.DeviceTable = DeviceTable
null
175,277
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def buildVarDevTable(store_builder, master_values): if allEqual(master_values): return master_values[0], None base, varIdx = store_builder.storeMasters(master_values) return base, builder.buildVarDevTable(varIdx) class UnsupportedFormat(VarLibMergeError): """an OpenType subtable (%s) had a format I didn't expect""" def __init__(self, merger=None, **kwargs): super().__init__(merger, **kwargs) if not self.stack: self.stack = [".Format"] def reason(self): s = self.__doc__ % self.cause["subtable"] if "value" in self.cause: s += f" ({self.cause['value']!r})" return s def merge(merger, self, lst): if self.Format != 1: raise UnsupportedFormat(merger, subtable="an anchor") self.XCoordinate, XDeviceTable = buildVarDevTable( merger.store_builder, [a.XCoordinate for a in lst] ) self.YCoordinate, YDeviceTable = buildVarDevTable( merger.store_builder, [a.YCoordinate for a in lst] ) if XDeviceTable or YDeviceTable: self.Format = 3 self.XDeviceTable = XDeviceTable self.YDeviceTable = YDeviceTable
null
175,278
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def buildVarDevTable(store_builder, master_values): if allEqual(master_values): return master_values[0], None base, varIdx = store_builder.storeMasters(master_values) return base, builder.buildVarDevTable(varIdx) def merge(merger, self, lst): for name, tableName in [ ("XAdvance", "XAdvDevice"), ("YAdvance", "YAdvDevice"), ("XPlacement", "XPlaDevice"), ("YPlacement", "YPlaDevice"), ]: if hasattr(self, name): value, deviceTable = buildVarDevTable( merger.store_builder, [getattr(a, name, 0) for a in lst] ) setattr(self, name, value) if deviceTable: setattr(self, tableName, deviceTable)
null
175,279
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) class VarLibMergeError(VarLibError): def __init__(self, merger=None, **kwargs): def reason(self): def _master_name(self, ix): def offender(self): def details(self): def __str__(self): def merge(merger, self, lst): # ignore BaseGlyphCount, allow sparse glyph sets across masters out = {rec.BaseGlyph: rec for rec in self.BaseGlyphPaintRecord} masters = [{rec.BaseGlyph: rec for rec in m.BaseGlyphPaintRecord} for m in lst] for i, g in enumerate(out.keys()): try: # missing base glyphs don't participate in the merge merger.mergeThings(out[g], [v.get(g) for v in masters]) except VarLibMergeError as e: e.stack.append(f".BaseGlyphPaintRecord[{i}]") e.cause["location"] = f"base glyph {g!r}" raise merger._doneBaseGlyphs = True
null
175,280
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def merge(merger, self, lst): # nothing to merge for LayerList, assuming we have already merged all PaintColrLayers # found while traversing the paint graphs rooted at BaseGlyphPaintRecords. assert merger._doneBaseGlyphs, "BaseGlyphList must be merged before LayerList" # Simply flush the final list of layers and go home. self.LayerCount = len(merger.layers) self.Paint = merger.layers
null
175,281
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def _merge_PaintColrLayers(self, out, lst): # we only enforce that the (flat) number of layers is the same across all masters # but we allow FirstLayerIndex to differ to acommodate for sparse glyph sets. out_layers = list(_flatten_layers(out, self.font["COLR"].table)) # sanity check ttfs are subset to current values (see VariationMerger.mergeThings) # before matching each master PaintColrLayers to its respective COLR by position assert len(self.ttfs) == len(lst) master_layerses = [ list(_flatten_layers(lst[i], self.ttfs[i]["COLR"].table)) for i in range(len(lst)) ] try: self.mergeLists(out_layers, master_layerses) except VarLibMergeError as e: # NOTE: This attribute doesn't actually exist in PaintColrLayers but it's # handy to have it in the stack trace for debugging. e.stack.append(".Layers") raise # following block is very similar to LayerListBuilder._beforeBuildPaintColrLayers # but I couldn't find a nice way to share the code between the two... if self.layerReuseCache is not None: # successful reuse can make the list smaller out_layers = self.layerReuseCache.try_reuse(out_layers) # if the list is still too big we need to tree-fy it is_tree = len(out_layers) > MAX_PAINT_COLR_LAYER_COUNT out_layers = build_n_ary_tree(out_layers, n=MAX_PAINT_COLR_LAYER_COUNT) # We now have a tree of sequences with Paint leaves. # Convert the sequences into PaintColrLayers. def listToColrLayers(paint): if isinstance(paint, list): layers = [listToColrLayers(l) for l in paint] paint = ot.Paint() paint.Format = int(ot.PaintFormat.PaintColrLayers) paint.NumLayers = len(layers) paint.FirstLayerIndex = len(self.layers) self.layers.extend(layers) if self.layerReuseCache is not None: self.layerReuseCache.add(layers, paint.FirstLayerIndex) return paint out_layers = [listToColrLayers(l) for l in out_layers] if len(out_layers) == 1 and out_layers[0].Format == ot.PaintFormat.PaintColrLayers: # special case when the reuse cache finds a single perfect PaintColrLayers match # (it can only come from a successful reuse, _flatten_layers has gotten rid of # all nested PaintColrLayers already); we assign it directly and avoid creating # an extra table out.NumLayers = out_layers[0].NumLayers out.FirstLayerIndex = out_layers[0].FirstLayerIndex else: out.NumLayers = len(out_layers) out.FirstLayerIndex = len(self.layers) self.layers.extend(out_layers) # Register our parts for reuse provided we aren't a tree # If we are a tree the leaves registered for reuse and that will suffice if self.layerReuseCache is not None and not is_tree: self.layerReuseCache.add(out_layers, out.FirstLayerIndex) def merge(merger, self, lst): fmt = merger.checkFormatEnum(self, lst, lambda fmt: not fmt.is_variable()) if fmt is ot.PaintFormat.PaintColrLayers: _merge_PaintColrLayers(merger, self, lst) return varFormat = fmt.as_variable() varAttrs = () if varFormat is not None: varAttrs = otBase.getVariableAttrs(type(self), varFormat) staticAttrs = (c.name for c in self.getConverters() if c.name not in varAttrs) merger.mergeAttrs(self, lst, staticAttrs) varIndexBase = merger.mergeVariableAttrs(self, lst, varAttrs) subTables = [st.value for st in self.iterSubTables()] # Convert table to variable if itself has variations or any subtables have isVariable = varIndexBase != ot.NO_VARIATION_INDEX or any( id(table) in merger.varTableIds for table in subTables ) if isVariable: if varAttrs: # Some PaintVar* don't have any scalar attributes that can vary, # only indirect offsets to other variable subtables, thus have # no VarIndexBase of their own (e.g. PaintVarTransform) self.VarIndexBase = varIndexBase if subTables: # Convert Affine2x3 -> VarAffine2x3, ColorLine -> VarColorLine, etc. merger.convertSubTablesToVarType(self) assert varFormat is not None self.Format = int(varFormat)
null
175,282
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def merge(merger, self, lst): varType = type(self).VarType varAttrs = otBase.getVariableAttrs(varType) staticAttrs = (c.name for c in self.getConverters() if c.name not in varAttrs) merger.mergeAttrs(self, lst, staticAttrs) varIndexBase = merger.mergeVariableAttrs(self, lst, varAttrs) if varIndexBase != ot.NO_VARIATION_INDEX: self.VarIndexBase = varIndexBase # mark as having variations so the parent table will convert to Var{Type} merger.varTableIds.add(id(self))
null
175,283
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def merge(merger, self, lst): merger.mergeAttrs(self, lst, (c.name for c in self.getConverters())) if any(id(stop) in merger.varTableIds for stop in self.ColorStop): merger.convertSubTablesToVarType(self) merger.varTableIds.add(id(self))
null
175,284
import os import copy import enum from operator import ior import logging from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache from fontTools.misc import classifyTools from fontTools.misc.roundTools import otRound from fontTools.misc.treeTools import build_n_ary_tree from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables import otBase as otBase from fontTools.ttLib.tables.otConverters import BaseFixedValue from fontTools.ttLib.tables.otTraverse import dfs_base_table from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.varLib import builder, models, varStore from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList from fontTools.varLib.varStore import VarStoreInstancer from functools import reduce from fontTools.otlLib.builder import buildSinglePos from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_pair_pos, ) from .errors import ( ShouldBeConstant, FoundANone, MismatchedTypes, NotANone, LengthsDiffer, KeysDiffer, InconsistentGlyphOrder, InconsistentExtensions, InconsistentFormats, UnsupportedFormat, VarLibMergeError, ) def merge(merger, self, lst): # 'sparse' in that we allow non-default masters to omit ClipBox entries # for some/all glyphs (i.e. they don't participate) merger.mergeSparseDict(self, lst)
null
175,285
from fontTools.pens.basePen import AbstractPen, BasePen from fontTools.pens.pointPen import SegmentToPointPen from fontTools.pens.recordingPen import RecordingPen from fontTools.pens.statisticsPen import StatisticsPen from fontTools.pens.momentsPen import OpenContourError from collections import OrderedDict import itertools import sys The provided code snippet includes necessary dependencies for implementing the `_rot_list` function. Write a Python function `def _rot_list(l, k)` to solve the following problem: Rotate list by k items forward. Ie. item at position 0 will be at position k in returned list. Negative k is allowed. Here is the function: def _rot_list(l, k): """Rotate list by k items forward. Ie. item at position 0 will be at position k in returned list. Negative k is allowed.""" n = len(l) k %= n if not k: return l return l[n - k :] + l[: n - k]
Rotate list by k items forward. Ie. item at position 0 will be at position k in returned list. Negative k is allowed.
175,286
from fontTools.pens.basePen import AbstractPen, BasePen from fontTools.pens.pointPen import SegmentToPointPen from fontTools.pens.recordingPen import RecordingPen from fontTools.pens.statisticsPen import StatisticsPen from fontTools.pens.momentsPen import OpenContourError from collections import OrderedDict import itertools import sys def _vdiff(v0, v1): return tuple(b - a for a, b in zip(v0, v1))
null
175,287
from fontTools.pens.basePen import AbstractPen, BasePen from fontTools.pens.pointPen import SegmentToPointPen from fontTools.pens.recordingPen import RecordingPen from fontTools.pens.statisticsPen import StatisticsPen from fontTools.pens.momentsPen import OpenContourError from collections import OrderedDict import itertools import sys def _vlen(vec): v = 0 for x in vec: v += x * x return v
null
175,288
from fontTools.pens.basePen import AbstractPen, BasePen from fontTools.pens.pointPen import SegmentToPointPen from fontTools.pens.recordingPen import RecordingPen from fontTools.pens.statisticsPen import StatisticsPen from fontTools.pens.momentsPen import OpenContourError from collections import OrderedDict import itertools import sys def _complex_vlen(vec): v = 0 for x in vec: v += abs(x) * abs(x) return v
null
175,289
from fontTools.pens.basePen import AbstractPen, BasePen from fontTools.pens.pointPen import SegmentToPointPen from fontTools.pens.recordingPen import RecordingPen from fontTools.pens.statisticsPen import StatisticsPen from fontTools.pens.momentsPen import OpenContourError from collections import OrderedDict import itertools import sys def _matching_cost(G, matching): return sum(G[i][j] for i, j in enumerate(matching)) def min_cost_perfect_bipartite_matching(G): n = len(G) try: from scipy.optimize import linear_sum_assignment rows, cols = linear_sum_assignment(G) assert (rows == list(range(n))).all() return list(cols), _matching_cost(G, cols) except ImportError: pass try: from munkres import Munkres cols = [None] * n for row, col in Munkres().compute(G): cols[row] = col return cols, _matching_cost(G, cols) except ImportError: pass if n > 6: raise Exception("Install Python module 'munkres' or 'scipy >= 0.17.0'") # Otherwise just brute-force permutations = itertools.permutations(range(n)) best = list(next(permutations)) best_cost = _matching_cost(G, best) for p in permutations: cost = _matching_cost(G, p) if cost < best_cost: best, best_cost = list(p), cost return best, best_cost
null
175,290
from fontTools.misc.roundTools import noRound from .errors import VariationModelError def subList(truth, lst): assert len(truth) == len(lst) return [l for l, t in zip(lst, truth) if t]
null
175,291
from fontTools.misc.dictTools import hashdict from fontTools.misc.intTools import popCount from fontTools.ttLib import newTable from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.ttVisitor import TTVisitor from fontTools.otlLib.builder import buildLookup, buildSingleSubstSubtable from collections import OrderedDict from .errors import VarLibError, VarLibValidationError def _checkSubstitutionGlyphsExist(glyphNames, substitutions): referencedGlyphNames = set() for _, substitution in substitutions: referencedGlyphNames |= substitution.keys() referencedGlyphNames |= set(substitution.values()) missing = referencedGlyphNames - glyphNames if missing: raise VarLibValidationError( "Missing glyphs are referenced in conditional substitution rules:" f" {', '.join(missing)}" ) def overlayFeatureVariations(conditionalSubstitutions): """Compute overlaps between all conditional substitutions. The `conditionalSubstitutions` argument is a list of (Region, Substitutions) tuples. A Region is a list of Boxes. A Box is a dict mapping axisTags to (minValue, maxValue) tuples. Irrelevant axes may be omitted and they are interpretted as extending to end of axis in each direction. A Box represents an orthogonal 'rectangular' subset of an N-dimensional design space. A Region represents a more complex subset of an N-dimensional design space, ie. the union of all the Boxes in the Region. For efficiency, Boxes within a Region should ideally not overlap, but functionality is not compromised if they do. The minimum and maximum values are expressed in normalized coordinates. A Substitution is a dict mapping source glyph names to substitute glyph names. Returns data is in similar but different format. Overlaps of distinct substitution Boxes (*not* Regions) are explicitly listed as distinct rules, and rules with the same Box merged. The more specific rules appear earlier in the resulting list. Moreover, instead of just a dictionary of substitutions, a list of dictionaries is returned for substitutions corresponding to each unique space, with each dictionary being identical to one of the input substitution dictionaries. These dictionaries are not merged to allow data sharing when they are converted into font tables. Example:: >>> condSubst = [ ... # A list of (Region, Substitution) tuples. ... ([{"wght": (0.5, 1.0)}], {"dollar": "dollar.rvrn"}), ... ([{"wght": (0.5, 1.0)}], {"dollar": "dollar.rvrn"}), ... ([{"wdth": (0.5, 1.0)}], {"cent": "cent.rvrn"}), ... ([{"wght": (0.5, 1.0), "wdth": (-1, 1.0)}], {"dollar": "dollar.rvrn"}), ... ] >>> from pprint import pprint >>> pprint(overlayFeatureVariations(condSubst)) [({'wdth': (0.5, 1.0), 'wght': (0.5, 1.0)}, [{'dollar': 'dollar.rvrn'}, {'cent': 'cent.rvrn'}]), ({'wdth': (0.5, 1.0)}, [{'cent': 'cent.rvrn'}]), ({'wght': (0.5, 1.0)}, [{'dollar': 'dollar.rvrn'}])] """ # Merge same-substitutions rules, as this creates fewer number oflookups. merged = OrderedDict() for value, key in conditionalSubstitutions: key = hashdict(key) if key in merged: merged[key].extend(value) else: merged[key] = value conditionalSubstitutions = [(v, dict(k)) for k, v in merged.items()] del merged # Merge same-region rules, as this is cheaper. # Also convert boxes to hashdict() # # Reversing is such that earlier entries win in case of conflicting substitution # rules for the same region. merged = OrderedDict() for key, value in reversed(conditionalSubstitutions): key = tuple( sorted( (hashdict(cleanupBox(k)) for k in key), key=lambda d: tuple(sorted(d.items())), ) ) if key in merged: merged[key].update(value) else: merged[key] = dict(value) conditionalSubstitutions = list(reversed(merged.items())) del merged # Overlay # # Rank is the bit-set of the index of all contributing layers. initMapInit = ((hashdict(), 0),) # Initializer representing the entire space boxMap = OrderedDict(initMapInit) # Map from Box to Rank for i, (currRegion, _) in enumerate(conditionalSubstitutions): newMap = OrderedDict(initMapInit) currRank = 1 << i for box, rank in boxMap.items(): for currBox in currRegion: intersection, remainder = overlayBox(currBox, box) if intersection is not None: intersection = hashdict(intersection) newMap[intersection] = newMap.get(intersection, 0) | rank | currRank if remainder is not None: remainder = hashdict(remainder) newMap[remainder] = newMap.get(remainder, 0) | rank boxMap = newMap # Generate output items = [] for box, rank in sorted( boxMap.items(), key=(lambda BoxAndRank: -popCount(BoxAndRank[1])) ): # Skip any box that doesn't have any substitution. if rank == 0: continue substsList = [] i = 0 while rank: if rank & 1: substsList.append(conditionalSubstitutions[i][1]) rank >>= 1 i += 1 items.append((dict(box), substsList)) return items def addFeatureVariationsRaw(font, table, conditionalSubstitutions, featureTag="rvrn"): """Low level implementation of addFeatureVariations that directly models the possibilities of the FeatureVariations table.""" # # if there is no <featureTag> feature: # make empty <featureTag> feature # sort features, get <featureTag> feature index # add <featureTag> feature to all scripts # make lookups # add feature variations # if table.Version < 0x00010001: table.Version = 0x00010001 # allow table.FeatureVariations table.FeatureVariations = None # delete any existing FeatureVariations varFeatureIndices = [] for index, feature in enumerate(table.FeatureList.FeatureRecord): if feature.FeatureTag == featureTag: varFeatureIndices.append(index) if not varFeatureIndices: varFeature = buildFeatureRecord(featureTag, []) table.FeatureList.FeatureRecord.append(varFeature) table.FeatureList.FeatureCount = len(table.FeatureList.FeatureRecord) sortFeatureList(table) varFeatureIndex = table.FeatureList.FeatureRecord.index(varFeature) for scriptRecord in table.ScriptList.ScriptRecord: if scriptRecord.Script.DefaultLangSys is None: raise VarLibError( "Feature variations require that the script " f"'{scriptRecord.ScriptTag}' defines a default language system." ) langSystems = [lsr.LangSys for lsr in scriptRecord.Script.LangSysRecord] for langSys in [scriptRecord.Script.DefaultLangSys] + langSystems: langSys.FeatureIndex.append(varFeatureIndex) langSys.FeatureCount = len(langSys.FeatureIndex) varFeatureIndices = [varFeatureIndex] axisIndices = { axis.axisTag: axisIndex for axisIndex, axis in enumerate(font["fvar"].axes) } featureVariationRecords = [] for conditionSet, lookupIndices in conditionalSubstitutions: conditionTable = [] for axisTag, (minValue, maxValue) in sorted(conditionSet.items()): if minValue > maxValue: raise VarLibValidationError( "A condition set has a minimum value above the maximum value." ) ct = buildConditionTable(axisIndices[axisTag], minValue, maxValue) conditionTable.append(ct) records = [] for varFeatureIndex in varFeatureIndices: existingLookupIndices = table.FeatureList.FeatureRecord[ varFeatureIndex ].Feature.LookupListIndex records.append( buildFeatureTableSubstitutionRecord( varFeatureIndex, lookupIndices + existingLookupIndices ) ) featureVariationRecords.append( buildFeatureVariationRecord(conditionTable, records) ) table.FeatureVariations = buildFeatureVariations(featureVariationRecords) def buildGSUB(): """Build a GSUB table from scratch.""" fontTable = newTable("GSUB") gsub = fontTable.table = ot.GSUB() gsub.Version = 0x00010001 # allow gsub.FeatureVariations gsub.ScriptList = ot.ScriptList() gsub.ScriptList.ScriptRecord = [] gsub.FeatureList = ot.FeatureList() gsub.FeatureList.FeatureRecord = [] gsub.LookupList = ot.LookupList() gsub.LookupList.Lookup = [] srec = ot.ScriptRecord() srec.ScriptTag = "DFLT" srec.Script = ot.Script() srec.Script.DefaultLangSys = None srec.Script.LangSysRecord = [] srec.Script.LangSysCount = 0 langrec = ot.LangSysRecord() langrec.LangSys = ot.LangSys() langrec.LangSys.ReqFeatureIndex = 0xFFFF langrec.LangSys.FeatureIndex = [] srec.Script.DefaultLangSys = langrec.LangSys gsub.ScriptList.ScriptRecord.append(srec) gsub.ScriptList.ScriptCount = 1 gsub.FeatureVariations = None return fontTable def makeSubstitutionsHashable(conditionalSubstitutions): """Turn all the substitution dictionaries in sorted tuples of tuples so they are hashable, to detect duplicates so we don't write out redundant data.""" allSubstitutions = set() condSubst = [] for conditionSet, substitutionMaps in conditionalSubstitutions: substitutions = [] for substitutionMap in substitutionMaps: subst = tuple(sorted(substitutionMap.items())) substitutions.append(subst) allSubstitutions.add(subst) condSubst.append((conditionSet, substitutions)) return condSubst, sorted(allSubstitutions) def buildSubstitutionLookups(gsub, allSubstitutions): """Build the lookups for the glyph substitutions, return a dict mapping the substitution to lookup indices.""" # Insert lookups at the beginning of the lookup vector # https://github.com/googlefonts/fontmake/issues/950 lookupMap = {} for i, substitutionMap in enumerate(allSubstitutions): lookupMap[substitutionMap] = i # Shift all lookup indices in gsub by len(allSubstitutions) shift = len(allSubstitutions) visitor = ShifterVisitor(shift) visitor.visit(gsub.FeatureList.FeatureRecord) visitor.visit(gsub.LookupList.Lookup) for i, subst in enumerate(allSubstitutions): substMap = dict(subst) lookup = buildLookup([buildSingleSubstSubtable(substMap)]) gsub.LookupList.Lookup.insert(i, lookup) assert gsub.LookupList.Lookup[lookupMap[subst]] is lookup gsub.LookupList.LookupCount = len(gsub.LookupList.Lookup) return lookupMap The provided code snippet includes necessary dependencies for implementing the `addFeatureVariations` function. Write a Python function `def addFeatureVariations(font, conditionalSubstitutions, featureTag="rvrn")` to solve the following problem: Add conditional substitutions to a Variable Font. The `conditionalSubstitutions` argument is a list of (Region, Substitutions) tuples. A Region is a list of Boxes. A Box is a dict mapping axisTags to (minValue, maxValue) tuples. Irrelevant axes may be omitted and they are interpretted as extending to end of axis in each direction. A Box represents an orthogonal 'rectangular' subset of an N-dimensional design space. A Region represents a more complex subset of an N-dimensional design space, ie. the union of all the Boxes in the Region. For efficiency, Boxes within a Region should ideally not overlap, but functionality is not compromised if they do. The minimum and maximum values are expressed in normalized coordinates. A Substitution is a dict mapping source glyph names to substitute glyph names. Example: # >>> f = TTFont(srcPath) # >>> condSubst = [ # ... # A list of (Region, Substitution) tuples. # ... ([{"wdth": (0.5, 1.0)}], {"cent": "cent.rvrn"}), # ... ([{"wght": (0.5, 1.0)}], {"dollar": "dollar.rvrn"}), # ... ] # >>> addFeatureVariations(f, condSubst) # >>> f.save(dstPath) Here is the function: def addFeatureVariations(font, conditionalSubstitutions, featureTag="rvrn"): """Add conditional substitutions to a Variable Font. The `conditionalSubstitutions` argument is a list of (Region, Substitutions) tuples. A Region is a list of Boxes. A Box is a dict mapping axisTags to (minValue, maxValue) tuples. Irrelevant axes may be omitted and they are interpretted as extending to end of axis in each direction. A Box represents an orthogonal 'rectangular' subset of an N-dimensional design space. A Region represents a more complex subset of an N-dimensional design space, ie. the union of all the Boxes in the Region. For efficiency, Boxes within a Region should ideally not overlap, but functionality is not compromised if they do. The minimum and maximum values are expressed in normalized coordinates. A Substitution is a dict mapping source glyph names to substitute glyph names. Example: # >>> f = TTFont(srcPath) # >>> condSubst = [ # ... # A list of (Region, Substitution) tuples. # ... ([{"wdth": (0.5, 1.0)}], {"cent": "cent.rvrn"}), # ... ([{"wght": (0.5, 1.0)}], {"dollar": "dollar.rvrn"}), # ... ] # >>> addFeatureVariations(f, condSubst) # >>> f.save(dstPath) """ _checkSubstitutionGlyphsExist( glyphNames=set(font.getGlyphOrder()), substitutions=conditionalSubstitutions, ) substitutions = overlayFeatureVariations(conditionalSubstitutions) # turn substitution dicts into tuples of tuples, so they are hashable conditionalSubstitutions, allSubstitutions = makeSubstitutionsHashable( substitutions ) if "GSUB" not in font: font["GSUB"] = buildGSUB() # setup lookups lookupMap = buildSubstitutionLookups(font["GSUB"].table, allSubstitutions) # addFeatureVariationsRaw takes a list of # ( {condition}, [ lookup indices ] ) # so rearrange our lookups to match conditionsAndLookups = [] for conditionSet, substitutions in conditionalSubstitutions: conditionsAndLookups.append( (conditionSet, [lookupMap[s] for s in substitutions]) ) addFeatureVariationsRaw(font, font["GSUB"].table, conditionsAndLookups, featureTag)
Add conditional substitutions to a Variable Font. The `conditionalSubstitutions` argument is a list of (Region, Substitutions) tuples. A Region is a list of Boxes. A Box is a dict mapping axisTags to (minValue, maxValue) tuples. Irrelevant axes may be omitted and they are interpretted as extending to end of axis in each direction. A Box represents an orthogonal 'rectangular' subset of an N-dimensional design space. A Region represents a more complex subset of an N-dimensional design space, ie. the union of all the Boxes in the Region. For efficiency, Boxes within a Region should ideally not overlap, but functionality is not compromised if they do. The minimum and maximum values are expressed in normalized coordinates. A Substitution is a dict mapping source glyph names to substitute glyph names. Example: # >>> f = TTFont(srcPath) # >>> condSubst = [ # ... # A list of (Region, Substitution) tuples. # ... ([{"wdth": (0.5, 1.0)}], {"cent": "cent.rvrn"}), # ... ([{"wght": (0.5, 1.0)}], {"dollar": "dollar.rvrn"}), # ... ] # >>> addFeatureVariations(f, condSubst) # >>> f.save(dstPath)
175,292
from typing import ( Sequence, Tuple, Union, ) from numbers import Integral, Real _PointSegment = Sequence[_Point] _DeltaSegment = Sequence[_Delta] _DeltaOrNoneSegment = Sequence[_DeltaOrNone] _Endpoints = Sequence[Integral] def iup_contour_optimize( deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0.0 ) -> _DeltaOrNoneSegment: """For contour with coordinates `coords`, optimize a set of delta values `deltas` within error `tolerance`. Returns delta vector that has most number of None items instead of the input delta. """ n = len(deltas) # Get the easy cases out of the way: # If all are within tolerance distance of 0, encode nothing: if all(abs(complex(*p)) <= tolerance for p in deltas): return [None] * n # If there's exactly one point, return it: if n == 1: return deltas # If all deltas are exactly the same, return just one (the first one): d0 = deltas[0] if all(d0 == d for d in deltas): return [d0] + [None] * (n - 1) # Else, solve the general problem using Dynamic Programming. forced = _iup_contour_bound_forced_set(deltas, coords, tolerance) # The _iup_contour_optimize_dp() routine returns the optimal encoding # solution given the constraint that the last point is always encoded. # To remove this constraint, we use two different methods, depending on # whether forced set is non-empty or not: # Debugging: Make the next if always take the second branch and observe # if the font size changes (reduced); that would mean the forced-set # has members it should not have. if forced: # Forced set is non-empty: rotate the contour start point # such that the last point in the list is a forced point. k = (n - 1) - max(forced) assert k >= 0 deltas = _rot_list(deltas, k) coords = _rot_list(coords, k) forced = _rot_set(forced, k, n) # Debugging: Pass a set() instead of forced variable to the next call # to exercise forced-set computation for under-counting. chain, costs = _iup_contour_optimize_dp(deltas, coords, forced, tolerance) # Assemble solution. solution = set() i = n - 1 while i is not None: solution.add(i) i = chain[i] solution.remove(-1) # if not forced <= solution: # print("coord", coords) # print("deltas", deltas) # print("len", len(deltas)) assert forced <= solution, (forced, solution) deltas = [deltas[i] if i in solution else None for i in range(n)] deltas = _rot_list(deltas, -k) else: # Repeat the contour an extra time, solve the new case, then look for solutions of the # circular n-length problem in the solution for new linear case. I cannot prove that # this always produces the optimal solution... chain, costs = _iup_contour_optimize_dp( deltas + deltas, coords + coords, forced, tolerance, n ) best_sol, best_cost = None, n + 1 for start in range(n - 1, len(costs) - 1): # Assemble solution. solution = set() i = start while i > start - n: solution.add(i % n) i = chain[i] if i == start - n: cost = costs[start] - costs[start - n] if cost <= best_cost: best_sol, best_cost = solution, cost # if not forced <= best_sol: # print("coord", coords) # print("deltas", deltas) # print("len", len(deltas)) assert forced <= best_sol, (forced, best_sol) deltas = [deltas[i] if i in best_sol else None for i in range(n)] return deltas class Real(Complex, SupportsFloat): def __float__(self) -> float: ... def __trunc__(self) -> int: ... if sys.version_info >= (3, 0): def __floor__(self) -> int: ... def __ceil__(self) -> int: ... def __round__(self, ndigits: None = ...) -> int: ... def __round__(self, ndigits: int) -> Any: ... def __divmod__(self, other: Any) -> Any: ... def __rdivmod__(self, other: Any) -> Any: ... def __floordiv__(self, other: Any) -> int: ... def __rfloordiv__(self, other: Any) -> int: ... def __mod__(self, other: Any) -> Any: ... def __rmod__(self, other: Any) -> Any: ... def __lt__(self, other: Any) -> bool: ... def __le__(self, other: Any) -> bool: ... def __complex__(self) -> complex: ... def real(self) -> Any: ... def imag(self) -> Any: ... def conjugate(self) -> Any: ... The provided code snippet includes necessary dependencies for implementing the `iup_delta_optimize` function. Write a Python function `def iup_delta_optimize( deltas: _DeltaSegment, coords: _PointSegment, ends: _Endpoints, tolerance: Real = 0.0, ) -> _DeltaOrNoneSegment` to solve the following problem: For the outline given in `coords`, with contour endpoints given in sorted increasing order in `ends`, optimize a set of delta values `deltas` within error `tolerance`. Returns delta vector that has most number of None items instead of the input delta. Here is the function: def iup_delta_optimize( deltas: _DeltaSegment, coords: _PointSegment, ends: _Endpoints, tolerance: Real = 0.0, ) -> _DeltaOrNoneSegment: """For the outline given in `coords`, with contour endpoints given in sorted increasing order in `ends`, optimize a set of delta values `deltas` within error `tolerance`. Returns delta vector that has most number of None items instead of the input delta. """ assert sorted(ends) == ends and len(coords) == (ends[-1] + 1 if ends else 0) + 4 n = len(coords) ends = ends + [n - 4, n - 3, n - 2, n - 1] out = [] start = 0 for end in ends: contour = iup_contour_optimize( deltas[start : end + 1], coords[start : end + 1], tolerance ) assert len(contour) == end - start + 1 out.extend(contour) start = end + 1 return out
For the outline given in `coords`, with contour endpoints given in sorted increasing order in `ends`, optimize a set of delta values `deltas` within error `tolerance`. Returns delta vector that has most number of None items instead of the input delta.
175,293
from contextlib import contextmanager from copy import deepcopy from enum import IntEnum import re def getVariationNameIDs(varfont): used = [] if "fvar" in varfont: fvar = varfont["fvar"] for axis in fvar.axes: used.append(axis.axisNameID) for instance in fvar.instances: used.append(instance.subfamilyNameID) if instance.postscriptNameID != 0xFFFF: used.append(instance.postscriptNameID) if "STAT" in varfont: stat = varfont["STAT"].table for axis in stat.DesignAxisRecord.Axis if stat.DesignAxisRecord else (): used.append(axis.AxisNameID) for value in stat.AxisValueArray.AxisValue if stat.AxisValueArray else (): used.append(value.ValueNameID) elidedFallbackNameID = getattr(stat, "ElidedFallbackNameID", None) if elidedFallbackNameID is not None: used.append(elidedFallbackNameID) # nameIDs <= 255 are reserved by OT spec so we don't touch them return {nameID for nameID in used if nameID > 255} def pruningUnusedNames(varfont): from . import log origNameIDs = getVariationNameIDs(varfont) yield log.info("Pruning name table") exclude = origNameIDs - getVariationNameIDs(varfont) varfont["name"].names[:] = [ record for record in varfont["name"].names if record.nameID not in exclude ] if "ltag" in varfont: # Drop the whole 'ltag' table if all the language-dependent Unicode name # records that reference it have been dropped. # TODO: Only prune unused ltag tags, renumerating langIDs accordingly. # Note ltag can also be used by feat or morx tables, so check those too. if not any( record for record in varfont["name"].names if record.platformID == 0 and record.langID != 0xFFFF ): del varfont["ltag"]
null
175,294
from contextlib import contextmanager from copy import deepcopy from enum import IntEnum import re ELIDABLE_AXIS_VALUE_NAME = 2 def checkAxisValuesExist(stat, axisValues, axisCoords): seen = set() designAxes = stat.DesignAxisRecord.Axis for axisValueTable in axisValues: axisValueFormat = axisValueTable.Format if axisValueTable.Format in (1, 2, 3): axisTag = designAxes[axisValueTable.AxisIndex].AxisTag if axisValueFormat == 2: axisValue = axisValueTable.NominalValue else: axisValue = axisValueTable.Value if axisTag in axisCoords and axisValue == axisCoords[axisTag]: seen.add(axisTag) elif axisValueTable.Format == 4: for rec in axisValueTable.AxisValueRecord: axisTag = designAxes[rec.AxisIndex].AxisTag if axisTag in axisCoords and rec.Value == axisCoords[axisTag]: seen.add(axisTag) missingAxes = set(axisCoords) - seen if missingAxes: missing = ", ".join(f"'{i}': {axisCoords[i]}" for i in missingAxes) raise ValueError(f"Cannot find Axis Values {{{missing}}}") def _sortAxisValues(axisValues): # Sort by axis index, remove duplicates and ensure that format 4 AxisValues # are dominant. # The MS Spec states: "if a format 1, format 2 or format 3 table has a # (nominal) value used in a format 4 table that also has values for # other axes, the format 4 table, being the more specific match, is used", # https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-value-table-format-4 results = [] seenAxes = set() # Sort format 4 axes so the tables with the most AxisValueRecords are first format4 = sorted( [v for v in axisValues if v.Format == 4], key=lambda v: len(v.AxisValueRecord), reverse=True, ) for val in format4: axisIndexes = set(r.AxisIndex for r in val.AxisValueRecord) minIndex = min(axisIndexes) if not seenAxes & axisIndexes: seenAxes |= axisIndexes results.append((minIndex, val)) for val in axisValues: if val in format4: continue axisIndex = val.AxisIndex if axisIndex not in seenAxes: seenAxes.add(axisIndex) results.append((axisIndex, val)) return [axisValue for _, axisValue in sorted(results)] def _updateNameRecords(varfont, axisValues): # Update nametable based on the axisValues using the R/I/B/BI model. nametable = varfont["name"] stat = varfont["STAT"].table axisValueNameIDs = [a.ValueNameID for a in axisValues] ribbiNameIDs = [n for n in axisValueNameIDs if _isRibbi(nametable, n)] nonRibbiNameIDs = [n for n in axisValueNameIDs if n not in ribbiNameIDs] elidedNameID = stat.ElidedFallbackNameID elidedNameIsRibbi = _isRibbi(nametable, elidedNameID) getName = nametable.getName platforms = set((r.platformID, r.platEncID, r.langID) for r in nametable.names) for platform in platforms: if not all(getName(i, *platform) for i in (1, 2, elidedNameID)): # Since no family name and subfamily name records were found, # we cannot update this set of name Records. continue subFamilyName = " ".join( getName(n, *platform).toUnicode() for n in ribbiNameIDs ) if nonRibbiNameIDs: typoSubFamilyName = " ".join( getName(n, *platform).toUnicode() for n in axisValueNameIDs ) else: typoSubFamilyName = None # If neither subFamilyName and typographic SubFamilyName exist, # we will use the STAT's elidedFallbackName if not typoSubFamilyName and not subFamilyName: if elidedNameIsRibbi: subFamilyName = getName(elidedNameID, *platform).toUnicode() else: typoSubFamilyName = getName(elidedNameID, *platform).toUnicode() familyNameSuffix = " ".join( getName(n, *platform).toUnicode() for n in nonRibbiNameIDs ) _updateNameTableStyleRecords( varfont, familyNameSuffix, subFamilyName, typoSubFamilyName, *platform, ) The provided code snippet includes necessary dependencies for implementing the `updateNameTable` function. Write a Python function `def updateNameTable(varfont, axisLimits)` to solve the following problem: Update instatiated variable font's name table using STAT AxisValues. Raises ValueError if the STAT table is missing or an Axis Value table is missing for requested axis locations. First, collect all STAT AxisValues that match the new default axis locations (excluding "elided" ones); concatenate the strings in design axis order, while giving priority to "synthetic" values (Format 4), to form the typographic subfamily name associated with the new default instance. Finally, update all related records in the name table, making sure that legacy family/sub-family names conform to the the R/I/B/BI (Regular, Italic, Bold, Bold Italic) naming model. Example: Updating a partial variable font: | >>> ttFont = TTFont("OpenSans[wdth,wght].ttf") | >>> updateNameTable(ttFont, {"wght": (400, 900), "wdth": 75}) The name table records will be updated in the following manner: NameID 1 familyName: "Open Sans" --> "Open Sans Condensed" NameID 2 subFamilyName: "Regular" --> "Regular" NameID 3 Unique font identifier: "3.000;GOOG;OpenSans-Regular" --> \ "3.000;GOOG;OpenSans-Condensed" NameID 4 Full font name: "Open Sans Regular" --> "Open Sans Condensed" NameID 6 PostScript name: "OpenSans-Regular" --> "OpenSans-Condensed" NameID 16 Typographic Family name: None --> "Open Sans" NameID 17 Typographic Subfamily name: None --> "Condensed" References: https://docs.microsoft.com/en-us/typography/opentype/spec/stat https://docs.microsoft.com/en-us/typography/opentype/spec/name#name-ids Here is the function: def updateNameTable(varfont, axisLimits): """Update instatiated variable font's name table using STAT AxisValues. Raises ValueError if the STAT table is missing or an Axis Value table is missing for requested axis locations. First, collect all STAT AxisValues that match the new default axis locations (excluding "elided" ones); concatenate the strings in design axis order, while giving priority to "synthetic" values (Format 4), to form the typographic subfamily name associated with the new default instance. Finally, update all related records in the name table, making sure that legacy family/sub-family names conform to the the R/I/B/BI (Regular, Italic, Bold, Bold Italic) naming model. Example: Updating a partial variable font: | >>> ttFont = TTFont("OpenSans[wdth,wght].ttf") | >>> updateNameTable(ttFont, {"wght": (400, 900), "wdth": 75}) The name table records will be updated in the following manner: NameID 1 familyName: "Open Sans" --> "Open Sans Condensed" NameID 2 subFamilyName: "Regular" --> "Regular" NameID 3 Unique font identifier: "3.000;GOOG;OpenSans-Regular" --> \ "3.000;GOOG;OpenSans-Condensed" NameID 4 Full font name: "Open Sans Regular" --> "Open Sans Condensed" NameID 6 PostScript name: "OpenSans-Regular" --> "OpenSans-Condensed" NameID 16 Typographic Family name: None --> "Open Sans" NameID 17 Typographic Subfamily name: None --> "Condensed" References: https://docs.microsoft.com/en-us/typography/opentype/spec/stat https://docs.microsoft.com/en-us/typography/opentype/spec/name#name-ids """ from . import AxisLimits, axisValuesFromAxisLimits if "STAT" not in varfont: raise ValueError("Cannot update name table since there is no STAT table.") stat = varfont["STAT"].table if not stat.AxisValueArray: raise ValueError("Cannot update name table since there are no STAT Axis Values") fvar = varfont["fvar"] # The updated name table will reflect the new 'zero origin' of the font. # If we're instantiating a partial font, we will populate the unpinned # axes with their default axis values from fvar. axisLimits = AxisLimits(axisLimits).limitAxesAndPopulateDefaults(varfont) partialDefaults = axisLimits.defaultLocation() fvarDefaults = {a.axisTag: a.defaultValue for a in fvar.axes} defaultAxisCoords = AxisLimits({**fvarDefaults, **partialDefaults}) assert all(v.minimum == v.maximum for v in defaultAxisCoords.values()) axisValueTables = axisValuesFromAxisLimits(stat, defaultAxisCoords) checkAxisValuesExist(stat, axisValueTables, defaultAxisCoords.pinnedLocation()) # ignore "elidable" axis values, should be omitted in application font menus. axisValueTables = [ v for v in axisValueTables if not v.Flags & ELIDABLE_AXIS_VALUE_NAME ] axisValueTables = _sortAxisValues(axisValueTables) _updateNameRecords(varfont, axisValueTables)
Update instatiated variable font's name table using STAT AxisValues. Raises ValueError if the STAT table is missing or an Axis Value table is missing for requested axis locations. First, collect all STAT AxisValues that match the new default axis locations (excluding "elided" ones); concatenate the strings in design axis order, while giving priority to "synthetic" values (Format 4), to form the typographic subfamily name associated with the new default instance. Finally, update all related records in the name table, making sure that legacy family/sub-family names conform to the the R/I/B/BI (Regular, Italic, Bold, Bold Italic) naming model. Example: Updating a partial variable font: | >>> ttFont = TTFont("OpenSans[wdth,wght].ttf") | >>> updateNameTable(ttFont, {"wght": (400, 900), "wdth": 75}) The name table records will be updated in the following manner: NameID 1 familyName: "Open Sans" --> "Open Sans Condensed" NameID 2 subFamilyName: "Regular" --> "Regular" NameID 3 Unique font identifier: "3.000;GOOG;OpenSans-Regular" --> \ "3.000;GOOG;OpenSans-Condensed" NameID 4 Full font name: "Open Sans Regular" --> "Open Sans Condensed" NameID 6 PostScript name: "OpenSans-Regular" --> "OpenSans-Condensed" NameID 16 Typographic Family name: None --> "Open Sans" NameID 17 Typographic Subfamily name: None --> "Condensed" References: https://docs.microsoft.com/en-us/typography/opentype/spec/stat https://docs.microsoft.com/en-us/typography/opentype/spec/name#name-ids
175,295
from fontTools.varLib.models import supportScalar, normalizeValue from fontTools.misc.fixedTools import MAX_F2DOT14 from functools import lru_cache def _solve(tent, axisLimit, negative=False): axisMin, axisDef, axisMax = axisLimit lower, peak, upper = tent # Mirror the problem such that axisDef <= peak if axisDef > peak: return [ (scalar, _reverse_negate(t) if t is not None else None) for scalar, t in _solve( _reverse_negate(tent), _reverse_negate(axisLimit), not negative ) ] # axisDef <= peak # case 1: The whole deltaset falls outside the new limit; we can drop it # # peak # 1.........................................o.......... # / \ # / \ # / \ # / \ # 0---|-----------|----------|-------- o o----1 # axisMin axisDef axisMax lower upper # if axisMax <= lower and axisMax < peak: return [] # No overlap # case 2: Only the peak and outermost bound fall outside the new limit; # we keep the deltaset, update peak and outermost bound and and scale deltas # by the scalar value for the restricted axis at the new limit, and solve # recursively. # # |peak # 1...............................|.o.......... # |/ \ # / \ # /| \ # / | \ # 0--------------------------- o | o----1 # lower | upper # | # axisMax # # Convert to: # # 1............................................ # | # o peak # /| # /x| # 0--------------------------- o o upper ----1 # lower | # | # axisMax if axisMax < peak: mult = supportScalar({"tag": axisMax}, {"tag": tent}) tent = (lower, axisMax, axisMax) return [(scalar * mult, t) for scalar, t in _solve(tent, axisLimit)] # lower <= axisDef <= peak <= axisMax gain = supportScalar({"tag": axisDef}, {"tag": tent}) out = [(gain, None)] # First, the positive side # outGain is the scalar of axisMax at the tent. outGain = supportScalar({"tag": axisMax}, {"tag": tent}) # Case 3a: Gain is more than outGain. The tent down-slope crosses # the axis into negative. We have to split it into multiples. # # | peak | # 1...................|.o.....|.............. # |/x\_ | # gain................+....+_.|.............. # /| |y\| # ................../.|....|..+_......outGain # / | | | \ # 0---|-----------o | | | o----------1 # axisMin lower | | | upper # | | | # axisDef | axisMax # | # crossing if gain > outGain: # Crossing point on the axis. crossing = peak + ((1 - gain) * (upper - peak) / (1 - outGain)) loc = (peak, peak, crossing) scalar = 1 # The part before the crossing point. out.append((scalar - gain, loc)) # The part after the crossing point may use one or two tents, # depending on whether upper is before axisMax or not, in one # case we need to keep it down to eternity. # Case 3a1, similar to case 1neg; just one tent needed, as in # the drawing above. if upper >= axisMax: loc = (crossing, axisMax, axisMax) scalar = supportScalar({"tag": axisMax}, {"tag": tent}) out.append((scalar - gain, loc)) # Case 3a2: Similar to case 2neg; two tents needed, to keep # down to eternity. # # | peak | # 1...................|.o................|... # |/ \_ | # gain................+....+_............|... # /| | \xxxxxxxxxxy| # / | | \_xxxxxyyyy| # / | | \xxyyyyyy| # 0---|-----------o | | o-------|--1 # axisMin lower | | upper | # | | | # axisDef | axisMax # | # crossing else: # A tent's peak cannot fall on axis default. Nudge it. if upper == axisDef: upper += EPSILON # Downslope. loc1 = (crossing, upper, axisMax) scalar1 = 0 # Eternity justify. loc2 = (upper, axisMax, axisMax) scalar2 = supportScalar({"tag": axisMax}, {"tag": tent}) out.append((scalar1 - gain, loc1)) out.append((scalar2 - gain, loc2)) # Case 3: Outermost limit still fits within F2Dot14 bounds; # we keep deltas as is and only scale the axes bounds. Deltas beyond -1.0 # or +1.0 will never be applied as implementations must clamp to that range. # # A second tent is needed for cases when gain is positive, though we add it # unconditionally and it will be dropped because scalar ends up 0. # # TODO: See if we can just move upper closer to adjust the slope, instead of # second tent. # # | peak | # 1.........|............o...|.................. # | /x\ | # | /xxx\ | # | /xxxxx\| # | /xxxxxxx+ # | /xxxxxxxx|\ # 0---|-----|------oxxxxxxxxx|xo---------------1 # axisMin | lower | upper # | | # axisDef axisMax # elif axisDef + (axisMax - axisDef) * 2 >= upper: if not negative and axisDef + (axisMax - axisDef) * MAX_F2DOT14 < upper: # we clamp +2.0 to the max F2Dot14 (~1.99994) for convenience upper = axisDef + (axisMax - axisDef) * MAX_F2DOT14 assert peak < upper # Special-case if peak is at axisMax. if axisMax == peak: upper = peak loc1 = (max(axisDef, lower), peak, upper) scalar1 = 1 loc2 = (peak, upper, upper) scalar2 = 0 # Don't add a dirac delta! if axisDef < upper: out.append((scalar1 - gain, loc1)) if peak < upper: out.append((scalar2 - gain, loc2)) # Case 4: New limit doesn't fit; we need to chop into two tents, # because the shape of a triangle with part of one side cut off # cannot be represented as a triangle itself. # # | peak | # 1.........|......o.|................... # | /x\| # | |xxy|\_ # | /xxxy| \_ # | |xxxxy| \_ # | /xxxxy| \_ # 0---|-----|-oxxxxxx| o----------1 # axisMin | lower | upper # | | # axisDef axisMax # else: loc1 = (max(axisDef, lower), peak, axisMax) scalar1 = 1 loc2 = (peak, axisMax, axisMax) scalar2 = supportScalar({"tag": axisMax}, {"tag": tent}) out.append((scalar1 - gain, loc1)) # Don't add a dirac delta! if peak < axisMax: out.append((scalar2 - gain, loc2)) # Now, the negative side # Case 1neg: Lower extends beyond axisMin: we chop. Simple. # # | |peak # 1..................|...|.o................. # | |/ \ # gain...............|...+...\............... # |x_/| \ # |/ | \ # _/| | \ # 0---------------o | | o----------1 # lower | | upper # | | # axisMin axisDef # if lower <= axisMin: loc = (axisMin, axisMin, axisDef) scalar = supportScalar({"tag": axisMin}, {"tag": tent}) out.append((scalar - gain, loc)) # Case 2neg: Lower is betwen axisMin and axisDef: we add two # tents to keep it down all the way to eternity. # # | |peak # 1...|...............|.o................. # | |/ \ # gain|...............+...\............... # |yxxxxxxxxxxxxx/| \ # |yyyyyyxxxxxxx/ | \ # |yyyyyyyyyyyx/ | \ # 0---|-----------o | o----------1 # axisMin lower | upper # | # axisDef # else: # A tent's peak cannot fall on axis default. Nudge it. if lower == axisDef: lower -= EPSILON # Downslope. loc1 = (axisMin, lower, axisDef) scalar1 = 0 # Eternity justify. loc2 = (axisMin, axisMin, lower) scalar2 = 0 out.append((scalar1 - gain, loc1)) out.append((scalar2 - gain, loc2)) return out def normalizeValue(v, triple, extrapolate=False): """Normalizes value based on a min/default/max triple. >>> normalizeValue(400, (100, 400, 900)) 0.0 >>> normalizeValue(100, (100, 400, 900)) -1.0 >>> normalizeValue(650, (100, 400, 900)) 0.5 """ lower, default, upper = triple if not (lower <= default <= upper): raise ValueError( f"Invalid axis values, must be minimum, default, maximum: " f"{lower:3.3f}, {default:3.3f}, {upper:3.3f}" ) if not extrapolate: v = max(min(v, upper), lower) if v == default or lower == upper: return 0.0 if (v < default and lower != default) or (v > default and upper == default): return (v - default) / (default - lower) else: assert (v > default and upper != default) or ( v < default and lower == default ), f"Ooops... v={v}, triple=({lower}, {default}, {upper})" return (v - default) / (upper - default) The provided code snippet includes necessary dependencies for implementing the `rebaseTent` function. Write a Python function `def rebaseTent(tent, axisLimit)` to solve the following problem: Given a tuple (lower,peak,upper) "tent" and new axis limits (axisMin,axisDefault,axisMax), solves how to represent the tent under the new axis configuration. All values are in normalized -1,0,+1 coordinate system. Tent values can be outside this range. Return value is a list of tuples. Each tuple is of the form (scalar,tent), where scalar is a multipler to multiply any delta-sets by, and tent is a new tent for that output delta-set. If tent value is None, that is a special deltaset that should be always-enabled (called "gain"). Here is the function: def rebaseTent(tent, axisLimit): """Given a tuple (lower,peak,upper) "tent" and new axis limits (axisMin,axisDefault,axisMax), solves how to represent the tent under the new axis configuration. All values are in normalized -1,0,+1 coordinate system. Tent values can be outside this range. Return value is a list of tuples. Each tuple is of the form (scalar,tent), where scalar is a multipler to multiply any delta-sets by, and tent is a new tent for that output delta-set. If tent value is None, that is a special deltaset that should be always-enabled (called "gain").""" axisMin, axisDef, axisMax = axisLimit assert -1 <= axisMin <= axisDef <= axisMax <= +1 lower, peak, upper = tent assert -2 <= lower <= peak <= upper <= +2 assert peak != 0 sols = _solve(tent, axisLimit) n = lambda v: normalizeValue(v, axisLimit, extrapolate=True) sols = [ (scalar, (n(v[0]), n(v[1]), n(v[2])) if v is not None else None) for scalar, v in sols if scalar ] return sols
Given a tuple (lower,peak,upper) "tent" and new axis limits (axisMin,axisDefault,axisMax), solves how to represent the tent under the new axis configuration. All values are in normalized -1,0,+1 coordinate system. Tent values can be outside this range. Return value is a list of tuples. Each tuple is of the form (scalar,tent), where scalar is a multipler to multiply any delta-sets by, and tent is a new tent for that output delta-set. If tent value is None, that is a special deltaset that should be always-enabled (called "gain").
175,296
from fontTools.ttLib.tables import otTables as ot from fontTools.varLib.models import normalizeValue from copy import deepcopy import logging log = logging.getLogger("fontTools.varLib.instancer") def _instantiateFeatureVariations(table, fvarAxes, axisLimits): pinnedAxes = set(axisLimits.pinnedLocation()) axisOrder = [axis.axisTag for axis in fvarAxes if axis.axisTag not in pinnedAxes] axisIndexMap = {axisTag: axisOrder.index(axisTag) for axisTag in axisOrder} featureVariationApplied = False uniqueRecords = set() newRecords = [] defaultsSubsts = None for i, record in enumerate(table.FeatureVariations.FeatureVariationRecord): applies, shouldKeep, universal = _instantiateFeatureVariationRecord( record, i, axisLimits, fvarAxes, axisIndexMap ) if shouldKeep and _featureVariationRecordIsUnique(record, uniqueRecords): newRecords.append(record) if applies and not featureVariationApplied: assert record.FeatureTableSubstitution.Version == 0x00010000 defaultsSubsts = deepcopy(record.FeatureTableSubstitution) for default, rec in zip( defaultsSubsts.SubstitutionRecord, record.FeatureTableSubstitution.SubstitutionRecord, ): default.Feature = deepcopy( table.FeatureList.FeatureRecord[rec.FeatureIndex].Feature ) table.FeatureList.FeatureRecord[rec.FeatureIndex].Feature = deepcopy( rec.Feature ) # Set variations only once featureVariationApplied = True # Further records don't have a chance to apply after a universal record if universal: break # Insert a catch-all record to reinstate the old features if necessary if featureVariationApplied and newRecords and not universal: defaultRecord = ot.FeatureVariationRecord() defaultRecord.ConditionSet = ot.ConditionSet() defaultRecord.ConditionSet.ConditionTable = [] defaultRecord.ConditionSet.ConditionCount = 0 defaultRecord.FeatureTableSubstitution = defaultsSubsts newRecords.append(defaultRecord) if newRecords: table.FeatureVariations.FeatureVariationRecord = newRecords table.FeatureVariations.FeatureVariationCount = len(newRecords) else: del table.FeatureVariations # downgrade table version if there are no FeatureVariations left table.Version = 0x00010000 def instantiateFeatureVariations(varfont, axisLimits): for tableTag in ("GPOS", "GSUB"): if tableTag not in varfont or not getattr( varfont[tableTag].table, "FeatureVariations", None ): continue log.info("Instantiating FeatureVariations of %s table", tableTag) _instantiateFeatureVariations( varfont[tableTag].table, varfont["fvar"].axes, axisLimits ) # remove unreferenced lookups varfont[tableTag].prune_lookups()
null
175,297
from fontTools.ttLib import TTFont from fontTools.varLib import models, VarLibError, load_designspace, load_masters from fontTools.varLib.merger import InstancerMerger import os.path import logging from copy import deepcopy from pprint import pformat log = logging.getLogger("fontTools.varLib.interpolate_layout") def load_designspace(designspace): # TODO: remove this and always assume 'designspace' is a DesignSpaceDocument, # never a file path, as that's already handled by caller if hasattr(designspace, "sources"): # Assume a DesignspaceDocument ds = designspace else: # Assume a file path ds = DesignSpaceDocument.fromfile(designspace) masters = ds.sources if not masters: raise VarLibValidationError("Designspace must have at least one source.") instances = ds.instances # TODO: Use fontTools.designspaceLib.tagForAxisName instead. standard_axis_map = OrderedDict( [ ("weight", ("wght", {"en": "Weight"})), ("width", ("wdth", {"en": "Width"})), ("slant", ("slnt", {"en": "Slant"})), ("optical", ("opsz", {"en": "Optical Size"})), ("italic", ("ital", {"en": "Italic"})), ] ) # Setup axes if not ds.axes: raise VarLibValidationError(f"Designspace must have at least one axis.") axes = OrderedDict() for axis_index, axis in enumerate(ds.axes): axis_name = axis.name if not axis_name: if not axis.tag: raise VarLibValidationError(f"Axis at index {axis_index} needs a tag.") axis_name = axis.name = axis.tag if axis_name in standard_axis_map: if axis.tag is None: axis.tag = standard_axis_map[axis_name][0] if not axis.labelNames: axis.labelNames.update(standard_axis_map[axis_name][1]) else: if not axis.tag: raise VarLibValidationError(f"Axis at index {axis_index} needs a tag.") if not axis.labelNames: axis.labelNames["en"] = tostr(axis_name) axes[axis_name] = axis log.info("Axes:\n%s", pformat([axis.asdict() for axis in axes.values()])) # Check all master and instance locations are valid and fill in defaults for obj in masters + instances: obj_name = obj.name or obj.styleName or "" loc = obj.getFullDesignLocation(ds) obj.designLocation = loc if loc is None: raise VarLibValidationError( f"Source or instance '{obj_name}' has no location." ) for axis_name in loc.keys(): if axis_name not in axes: raise VarLibValidationError( f"Location axis '{axis_name}' unknown for '{obj_name}'." ) for axis_name, axis in axes.items(): v = axis.map_backward(loc[axis_name]) if not (axis.minimum <= v <= axis.maximum): raise VarLibValidationError( f"Source or instance '{obj_name}' has out-of-range location " f"for axis '{axis_name}': is mapped to {v} but must be in " f"mapped range [{axis.minimum}..{axis.maximum}] (NOTE: all " "values are in user-space)." ) # Normalize master locations internal_master_locs = [o.getFullDesignLocation(ds) for o in masters] log.info("Internal master locations:\n%s", pformat(internal_master_locs)) # TODO This mapping should ideally be moved closer to logic in _add_fvar/avar internal_axis_supports = {} for axis in axes.values(): triple = (axis.minimum, axis.default, axis.maximum) internal_axis_supports[axis.name] = [axis.map_forward(v) for v in triple] log.info("Internal axis supports:\n%s", pformat(internal_axis_supports)) normalized_master_locs = [ models.normalizeLocation(m, internal_axis_supports) for m in internal_master_locs ] log.info("Normalized master locations:\n%s", pformat(normalized_master_locs)) # Find base master base_idx = None for i, m in enumerate(normalized_master_locs): if all(v == 0 for v in m.values()): if base_idx is not None: raise VarLibValidationError( "More than one base master found in Designspace." ) base_idx = i if base_idx is None: raise VarLibValidationError( "Base master not found; no master at default location?" ) log.info("Index of base master: %s", base_idx) return _DesignSpaceData( axes, internal_axis_supports, base_idx, normalized_master_locs, masters, instances, ds.rules, ds.rulesProcessingLast, ds.lib, ) def load_masters(designspace, master_finder=lambda s: s): """Ensure that all SourceDescriptor.font attributes have an appropriate TTFont object loaded, or else open TTFont objects from the SourceDescriptor.path attributes. The paths can point to either an OpenType font, a TTX file, or a UFO. In the latter case, use the provided master_finder callable to map from UFO paths to the respective master font binaries (e.g. .ttf, .otf or .ttx). Return list of master TTFont objects in the same order they are listed in the DesignSpaceDocument. """ for master in designspace.sources: # If a SourceDescriptor has a layer name, demand that the compiled TTFont # be supplied by the caller. This spares us from modifying MasterFinder. if master.layerName and master.font is None: raise VarLibValidationError( f"Designspace source '{master.name or '<Unknown>'}' specified a " "layer name but lacks the required TTFont object in the 'font' " "attribute." ) return designspace.loadSourceFonts(_open_font, master_finder=master_finder) class InstancerMerger(AligningMerger): """A merger that takes multiple master fonts, and instantiates an instance.""" def __init__(self, font, model, location): Merger.__init__(self, font) self.model = model self.location = location self.scalars = model.getScalars(location) def deepcopy(x: _T, memo: Optional[Dict[int, Any]] = ..., _nil: Any = ...) -> _T: ... class DesignSpaceDocument(LogMixin, AsDictMixin): """The DesignSpaceDocument object can read and write ``.designspace`` data. It imports the axes, sources, variable fonts and instances to very basic **descriptor** objects that store the data in attributes. Data is added to the document by creating such descriptor objects, filling them with data and then adding them to the document. This makes it easy to integrate this object in different contexts. The **DesignSpaceDocument** object can be subclassed to work with different objects, as long as they have the same attributes. Reader and Writer objects can be subclassed as well. **Note:** Python attribute names are usually camelCased, the corresponding `XML <document-xml-structure>`_ attributes are usually all lowercase. .. code:: python from fontTools.designspaceLib import DesignSpaceDocument doc = DesignSpaceDocument.fromfile("some/path/to/my.designspace") doc.formatVersion doc.elidedFallbackName doc.axes doc.locationLabels doc.rules doc.rulesProcessingLast doc.sources doc.variableFonts doc.instances doc.lib """ def __init__(self, readerClass=None, writerClass=None): self.path = None """String, optional. When the document is read from the disk, this is the full path that was given to :meth:`read` or :meth:`fromfile`. """ self.filename = None """String, optional. When the document is read from the disk, this is its original file name, i.e. the last part of its path. When the document is produced by a Python script and still only exists in memory, the producing script can write here an indication of a possible "good" filename, in case one wants to save the file somewhere. """ self.formatVersion: Optional[str] = None """Format version for this document, as a string. E.g. "4.0" """ self.elidedFallbackName: Optional[str] = None """STAT Style Attributes Header field ``elidedFallbackNameID``. See: `OTSpec STAT Style Attributes Header <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#style-attributes-header>`_ .. versionadded:: 5.0 """ self.axes: List[Union[AxisDescriptor, DiscreteAxisDescriptor]] = [] """List of this document's axes.""" self.locationLabels: List[LocationLabelDescriptor] = [] """List of this document's STAT format 4 labels. .. versionadded:: 5.0""" self.rules: List[RuleDescriptor] = [] """List of this document's rules.""" self.rulesProcessingLast: bool = False """This flag indicates whether the substitution rules should be applied before or after other glyph substitution features. - False: before - True: after. Default is False. For new projects, you probably want True. See the following issues for more information: `fontTools#1371 <https://github.com/fonttools/fonttools/issues/1371#issuecomment-590214572>`__ `fontTools#2050 <https://github.com/fonttools/fonttools/issues/2050#issuecomment-678691020>`__ If you want to use a different feature altogether, e.g. ``calt``, use the lib key ``com.github.fonttools.varLib.featureVarsFeatureTag`` .. code:: xml <lib> <dict> <key>com.github.fonttools.varLib.featureVarsFeatureTag</key> <string>calt</string> </dict> </lib> """ self.sources: List[SourceDescriptor] = [] """List of this document's sources.""" self.variableFonts: List[VariableFontDescriptor] = [] """List of this document's variable fonts. .. versionadded:: 5.0""" self.instances: List[InstanceDescriptor] = [] """List of this document's instances.""" self.lib: Dict = {} """User defined, custom data associated with the whole document. Use reverse-DNS notation to identify your own data. Respect the data stored by others. """ self.default: Optional[str] = None """Name of the default master. This attribute is updated by the :meth:`findDefault` """ if readerClass is not None: self.readerClass = readerClass else: self.readerClass = BaseDocReader if writerClass is not None: self.writerClass = writerClass else: self.writerClass = BaseDocWriter def fromfile(cls, path, readerClass=None, writerClass=None): """Read a designspace file from ``path`` and return a new instance of :class:. """ self = cls(readerClass=readerClass, writerClass=writerClass) self.read(path) return self def fromstring(cls, string, readerClass=None, writerClass=None): self = cls(readerClass=readerClass, writerClass=writerClass) reader = self.readerClass.fromstring(string, self) reader.read() if self.sources: self.findDefault() return self def tostring(self, encoding=None): """Returns the designspace as a string. Default encoding ``utf-8``.""" if encoding is str or (encoding is not None and encoding.lower() == "unicode"): f = StringIO() xml_declaration = False elif encoding is None or encoding == "utf-8": f = BytesIO() encoding = "UTF-8" xml_declaration = True else: raise ValueError("unsupported encoding: '%s'" % encoding) writer = self.writerClass(f, self) writer.write(encoding=encoding, xml_declaration=xml_declaration) return f.getvalue() def read(self, path): """Read a designspace file from ``path`` and populates the fields of ``self`` with the data. """ if hasattr(path, "__fspath__"): # support os.PathLike objects path = path.__fspath__() self.path = path self.filename = os.path.basename(path) reader = self.readerClass(path, self) reader.read() if self.sources: self.findDefault() def write(self, path): """Write this designspace to ``path``.""" if hasattr(path, "__fspath__"): # support os.PathLike objects path = path.__fspath__() self.path = path self.filename = os.path.basename(path) self.updatePaths() writer = self.writerClass(path, self) writer.write() def _posixRelativePath(self, otherPath): relative = os.path.relpath(otherPath, os.path.dirname(self.path)) return posix(relative) def updatePaths(self): """ Right before we save we need to identify and respond to the following situations: In each descriptor, we have to do the right thing for the filename attribute. :: case 1. descriptor.filename == None descriptor.path == None -- action: write as is, descriptors will not have a filename attr. useless, but no reason to interfere. case 2. descriptor.filename == "../something" descriptor.path == None -- action: write as is. The filename attr should not be touched. case 3. descriptor.filename == None descriptor.path == "~/absolute/path/there" -- action: calculate the relative path for filename. We're not overwriting some other value for filename, it should be fine case 4. descriptor.filename == '../somewhere' descriptor.path == "~/absolute/path/there" -- action: there is a conflict between the given filename, and the path. So we know where the file is relative to the document. Can't guess why they're different, we just choose for path to be correct and update filename. """ assert self.path is not None for descriptor in self.sources + self.instances: if descriptor.path is not None: # case 3 and 4: filename gets updated and relativized descriptor.filename = self._posixRelativePath(descriptor.path) def addSource(self, sourceDescriptor: SourceDescriptor): """Add the given ``sourceDescriptor`` to ``doc.sources``.""" self.sources.append(sourceDescriptor) def addSourceDescriptor(self, **kwargs): """Instantiate a new :class:`SourceDescriptor` using the given ``kwargs`` and add it to ``doc.sources``. """ source = self.writerClass.sourceDescriptorClass(**kwargs) self.addSource(source) return source def addInstance(self, instanceDescriptor: InstanceDescriptor): """Add the given ``instanceDescriptor`` to :attr:`instances`.""" self.instances.append(instanceDescriptor) def addInstanceDescriptor(self, **kwargs): """Instantiate a new :class:`InstanceDescriptor` using the given ``kwargs`` and add it to :attr:`instances`. """ instance = self.writerClass.instanceDescriptorClass(**kwargs) self.addInstance(instance) return instance def addAxis(self, axisDescriptor: Union[AxisDescriptor, DiscreteAxisDescriptor]): """Add the given ``axisDescriptor`` to :attr:`axes`.""" self.axes.append(axisDescriptor) def addAxisDescriptor(self, **kwargs): """Instantiate a new :class:`AxisDescriptor` using the given ``kwargs`` and add it to :attr:`axes`. The axis will be and instance of :class:`DiscreteAxisDescriptor` if the ``kwargs`` provide a ``value``, or a :class:`AxisDescriptor` otherwise. """ if "values" in kwargs: axis = self.writerClass.discreteAxisDescriptorClass(**kwargs) else: axis = self.writerClass.axisDescriptorClass(**kwargs) self.addAxis(axis) return axis def addRule(self, ruleDescriptor: RuleDescriptor): """Add the given ``ruleDescriptor`` to :attr:`rules`.""" self.rules.append(ruleDescriptor) def addRuleDescriptor(self, **kwargs): """Instantiate a new :class:`RuleDescriptor` using the given ``kwargs`` and add it to :attr:`rules`. """ rule = self.writerClass.ruleDescriptorClass(**kwargs) self.addRule(rule) return rule def addVariableFont(self, variableFontDescriptor: VariableFontDescriptor): """Add the given ``variableFontDescriptor`` to :attr:`variableFonts`. .. versionadded:: 5.0 """ self.variableFonts.append(variableFontDescriptor) def addVariableFontDescriptor(self, **kwargs): """Instantiate a new :class:`VariableFontDescriptor` using the given ``kwargs`` and add it to :attr:`variableFonts`. .. versionadded:: 5.0 """ variableFont = self.writerClass.variableFontDescriptorClass(**kwargs) self.addVariableFont(variableFont) return variableFont def addLocationLabel(self, locationLabelDescriptor: LocationLabelDescriptor): """Add the given ``locationLabelDescriptor`` to :attr:`locationLabels`. .. versionadded:: 5.0 """ self.locationLabels.append(locationLabelDescriptor) def addLocationLabelDescriptor(self, **kwargs): """Instantiate a new :class:`LocationLabelDescriptor` using the given ``kwargs`` and add it to :attr:`locationLabels`. .. versionadded:: 5.0 """ locationLabel = self.writerClass.locationLabelDescriptorClass(**kwargs) self.addLocationLabel(locationLabel) return locationLabel def newDefaultLocation(self): """Return a dict with the default location in design space coordinates.""" # Without OrderedDict, output XML would be non-deterministic. # https://github.com/LettError/designSpaceDocument/issues/10 loc = collections.OrderedDict() for axisDescriptor in self.axes: loc[axisDescriptor.name] = axisDescriptor.map_forward( axisDescriptor.default ) return loc def labelForUserLocation( self, userLocation: SimpleLocationDict ) -> Optional[LocationLabelDescriptor]: """Return the :class:`LocationLabel` that matches the given ``userLocation``, or ``None`` if no such label exists. .. versionadded:: 5.0 """ return next( ( label for label in self.locationLabels if label.userLocation == userLocation ), None, ) def updateFilenameFromPath(self, masters=True, instances=True, force=False): """Set a descriptor filename attr from the path and this document path. If the filename attribute is not None: skip it. """ if masters: for descriptor in self.sources: if descriptor.filename is not None and not force: continue if self.path is not None: descriptor.filename = self._posixRelativePath(descriptor.path) if instances: for descriptor in self.instances: if descriptor.filename is not None and not force: continue if self.path is not None: descriptor.filename = self._posixRelativePath(descriptor.path) def newAxisDescriptor(self): """Ask the writer class to make us a new axisDescriptor.""" return self.writerClass.getAxisDecriptor() def newSourceDescriptor(self): """Ask the writer class to make us a new sourceDescriptor.""" return self.writerClass.getSourceDescriptor() def newInstanceDescriptor(self): """Ask the writer class to make us a new instanceDescriptor.""" return self.writerClass.getInstanceDescriptor() def getAxisOrder(self): """Return a list of axis names, in the same order as defined in the document.""" names = [] for axisDescriptor in self.axes: names.append(axisDescriptor.name) return names def getAxis(self, name: str) -> AxisDescriptor | DiscreteAxisDescriptor | None: """Return the axis with the given ``name``, or ``None`` if no such axis exists.""" return next((axis for axis in self.axes if axis.name == name), None) def getAxisByTag(self, tag: str) -> AxisDescriptor | DiscreteAxisDescriptor | None: """Return the axis with the given ``tag``, or ``None`` if no such axis exists.""" return next((axis for axis in self.axes if axis.tag == tag), None) def getLocationLabel(self, name: str) -> Optional[LocationLabelDescriptor]: """Return the top-level location label with the given ``name``, or ``None`` if no such label exists. .. versionadded:: 5.0 """ for label in self.locationLabels: if label.name == name: return label return None def map_forward(self, userLocation: SimpleLocationDict) -> SimpleLocationDict: """Map a user location to a design location. Assume that missing coordinates are at the default location for that axis. Note: the output won't be anisotropic, only the xvalue is set. .. versionadded:: 5.0 """ return { axis.name: axis.map_forward(userLocation.get(axis.name, axis.default)) for axis in self.axes } def map_backward( self, designLocation: AnisotropicLocationDict ) -> SimpleLocationDict: """Map a design location to a user location. Assume that missing coordinates are at the default location for that axis. When the input has anisotropic locations, only the xvalue is used. .. versionadded:: 5.0 """ return { axis.name: ( axis.map_backward(designLocation[axis.name]) if axis.name in designLocation else axis.default ) for axis in self.axes } def findDefault(self): """Set and return SourceDescriptor at the default location or None. The default location is the set of all `default` values in user space of all axes. This function updates the document's :attr:`default` value. .. versionchanged:: 5.0 Allow the default source to not specify some of the axis values, and they are assumed to be the default. See :meth:`SourceDescriptor.getFullDesignLocation()` """ self.default = None # Convert the default location from user space to design space before comparing # it against the SourceDescriptor locations (always in design space). defaultDesignLocation = self.newDefaultLocation() for sourceDescriptor in self.sources: if sourceDescriptor.getFullDesignLocation(self) == defaultDesignLocation: self.default = sourceDescriptor return sourceDescriptor return None def normalizeLocation(self, location): """Return a dict with normalized axis values.""" from fontTools.varLib.models import normalizeValue new = {} for axis in self.axes: if axis.name not in location: # skipping this dimension it seems continue value = location[axis.name] # 'anisotropic' location, take first coord only if isinstance(value, tuple): value = value[0] triple = [ axis.map_forward(v) for v in (axis.minimum, axis.default, axis.maximum) ] new[axis.name] = normalizeValue(value, triple) return new def normalize(self): """ Normalise the geometry of this designspace: - scale all the locations of all masters and instances to the -1 - 0 - 1 value. - we need the axis data to do the scaling, so we do those last. """ # masters for item in self.sources: item.location = self.normalizeLocation(item.location) # instances for item in self.instances: # glyph masters for this instance for _, glyphData in item.glyphs.items(): glyphData["instanceLocation"] = self.normalizeLocation( glyphData["instanceLocation"] ) for glyphMaster in glyphData["masters"]: glyphMaster["location"] = self.normalizeLocation( glyphMaster["location"] ) item.location = self.normalizeLocation(item.location) # the axes for axis in self.axes: # scale the map first newMap = [] for inputValue, outputValue in axis.map: newOutputValue = self.normalizeLocation({axis.name: outputValue}).get( axis.name ) newMap.append((inputValue, newOutputValue)) if newMap: axis.map = newMap # finally the axis values minimum = self.normalizeLocation({axis.name: axis.minimum}).get(axis.name) maximum = self.normalizeLocation({axis.name: axis.maximum}).get(axis.name) default = self.normalizeLocation({axis.name: axis.default}).get(axis.name) # and set them in the axis.minimum axis.minimum = minimum axis.maximum = maximum axis.default = default # now the rules for rule in self.rules: newConditionSets = [] for conditions in rule.conditionSets: newConditions = [] for cond in conditions: if cond.get("minimum") is not None: minimum = self.normalizeLocation( {cond["name"]: cond["minimum"]} ).get(cond["name"]) else: minimum = None if cond.get("maximum") is not None: maximum = self.normalizeLocation( {cond["name"]: cond["maximum"]} ).get(cond["name"]) else: maximum = None newConditions.append( dict(name=cond["name"], minimum=minimum, maximum=maximum) ) newConditionSets.append(newConditions) rule.conditionSets = newConditionSets def loadSourceFonts(self, opener, **kwargs): """Ensure SourceDescriptor.font attributes are loaded, and return list of fonts. Takes a callable which initializes a new font object (e.g. TTFont, or defcon.Font, etc.) from the SourceDescriptor.path, and sets the SourceDescriptor.font attribute. If the font attribute is already not None, it is not loaded again. Fonts with the same path are only loaded once and shared among SourceDescriptors. For example, to load UFO sources using defcon: designspace = DesignSpaceDocument.fromfile("path/to/my.designspace") designspace.loadSourceFonts(defcon.Font) Or to load masters as FontTools binary fonts, including extra options: designspace.loadSourceFonts(ttLib.TTFont, recalcBBoxes=False) Args: opener (Callable): takes one required positional argument, the source.path, and an optional list of keyword arguments, and returns a new font object loaded from the path. **kwargs: extra options passed on to the opener function. Returns: List of font objects in the order they appear in the sources list. """ # we load fonts with the same source.path only once loaded = {} fonts = [] for source in self.sources: if source.font is not None: # font already loaded fonts.append(source.font) continue if source.path in loaded: source.font = loaded[source.path] else: if source.path is None: raise DesignSpaceDocumentError( "Designspace source '%s' has no 'path' attribute" % (source.name or "<Unknown>") ) source.font = opener(source.path, **kwargs) loaded[source.path] = source.font fonts.append(source.font) return fonts def formatTuple(self): """Return the formatVersion as a tuple of (major, minor). .. versionadded:: 5.0 """ if self.formatVersion is None: return (5, 0) numbers = (int(i) for i in self.formatVersion.split(".")) major = next(numbers) minor = next(numbers, 0) return (major, minor) def getVariableFonts(self) -> List[VariableFontDescriptor]: """Return all variable fonts defined in this document, or implicit variable fonts that can be built from the document's continuous axes. In the case of Designspace documents before version 5, the whole document was implicitly describing a variable font that covers the whole space. In version 5 and above documents, there can be as many variable fonts as there are locations on discrete axes. .. seealso:: :func:`splitInterpolable` .. versionadded:: 5.0 """ if self.variableFonts: return self.variableFonts variableFonts = [] discreteAxes = [] rangeAxisSubsets: List[ Union[RangeAxisSubsetDescriptor, ValueAxisSubsetDescriptor] ] = [] for axis in self.axes: if hasattr(axis, "values"): # Mypy doesn't support narrowing union types via hasattr() # TODO(Python 3.10): use TypeGuard # https://mypy.readthedocs.io/en/stable/type_narrowing.html axis = cast(DiscreteAxisDescriptor, axis) discreteAxes.append(axis) # type: ignore else: rangeAxisSubsets.append(RangeAxisSubsetDescriptor(name=axis.name)) valueCombinations = itertools.product(*[axis.values for axis in discreteAxes]) for values in valueCombinations: basename = None if self.filename is not None: basename = os.path.splitext(self.filename)[0] + "-VF" if self.path is not None: basename = os.path.splitext(os.path.basename(self.path))[0] + "-VF" if basename is None: basename = "VF" axisNames = "".join( [f"-{axis.tag}{value}" for axis, value in zip(discreteAxes, values)] ) variableFonts.append( VariableFontDescriptor( name=f"{basename}{axisNames}", axisSubsets=rangeAxisSubsets + [ ValueAxisSubsetDescriptor(name=axis.name, userValue=value) for axis, value in zip(discreteAxes, values) ], ) ) return variableFonts def deepcopyExceptFonts(self): """Allow deep-copying a DesignSpace document without deep-copying attached UFO fonts or TTFont objects. The :attr:`font` attribute is shared by reference between the original and the copy. .. versionadded:: 5.0 """ fonts = [source.font for source in self.sources] try: for source in self.sources: source.font = None res = copy.deepcopy(self) for source, font in zip(res.sources, fonts): source.font = font return res finally: for source, font in zip(self.sources, fonts): source.font = font The provided code snippet includes necessary dependencies for implementing the `interpolate_layout` function. Write a Python function `def interpolate_layout(designspace, loc, master_finder=lambda s: s, mapped=False)` to solve the following problem: Interpolate GPOS from a designspace file and location. If master_finder is set, it should be a callable that takes master filename as found in designspace file and map it to master font binary as to be opened (eg. .ttf or .otf). If mapped is False (default), then location is mapped using the map element of the axes in designspace file. If mapped is True, it is assumed that location is in designspace's internal space and no mapping is performed. Here is the function: def interpolate_layout(designspace, loc, master_finder=lambda s: s, mapped=False): """ Interpolate GPOS from a designspace file and location. If master_finder is set, it should be a callable that takes master filename as found in designspace file and map it to master font binary as to be opened (eg. .ttf or .otf). If mapped is False (default), then location is mapped using the map element of the axes in designspace file. If mapped is True, it is assumed that location is in designspace's internal space and no mapping is performed. """ if hasattr(designspace, "sources"): # Assume a DesignspaceDocument pass else: # Assume a file path from fontTools.designspaceLib import DesignSpaceDocument designspace = DesignSpaceDocument.fromfile(designspace) ds = load_designspace(designspace) log.info("Building interpolated font") log.info("Loading master fonts") master_fonts = load_masters(designspace, master_finder) font = deepcopy(master_fonts[ds.base_idx]) log.info("Location: %s", pformat(loc)) if not mapped: loc = {name: ds.axes[name].map_forward(v) for name, v in loc.items()} log.info("Internal location: %s", pformat(loc)) loc = models.normalizeLocation(loc, ds.internal_axis_supports) log.info("Normalized location: %s", pformat(loc)) # Assume single-model for now. model = models.VariationModel(ds.normalized_master_locs) assert 0 == model.mapping[ds.base_idx] merger = InstancerMerger(font, model, loc) log.info("Building interpolated tables") # TODO GSUB/GDEF merger.mergeTables(font, master_fonts, ["GPOS"]) return font
Interpolate GPOS from a designspace file and location. If master_finder is set, it should be a callable that takes master filename as found in designspace file and map it to master font binary as to be opened (eg. .ttf or .otf). If mapped is False (default), then location is mapped using the map element of the axes in designspace file. If mapped is True, it is assumed that location is in designspace's internal space and no mapping is performed.
175,298
from fontTools.misc.fixedTools import floatToFixedToFloat, floatToFixed from fontTools.misc.roundTools import otRound from fontTools.pens.boundsPen import BoundsPen from fontTools.ttLib import TTFont, newTable from fontTools.ttLib.tables import ttProgram from fontTools.ttLib.tables._g_l_y_f import ( GlyphCoordinates, flagOverlapSimple, OVERLAP_COMPOUND, ) from fontTools.varLib.models import ( supportScalar, normalizeLocation, piecewiseLinearMap, ) from fontTools.varLib.merger import MutatorMerger from fontTools.varLib.varStore import VarStoreInstancer from fontTools.varLib.mvar import MVAR_ENTRIES from fontTools.varLib.iup import iup_delta import fontTools.subset.cff import os.path import logging from io import BytesIO log = logging.getLogger("fontTools.varlib.mutator") OS2_WIDTH_CLASS_VALUES = {} for i, (prev, curr) in enumerate(zip(percents[:-1], percents[1:]), start=1): half = (prev + curr) / 2 OS2_WIDTH_CLASS_VALUES[half] = i def interpolate_cff2_PrivateDict(topDict, interpolateFromDeltas): pd_blend_lists = ( "BlueValues", "OtherBlues", "FamilyBlues", "FamilyOtherBlues", "StemSnapH", "StemSnapV", ) pd_blend_values = ("BlueScale", "BlueShift", "BlueFuzz", "StdHW", "StdVW") for fontDict in topDict.FDArray: pd = fontDict.Private vsindex = pd.vsindex if (hasattr(pd, "vsindex")) else 0 for key, value in pd.rawDict.items(): if (key in pd_blend_values) and isinstance(value, list): delta = interpolateFromDeltas(vsindex, value[1:]) pd.rawDict[key] = otRound(value[0] + delta) elif (key in pd_blend_lists) and isinstance(value[0], list): """If any argument in a BlueValues list is a blend list, then they all are. The first value of each list is an absolute value. The delta tuples are calculated from relative master values, hence we need to append all the deltas to date to each successive absolute value.""" delta = 0 for i, val_list in enumerate(value): delta += otRound(interpolateFromDeltas(vsindex, val_list[1:])) value[i] = val_list[0] + delta def interpolate_cff2_charstrings(topDict, interpolateFromDeltas, glyphOrder): charstrings = topDict.CharStrings for gname in glyphOrder: # Interpolate charstring # e.g replace blend op args with regular args, # and use and discard vsindex op. charstring = charstrings[gname] new_program = [] vsindex = 0 last_i = 0 for i, token in enumerate(charstring.program): if token == "vsindex": vsindex = charstring.program[i - 1] if last_i != 0: new_program.extend(charstring.program[last_i : i - 1]) last_i = i + 1 elif token == "blend": num_regions = charstring.getNumRegions(vsindex) numMasters = 1 + num_regions num_args = charstring.program[i - 1] # The program list starting at program[i] is now: # ..args for following operations # num_args values from the default font # num_args tuples, each with numMasters-1 delta values # num_blend_args # 'blend' argi = i - (num_args * numMasters + 1) end_args = tuplei = argi + num_args while argi < end_args: next_ti = tuplei + num_regions deltas = charstring.program[tuplei:next_ti] delta = interpolateFromDeltas(vsindex, deltas) charstring.program[argi] += otRound(delta) tuplei = next_ti argi += 1 new_program.extend(charstring.program[last_i:end_args]) last_i = i + 1 if last_i != 0: new_program.extend(charstring.program[last_i:]) charstring.program = new_program def interpolate_cff2_metrics(varfont, topDict, glyphOrder, loc): """Unlike TrueType glyphs, neither advance width nor bounding box info is stored in a CFF2 charstring. The width data exists only in the hmtx and HVAR tables. Since LSB data cannot be interpolated reliably from the master LSB values in the hmtx table, we traverse the charstring to determine the actual bound box.""" charstrings = topDict.CharStrings boundsPen = BoundsPen(glyphOrder) hmtx = varfont["hmtx"] hvar_table = None if "HVAR" in varfont: hvar_table = varfont["HVAR"].table fvar = varfont["fvar"] varStoreInstancer = VarStoreInstancer(hvar_table.VarStore, fvar.axes, loc) for gid, gname in enumerate(glyphOrder): entry = list(hmtx[gname]) # get width delta. if hvar_table: if hvar_table.AdvWidthMap: width_idx = hvar_table.AdvWidthMap.mapping[gname] else: width_idx = gid width_delta = otRound(varStoreInstancer[width_idx]) else: width_delta = 0 # get LSB. boundsPen.init() charstring = charstrings[gname] charstring.draw(boundsPen) if boundsPen.bounds is None: # Happens with non-marking glyphs lsb_delta = 0 else: lsb = otRound(boundsPen.bounds[0]) lsb_delta = entry[1] - lsb if lsb_delta or width_delta: if width_delta: entry[0] = max(0, entry[0] + width_delta) if lsb_delta: entry[1] = lsb hmtx[gname] = tuple(entry) def floatToFixed(value, precisionBits): """Converts a float to a fixed-point number given the number of precision bits. Args: value (float): Floating point value. precisionBits (int): Number of precision bits. Returns: int: Fixed-point representation. Examples:: >>> floatToFixed(-0.61883544921875, precisionBits=14) -10139 >>> floatToFixed(-0.61884, precisionBits=14) -10139 """ return otRound(value * (1 << precisionBits)) def floatToFixedToFloat(value, precisionBits): """Converts a float to a fixed-point number and back again. By converting the float to fixed, rounding it, and converting it back to float again, this returns a floating point values which is exactly representable in fixed-point format. Note: this **is** equivalent to ``fixedToFloat(floatToFixed(value))``. Args: value (float): The input floating point value. precisionBits (int): Number of precision bits. Returns: float: The transformed and rounded value. Examples:: >>> import math >>> f1 = -0.61884 >>> f2 = floatToFixedToFloat(-0.61884, precisionBits=14) >>> f1 != f2 True >>> math.isclose(f2, -0.61883544921875) True """ scale = 1 << precisionBits return otRound(value * scale) / scale def otRound(value): """Round float value to nearest integer towards ``+Infinity``. The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_) defines the required method for converting floating point values to fixed-point. In particular it specifies the following rounding strategy: for fractional values of 0.5 and higher, take the next higher integer; for other fractional values, truncate. This function rounds the floating-point value according to this strategy in preparation for conversion to fixed-point. Args: value (float): The input floating-point value. Returns float: The rounded value. """ # See this thread for how we ended up with this implementation: # https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166 return int(math.floor(value + 0.5)) flagOverlapSimple = 0x40 OVERLAP_COMPOUND = 0x0400 class GlyphCoordinates(object): """A list of glyph coordinates. Unlike an ordinary list, this is a numpy-like matrix object which supports matrix addition, scalar multiplication and other operations described below. """ def __init__(self, iterable=[]): self._a = array.array("d") self.extend(iterable) def array(self): """Returns the underlying array of coordinates""" return self._a def zeros(count): """Creates a new ``GlyphCoordinates`` object with all coordinates set to (0,0)""" g = GlyphCoordinates() g._a.frombytes(bytes(count * 2 * g._a.itemsize)) return g def copy(self): """Creates a new ``GlyphCoordinates`` object which is a copy of the current one.""" c = GlyphCoordinates() c._a.extend(self._a) return c def __len__(self): """Returns the number of coordinates in the array.""" return len(self._a) // 2 def __getitem__(self, k): """Returns a two element tuple (x,y)""" if isinstance(k, slice): indices = range(*k.indices(len(self))) return [self[i] for i in indices] a = self._a x = a[2 * k] y = a[2 * k + 1] return (int(x) if x.is_integer() else x, int(y) if y.is_integer() else y) def __setitem__(self, k, v): """Sets a point's coordinates to a two element tuple (x,y)""" if isinstance(k, slice): indices = range(*k.indices(len(self))) # XXX This only works if len(v) == len(indices) for j, i in enumerate(indices): self[i] = v[j] return self._a[2 * k], self._a[2 * k + 1] = v def __delitem__(self, i): """Removes a point from the list""" i = (2 * i) % len(self._a) del self._a[i] del self._a[i] def __repr__(self): return "GlyphCoordinates([" + ",".join(str(c) for c in self) + "])" def append(self, p): self._a.extend(tuple(p)) def extend(self, iterable): for p in iterable: self._a.extend(p) def toInt(self, *, round=otRound): a = self._a for i in range(len(a)): a[i] = round(a[i]) def relativeToAbsolute(self): a = self._a x, y = 0, 0 for i in range(0, len(a), 2): a[i] = x = a[i] + x a[i + 1] = y = a[i + 1] + y def absoluteToRelative(self): a = self._a x, y = 0, 0 for i in range(0, len(a), 2): nx = a[i] ny = a[i + 1] a[i] = nx - x a[i + 1] = ny - y x = nx y = ny def translate(self, p): """ >>> GlyphCoordinates([(1,2)]).translate((.5,0)) """ x, y = p if x == 0 and y == 0: return a = self._a for i in range(0, len(a), 2): a[i] += x a[i + 1] += y def scale(self, p): """ >>> GlyphCoordinates([(1,2)]).scale((.5,0)) """ x, y = p if x == 1 and y == 1: return a = self._a for i in range(0, len(a), 2): a[i] *= x a[i + 1] *= y def transform(self, t): """ >>> GlyphCoordinates([(1,2)]).transform(((.5,0),(.2,.5))) """ a = self._a for i in range(0, len(a), 2): x = a[i] y = a[i + 1] px = x * t[0][0] + y * t[1][0] py = x * t[0][1] + y * t[1][1] a[i] = px a[i + 1] = py def __eq__(self, other): """ >>> g = GlyphCoordinates([(1,2)]) >>> g2 = GlyphCoordinates([(1.0,2)]) >>> g3 = GlyphCoordinates([(1.5,2)]) >>> g == g2 True >>> g == g3 False >>> g2 == g3 False """ if type(self) != type(other): return NotImplemented return self._a == other._a def __ne__(self, other): """ >>> g = GlyphCoordinates([(1,2)]) >>> g2 = GlyphCoordinates([(1.0,2)]) >>> g3 = GlyphCoordinates([(1.5,2)]) >>> g != g2 False >>> g != g3 True >>> g2 != g3 True """ result = self.__eq__(other) return result if result is NotImplemented else not result # Math operations def __pos__(self): """ >>> g = GlyphCoordinates([(1,2)]) >>> g GlyphCoordinates([(1, 2)]) >>> g2 = +g >>> g2 GlyphCoordinates([(1, 2)]) >>> g2.translate((1,0)) >>> g2 GlyphCoordinates([(2, 2)]) >>> g GlyphCoordinates([(1, 2)]) """ return self.copy() def __neg__(self): """ >>> g = GlyphCoordinates([(1,2)]) >>> g GlyphCoordinates([(1, 2)]) >>> g2 = -g >>> g2 GlyphCoordinates([(-1, -2)]) >>> g GlyphCoordinates([(1, 2)]) """ r = self.copy() a = r._a for i in range(len(a)): a[i] = -a[i] return r def __round__(self, *, round=otRound): r = self.copy() r.toInt(round=round) return r def __add__(self, other): return self.copy().__iadd__(other) def __sub__(self, other): return self.copy().__isub__(other) def __mul__(self, other): return self.copy().__imul__(other) def __truediv__(self, other): return self.copy().__itruediv__(other) __radd__ = __add__ __rmul__ = __mul__ def __rsub__(self, other): return other + (-self) def __iadd__(self, other): """ >>> g = GlyphCoordinates([(1,2)]) >>> g += (.5,0) >>> g GlyphCoordinates([(1.5, 2)]) >>> g2 = GlyphCoordinates([(3,4)]) >>> g += g2 >>> g GlyphCoordinates([(4.5, 6)]) """ if isinstance(other, tuple): assert len(other) == 2 self.translate(other) return self if isinstance(other, GlyphCoordinates): other = other._a a = self._a assert len(a) == len(other) for i in range(len(a)): a[i] += other[i] return self return NotImplemented def __isub__(self, other): """ >>> g = GlyphCoordinates([(1,2)]) >>> g -= (.5,0) >>> g GlyphCoordinates([(0.5, 2)]) >>> g2 = GlyphCoordinates([(3,4)]) >>> g -= g2 >>> g GlyphCoordinates([(-2.5, -2)]) """ if isinstance(other, tuple): assert len(other) == 2 self.translate((-other[0], -other[1])) return self if isinstance(other, GlyphCoordinates): other = other._a a = self._a assert len(a) == len(other) for i in range(len(a)): a[i] -= other[i] return self return NotImplemented def __imul__(self, other): """ >>> g = GlyphCoordinates([(1,2)]) >>> g *= (2,.5) >>> g *= 2 >>> g GlyphCoordinates([(4, 2)]) >>> g = GlyphCoordinates([(1,2)]) >>> g *= 2 >>> g GlyphCoordinates([(2, 4)]) """ if isinstance(other, tuple): assert len(other) == 2 self.scale(other) return self if isinstance(other, Number): if other == 1: return self a = self._a for i in range(len(a)): a[i] *= other return self return NotImplemented def __itruediv__(self, other): """ >>> g = GlyphCoordinates([(1,3)]) >>> g /= (.5,1.5) >>> g /= 2 >>> g GlyphCoordinates([(1, 1)]) """ if isinstance(other, Number): other = (other, other) if isinstance(other, tuple): if other == (1, 1): return self assert len(other) == 2 self.scale((1.0 / other[0], 1.0 / other[1])) return self return NotImplemented def __bool__(self): """ >>> g = GlyphCoordinates([]) >>> bool(g) False >>> g = GlyphCoordinates([(0,0), (0.,0)]) >>> bool(g) True >>> g = GlyphCoordinates([(0,0), (1,0)]) >>> bool(g) True >>> g = GlyphCoordinates([(0,.5), (0,0)]) >>> bool(g) True """ return bool(self._a) __nonzero__ = __bool__ def normalizeLocation(location, axes, extrapolate=False): """Normalizes location based on axis min/default/max values from axes. >>> axes = {"wght": (100, 400, 900)} >>> normalizeLocation({"wght": 400}, axes) {'wght': 0.0} >>> normalizeLocation({"wght": 100}, axes) {'wght': -1.0} >>> normalizeLocation({"wght": 900}, axes) {'wght': 1.0} >>> normalizeLocation({"wght": 650}, axes) {'wght': 0.5} >>> normalizeLocation({"wght": 1000}, axes) {'wght': 1.0} >>> normalizeLocation({"wght": 0}, axes) {'wght': -1.0} >>> axes = {"wght": (0, 0, 1000)} >>> normalizeLocation({"wght": 0}, axes) {'wght': 0.0} >>> normalizeLocation({"wght": -1}, axes) {'wght': 0.0} >>> normalizeLocation({"wght": 1000}, axes) {'wght': 1.0} >>> normalizeLocation({"wght": 500}, axes) {'wght': 0.5} >>> normalizeLocation({"wght": 1001}, axes) {'wght': 1.0} >>> axes = {"wght": (0, 1000, 1000)} >>> normalizeLocation({"wght": 0}, axes) {'wght': -1.0} >>> normalizeLocation({"wght": -1}, axes) {'wght': -1.0} >>> normalizeLocation({"wght": 500}, axes) {'wght': -0.5} >>> normalizeLocation({"wght": 1000}, axes) {'wght': 0.0} >>> normalizeLocation({"wght": 1001}, axes) {'wght': 0.0} """ out = {} for tag, triple in axes.items(): v = location.get(tag, triple[1]) out[tag] = normalizeValue(v, triple, extrapolate=extrapolate) return out def supportScalar(location, support, ot=True, extrapolate=False, axisRanges=None): """Returns the scalar multiplier at location, for a master with support. If ot is True, then a peak value of zero for support of an axis means "axis does not participate". That is how OpenType Variation Font technology works. If extrapolate is True, axisRanges must be a dict that maps axis names to (axisMin, axisMax) tuples. >>> supportScalar({}, {}) 1.0 >>> supportScalar({'wght':.2}, {}) 1.0 >>> supportScalar({'wght':.2}, {'wght':(0,2,3)}) 0.1 >>> supportScalar({'wght':2.5}, {'wght':(0,2,4)}) 0.75 >>> supportScalar({'wght':2.5, 'wdth':0}, {'wght':(0,2,4), 'wdth':(-1,0,+1)}) 0.75 >>> supportScalar({'wght':2.5, 'wdth':.5}, {'wght':(0,2,4), 'wdth':(-1,0,+1)}, ot=False) 0.375 >>> supportScalar({'wght':2.5, 'wdth':0}, {'wght':(0,2,4), 'wdth':(-1,0,+1)}) 0.75 >>> supportScalar({'wght':2.5, 'wdth':.5}, {'wght':(0,2,4), 'wdth':(-1,0,+1)}) 0.75 >>> supportScalar({'wght':3}, {'wght':(0,1,2)}, extrapolate=True, axisRanges={'wght':(0, 2)}) -1.0 >>> supportScalar({'wght':-1}, {'wght':(0,1,2)}, extrapolate=True, axisRanges={'wght':(0, 2)}) -1.0 >>> supportScalar({'wght':3}, {'wght':(0,2,2)}, extrapolate=True, axisRanges={'wght':(0, 2)}) 1.5 >>> supportScalar({'wght':-1}, {'wght':(0,2,2)}, extrapolate=True, axisRanges={'wght':(0, 2)}) -0.5 """ if extrapolate and axisRanges is None: raise TypeError("axisRanges must be passed when extrapolate is True") scalar = 1.0 for axis, (lower, peak, upper) in support.items(): if ot: # OpenType-specific case handling if peak == 0.0: continue if lower > peak or peak > upper: continue if lower < 0.0 and upper > 0.0: continue v = location.get(axis, 0.0) else: assert axis in location v = location[axis] if v == peak: continue if extrapolate: axisMin, axisMax = axisRanges[axis] if v < axisMin and lower <= axisMin: if peak <= axisMin and peak < upper: scalar *= (v - upper) / (peak - upper) continue elif axisMin < peak: scalar *= (v - lower) / (peak - lower) continue elif axisMax < v and axisMax <= upper: if axisMax <= peak and lower < peak: scalar *= (v - lower) / (peak - lower) continue elif peak < axisMax: scalar *= (v - upper) / (peak - upper) continue if v <= lower or upper <= v: scalar = 0.0 break if v < peak: scalar *= (v - lower) / (peak - lower) else: # v > peak scalar *= (v - upper) / (peak - upper) return scalar def piecewiseLinearMap(v, mapping): keys = mapping.keys() if not keys: return v if v in keys: return mapping[v] k = min(keys) if v < k: return v + mapping[k] - k k = max(keys) if v > k: return v + mapping[k] - k # Interpolate a = max(k for k in keys if k < v) b = min(k for k in keys if k > v) va = mapping[a] vb = mapping[b] return va + (vb - va) * (v - a) / (b - a) class MutatorMerger(AligningMerger): """A merger that takes a variable font, and instantiates an instance. While there's no "merging" to be done per se, the operation can benefit from many operations that the aligning merger does.""" def __init__(self, font, instancer, deleteVariations=True): Merger.__init__(self, font) self.instancer = instancer self.deleteVariations = deleteVariations class VarStoreInstancer(object): def __init__(self, varstore, fvar_axes, location={}): self.fvar_axes = fvar_axes assert varstore is None or varstore.Format == 1 self._varData = varstore.VarData if varstore else [] self._regions = varstore.VarRegionList.Region if varstore else [] self.setLocation(location) def setLocation(self, location): self.location = dict(location) self._clearCaches() def _clearCaches(self): self._scalars = {} def _getScalar(self, regionIdx): scalar = self._scalars.get(regionIdx) if scalar is None: support = self._regions[regionIdx].get_support(self.fvar_axes) scalar = supportScalar(self.location, support) self._scalars[regionIdx] = scalar return scalar def interpolateFromDeltasAndScalars(deltas, scalars): delta = 0.0 for d, s in zip(deltas, scalars): if not s: continue delta += d * s return delta def __getitem__(self, varidx): major, minor = varidx >> 16, varidx & 0xFFFF if varidx == NO_VARIATION_INDEX: return 0.0 varData = self._varData scalars = [self._getScalar(ri) for ri in varData[major].VarRegionIndex] deltas = varData[major].Item[minor] return self.interpolateFromDeltasAndScalars(deltas, scalars) def interpolateFromDeltas(self, varDataIndex, deltas): varData = self._varData scalars = [self._getScalar(ri) for ri in varData[varDataIndex].VarRegionIndex] return self.interpolateFromDeltasAndScalars(deltas, scalars) MVAR_ENTRIES = { "hasc": ("OS/2", "sTypoAscender"), # horizontal ascender "hdsc": ("OS/2", "sTypoDescender"), # horizontal descender "hlgp": ("OS/2", "sTypoLineGap"), # horizontal line gap "hcla": ("OS/2", "usWinAscent"), # horizontal clipping ascent "hcld": ("OS/2", "usWinDescent"), # horizontal clipping descent "vasc": ("vhea", "ascent"), # vertical ascender "vdsc": ("vhea", "descent"), # vertical descender "vlgp": ("vhea", "lineGap"), # vertical line gap "hcrs": ("hhea", "caretSlopeRise"), # horizontal caret rise "hcrn": ("hhea", "caretSlopeRun"), # horizontal caret run "hcof": ("hhea", "caretOffset"), # horizontal caret offset "vcrs": ("vhea", "caretSlopeRise"), # vertical caret rise "vcrn": ("vhea", "caretSlopeRun"), # vertical caret run "vcof": ("vhea", "caretOffset"), # vertical caret offset "xhgt": ("OS/2", "sxHeight"), # x height "cpht": ("OS/2", "sCapHeight"), # cap height "sbxs": ("OS/2", "ySubscriptXSize"), # subscript em x size "sbys": ("OS/2", "ySubscriptYSize"), # subscript em y size "sbxo": ("OS/2", "ySubscriptXOffset"), # subscript em x offset "sbyo": ("OS/2", "ySubscriptYOffset"), # subscript em y offset "spxs": ("OS/2", "ySuperscriptXSize"), # superscript em x size "spys": ("OS/2", "ySuperscriptYSize"), # superscript em y size "spxo": ("OS/2", "ySuperscriptXOffset"), # superscript em x offset "spyo": ("OS/2", "ySuperscriptYOffset"), # superscript em y offset "strs": ("OS/2", "yStrikeoutSize"), # strikeout size "stro": ("OS/2", "yStrikeoutPosition"), # strikeout offset "unds": ("post", "underlineThickness"), # underline size "undo": ("post", "underlinePosition"), # underline offset #'gsp0': ('gasp', 'gaspRange[0].rangeMaxPPEM'), # gaspRange[0] #'gsp1': ('gasp', 'gaspRange[1].rangeMaxPPEM'), # gaspRange[1] #'gsp2': ('gasp', 'gaspRange[2].rangeMaxPPEM'), # gaspRange[2] #'gsp3': ('gasp', 'gaspRange[3].rangeMaxPPEM'), # gaspRange[3] #'gsp4': ('gasp', 'gaspRange[4].rangeMaxPPEM'), # gaspRange[4] #'gsp5': ('gasp', 'gaspRange[5].rangeMaxPPEM'), # gaspRange[5] #'gsp6': ('gasp', 'gaspRange[6].rangeMaxPPEM'), # gaspRange[6] #'gsp7': ('gasp', 'gaspRange[7].rangeMaxPPEM'), # gaspRange[7] #'gsp8': ('gasp', 'gaspRange[8].rangeMaxPPEM'), # gaspRange[8] #'gsp9': ('gasp', 'gaspRange[9].rangeMaxPPEM'), # gaspRange[9] } def iup_delta( deltas: _DeltaOrNoneSegment, coords: _PointSegment, ends: _Endpoints ) -> _DeltaSegment: """For the outline given in `coords`, with contour endpoints given in sorted increasing order in `ends`, interpolate any missing delta values in delta vector `deltas`. Returns fully filled-out delta vector.""" assert sorted(ends) == ends and len(coords) == (ends[-1] + 1 if ends else 0) + 4 n = len(coords) ends = ends + [n - 4, n - 3, n - 2, n - 1] out = [] start = 0 for end in ends: end += 1 contour = iup_contour(deltas[start:end], coords[start:end]) out.extend(contour) start = end return out class BytesIO(BufferedIOBase, BinaryIO): def __init__(self, initial_bytes: bytes = ...) -> None: ... # BytesIO does not contain a "name" field. This workaround is necessary # to allow BytesIO sub-classes to add this field, as it is defined # as a read-only property on IO[]. name: Any def __enter__(self: _T) -> _T: ... def getvalue(self) -> bytes: ... def getbuffer(self) -> memoryview: ... if sys.version_info >= (3, 7): def read1(self, __size: Optional[int] = ...) -> bytes: ... else: def read1(self, __size: Optional[int]) -> bytes: ... # type: ignore The provided code snippet includes necessary dependencies for implementing the `instantiateVariableFont` function. Write a Python function `def instantiateVariableFont(varfont, location, inplace=False, overlap=True)` to solve the following problem: Generate a static instance from a variable TTFont and a dictionary defining the desired location along the variable font's axes. The location values must be specified as user-space coordinates, e.g.: {'wght': 400, 'wdth': 100} By default, a new TTFont object is returned. If ``inplace`` is True, the input varfont is modified and reduced to a static font. When the overlap parameter is defined as True, OVERLAP_SIMPLE and OVERLAP_COMPOUND bits are set to 1. See https://docs.microsoft.com/en-us/typography/opentype/spec/glyf Here is the function: def instantiateVariableFont(varfont, location, inplace=False, overlap=True): """Generate a static instance from a variable TTFont and a dictionary defining the desired location along the variable font's axes. The location values must be specified as user-space coordinates, e.g.: {'wght': 400, 'wdth': 100} By default, a new TTFont object is returned. If ``inplace`` is True, the input varfont is modified and reduced to a static font. When the overlap parameter is defined as True, OVERLAP_SIMPLE and OVERLAP_COMPOUND bits are set to 1. See https://docs.microsoft.com/en-us/typography/opentype/spec/glyf """ if not inplace: # make a copy to leave input varfont unmodified stream = BytesIO() varfont.save(stream) stream.seek(0) varfont = TTFont(stream) fvar = varfont["fvar"] axes = {a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in fvar.axes} loc = normalizeLocation(location, axes) if "avar" in varfont: maps = varfont["avar"].segments loc = {k: piecewiseLinearMap(v, maps[k]) for k, v in loc.items()} # Quantize to F2Dot14, to avoid surprise interpolations. loc = {k: floatToFixedToFloat(v, 14) for k, v in loc.items()} # Location is normalized now log.info("Normalized location: %s", loc) if "gvar" in varfont: log.info("Mutating glyf/gvar tables") gvar = varfont["gvar"] glyf = varfont["glyf"] hMetrics = varfont["hmtx"].metrics vMetrics = getattr(varfont.get("vmtx"), "metrics", None) # get list of glyph names in gvar sorted by component depth glyphnames = sorted( gvar.variations.keys(), key=lambda name: ( glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth if glyf[name].isComposite() or glyf[name].isVarComposite() else 0, name, ), ) for glyphname in glyphnames: variations = gvar.variations[glyphname] coordinates, _ = glyf._getCoordinatesAndControls( glyphname, hMetrics, vMetrics ) origCoords, endPts = None, None for var in variations: scalar = supportScalar(loc, var.axes) if not scalar: continue delta = var.coordinates if None in delta: if origCoords is None: origCoords, g = glyf._getCoordinatesAndControls( glyphname, hMetrics, vMetrics ) delta = iup_delta(delta, origCoords, g.endPts) coordinates += GlyphCoordinates(delta) * scalar glyf._setCoordinates(glyphname, coordinates, hMetrics, vMetrics) else: glyf = None if "DSIG" in varfont: del varfont["DSIG"] if "cvar" in varfont: log.info("Mutating cvt/cvar tables") cvar = varfont["cvar"] cvt = varfont["cvt "] deltas = {} for var in cvar.variations: scalar = supportScalar(loc, var.axes) if not scalar: continue for i, c in enumerate(var.coordinates): if c is not None: deltas[i] = deltas.get(i, 0) + scalar * c for i, delta in deltas.items(): cvt[i] += otRound(delta) if "CFF2" in varfont: log.info("Mutating CFF2 table") glyphOrder = varfont.getGlyphOrder() CFF2 = varfont["CFF2"] topDict = CFF2.cff.topDictIndex[0] vsInstancer = VarStoreInstancer(topDict.VarStore.otVarStore, fvar.axes, loc) interpolateFromDeltas = vsInstancer.interpolateFromDeltas interpolate_cff2_PrivateDict(topDict, interpolateFromDeltas) CFF2.desubroutinize() interpolate_cff2_charstrings(topDict, interpolateFromDeltas, glyphOrder) interpolate_cff2_metrics(varfont, topDict, glyphOrder, loc) del topDict.rawDict["VarStore"] del topDict.VarStore if "MVAR" in varfont: log.info("Mutating MVAR table") mvar = varfont["MVAR"].table varStoreInstancer = VarStoreInstancer(mvar.VarStore, fvar.axes, loc) records = mvar.ValueRecord for rec in records: mvarTag = rec.ValueTag if mvarTag not in MVAR_ENTRIES: continue tableTag, itemName = MVAR_ENTRIES[mvarTag] delta = otRound(varStoreInstancer[rec.VarIdx]) if not delta: continue setattr( varfont[tableTag], itemName, getattr(varfont[tableTag], itemName) + delta, ) log.info("Mutating FeatureVariations") for tableTag in "GSUB", "GPOS": if not tableTag in varfont: continue table = varfont[tableTag].table if not getattr(table, "FeatureVariations", None): continue variations = table.FeatureVariations for record in variations.FeatureVariationRecord: applies = True for condition in record.ConditionSet.ConditionTable: if condition.Format == 1: axisIdx = condition.AxisIndex axisTag = fvar.axes[axisIdx].axisTag Min = condition.FilterRangeMinValue Max = condition.FilterRangeMaxValue v = loc[axisTag] if not (Min <= v <= Max): applies = False else: applies = False if not applies: break if applies: assert record.FeatureTableSubstitution.Version == 0x00010000 for rec in record.FeatureTableSubstitution.SubstitutionRecord: table.FeatureList.FeatureRecord[ rec.FeatureIndex ].Feature = rec.Feature break del table.FeatureVariations if "GDEF" in varfont and varfont["GDEF"].table.Version >= 0x00010003: log.info("Mutating GDEF/GPOS/GSUB tables") gdef = varfont["GDEF"].table instancer = VarStoreInstancer(gdef.VarStore, fvar.axes, loc) merger = MutatorMerger(varfont, instancer) merger.mergeTables(varfont, [varfont], ["GDEF", "GPOS"]) # Downgrade GDEF. del gdef.VarStore gdef.Version = 0x00010002 if gdef.MarkGlyphSetsDef is None: del gdef.MarkGlyphSetsDef gdef.Version = 0x00010000 if not ( gdef.LigCaretList or gdef.MarkAttachClassDef or gdef.GlyphClassDef or gdef.AttachList or (gdef.Version >= 0x00010002 and gdef.MarkGlyphSetsDef) ): del varfont["GDEF"] addidef = False if glyf: for glyph in glyf.glyphs.values(): if hasattr(glyph, "program"): instructions = glyph.program.getAssembly() # If GETVARIATION opcode is used in bytecode of any glyph add IDEF addidef = any(op.startswith("GETVARIATION") for op in instructions) if addidef: break if overlap: for glyph_name in glyf.keys(): glyph = glyf[glyph_name] # Set OVERLAP_COMPOUND bit for compound glyphs if glyph.isComposite(): glyph.components[0].flags |= OVERLAP_COMPOUND # Set OVERLAP_SIMPLE bit for simple glyphs elif glyph.numberOfContours > 0: glyph.flags[0] |= flagOverlapSimple if addidef: log.info("Adding IDEF to fpgm table for GETVARIATION opcode") asm = [] if "fpgm" in varfont: fpgm = varfont["fpgm"] asm = fpgm.program.getAssembly() else: fpgm = newTable("fpgm") fpgm.program = ttProgram.Program() varfont["fpgm"] = fpgm asm.append("PUSHB[000] 145") asm.append("IDEF[ ]") args = [str(len(loc))] for a in fvar.axes: args.append(str(floatToFixed(loc[a.axisTag], 14))) asm.append("NPUSHW[ ] " + " ".join(args)) asm.append("ENDF[ ]") fpgm.program.fromAssembly(asm) # Change maxp attributes as IDEF is added if "maxp" in varfont: maxp = varfont["maxp"] setattr( maxp, "maxInstructionDefs", 1 + getattr(maxp, "maxInstructionDefs", 0) ) setattr( maxp, "maxStackElements", max(len(loc), getattr(maxp, "maxStackElements", 0)), ) if "name" in varfont: log.info("Pruning name table") exclude = {a.axisNameID for a in fvar.axes} for i in fvar.instances: exclude.add(i.subfamilyNameID) exclude.add(i.postscriptNameID) if "ltag" in varfont: # Drop the whole 'ltag' table if all its language tags are referenced by # name records to be pruned. # TODO: prune unused ltag tags and re-enumerate langIDs accordingly excludedUnicodeLangIDs = [ n.langID for n in varfont["name"].names if n.nameID in exclude and n.platformID == 0 and n.langID != 0xFFFF ] if set(excludedUnicodeLangIDs) == set(range(len((varfont["ltag"].tags)))): del varfont["ltag"] varfont["name"].names[:] = [ n for n in varfont["name"].names if n.nameID not in exclude ] if "wght" in location and "OS/2" in varfont: varfont["OS/2"].usWeightClass = otRound(max(1, min(location["wght"], 1000))) if "wdth" in location: wdth = location["wdth"] for percent, widthClass in sorted(OS2_WIDTH_CLASS_VALUES.items()): if wdth < percent: varfont["OS/2"].usWidthClass = widthClass break else: varfont["OS/2"].usWidthClass = 9 if "slnt" in location and "post" in varfont: varfont["post"].italicAngle = max(-90, min(location["slnt"], 90)) log.info("Removing variable tables") for tag in ("avar", "cvar", "fvar", "gvar", "HVAR", "MVAR", "VVAR", "STAT"): if tag in varfont: del varfont[tag] return varfont
Generate a static instance from a variable TTFont and a dictionary defining the desired location along the variable font's axes. The location values must be specified as user-space coordinates, e.g.: {'wght': 400, 'wdth': 100} By default, a new TTFont object is returned. If ``inplace`` is True, the input varfont is modified and reduced to a static font. When the overlap parameter is defined as True, OVERLAP_SIMPLE and OVERLAP_COMPOUND bits are set to 1. See https://docs.microsoft.com/en-us/typography/opentype/spec/glyf
175,299
from collections import namedtuple from fontTools.cffLib import ( maxStackLimit, TopDictIndex, buildOrder, topDictOperators, topDictOperators2, privateDictOperators, privateDictOperators2, FDArrayIndex, FontDict, VarStoreData, ) from io import BytesIO from fontTools.cffLib.specializer import specializeCommands, commandsToProgram from fontTools.ttLib import newTable from fontTools import varLib from fontTools.varLib.models import allEqual from fontTools.misc.roundTools import roundFunc from fontTools.misc.psCharStrings import T2CharString, T2OutlineExtractor from fontTools.pens.t2CharStringPen import T2CharStringPen from functools import partial from .errors import ( VarLibCFFDictMergeError, VarLibCFFPointTypeMergeError, VarLibCFFHintTypeMergeError, VarLibMergeError, ) def lib_convertCFFToCFF2(cff, otFont): # This assumes a decompiled CFF table. cff2GetGlyphOrder = cff.otFont.getGlyphOrder topDictData = TopDictIndex(None, cff2GetGlyphOrder, None) topDictData.items = cff.topDictIndex.items cff.topDictIndex = topDictData topDict = topDictData[0] if hasattr(topDict, "Private"): privateDict = topDict.Private else: privateDict = None opOrder = buildOrder(topDictOperators2) topDict.order = opOrder topDict.cff2GetGlyphOrder = cff2GetGlyphOrder if not hasattr(topDict, "FDArray"): fdArray = topDict.FDArray = FDArrayIndex() fdArray.strings = None fdArray.GlobalSubrs = topDict.GlobalSubrs topDict.GlobalSubrs.fdArray = fdArray charStrings = topDict.CharStrings if charStrings.charStringsAreIndexed: charStrings.charStringsIndex.fdArray = fdArray else: charStrings.fdArray = fdArray fontDict = FontDict() fontDict.setCFF2(True) fdArray.append(fontDict) fontDict.Private = privateDict privateOpOrder = buildOrder(privateDictOperators2) if privateDict is not None: for entry in privateDictOperators: key = entry[1] if key not in privateOpOrder: if key in privateDict.rawDict: # print "Removing private dict", key del privateDict.rawDict[key] if hasattr(privateDict, key): delattr(privateDict, key) # print "Removing privateDict attr", key else: # clean up the PrivateDicts in the fdArray fdArray = topDict.FDArray privateOpOrder = buildOrder(privateDictOperators2) for fontDict in fdArray: fontDict.setCFF2(True) for key in list(fontDict.rawDict.keys()): if key not in fontDict.order: del fontDict.rawDict[key] if hasattr(fontDict, key): delattr(fontDict, key) privateDict = fontDict.Private for entry in privateDictOperators: key = entry[1] if key not in privateOpOrder: if key in privateDict.rawDict: # print "Removing private dict", key del privateDict.rawDict[key] if hasattr(privateDict, key): delattr(privateDict, key) # print "Removing privateDict attr", key # Now delete up the deprecated topDict operators from CFF 1.0 for entry in topDictOperators: key = entry[1] if key not in opOrder: if key in topDict.rawDict: del topDict.rawDict[key] if hasattr(topDict, key): delattr(topDict, key) # At this point, the Subrs and Charstrings are all still T2Charstring class # easiest to fix this by compiling, then decompiling again cff.major = 2 file = BytesIO() cff.compile(file, otFont, isCFF2=True) file.seek(0) cff.decompile(file, otFont, isCFF2=True) def convertCFFtoCFF2(varFont): # Convert base font to a single master CFF2 font. cffTable = varFont["CFF "] lib_convertCFFToCFF2(cffTable.cff, varFont) newCFF2 = newTable("CFF2") newCFF2.cff = cffTable.cff varFont["CFF2"] = newCFF2 del varFont["CFF "]
null
175,300
from collections import namedtuple from fontTools.cffLib import ( maxStackLimit, TopDictIndex, buildOrder, topDictOperators, topDictOperators2, privateDictOperators, privateDictOperators2, FDArrayIndex, FontDict, VarStoreData, ) from io import BytesIO from fontTools.cffLib.specializer import specializeCommands, commandsToProgram from fontTools.ttLib import newTable from fontTools import varLib from fontTools.varLib.models import allEqual from fontTools.misc.roundTools import roundFunc from fontTools.misc.psCharStrings import T2CharString, T2OutlineExtractor from fontTools.pens.t2CharStringPen import T2CharStringPen from functools import partial from .errors import ( VarLibCFFDictMergeError, VarLibCFFPointTypeMergeError, VarLibCFFHintTypeMergeError, VarLibMergeError, ) def addCFFVarStore(varFont, varModel, varDataList, masterSupports): fvarTable = varFont["fvar"] axisKeys = [axis.axisTag for axis in fvarTable.axes] varTupleList = varLib.builder.buildVarRegionList(masterSupports, axisKeys) varStoreCFFV = varLib.builder.buildVarStore(varTupleList, varDataList) topDict = varFont["CFF2"].cff.topDictIndex[0] topDict.VarStore = VarStoreData(otVarStore=varStoreCFFV) if topDict.FDArray[0].vstore is None: fdArray = topDict.FDArray for fontDict in fdArray: if hasattr(fontDict, "Private"): fontDict.Private.vstore = topDict.VarStore def merge_PrivateDicts(top_dicts, vsindex_dict, var_model, fd_map): """ I step through the FontDicts in the FDArray of the varfont TopDict. For each varfont FontDict: * step through each key in FontDict.Private. * For each key, step through each relevant source font Private dict, and build a list of values to blend. The 'relevant' source fonts are selected by first getting the right submodel using ``vsindex_dict[vsindex]``. The indices of the ``subModel.locations`` are mapped to source font list indices by assuming the latter order is the same as the order of the ``var_model.locations``. I can then get the index of each subModel location in the list of ``var_model.locations``. """ topDict = top_dicts[0] region_top_dicts = top_dicts[1:] if hasattr(region_top_dicts[0], "FDArray"): regionFDArrays = [fdTopDict.FDArray for fdTopDict in region_top_dicts] else: regionFDArrays = [[fdTopDict] for fdTopDict in region_top_dicts] for fd_index, font_dict in enumerate(topDict.FDArray): private_dict = font_dict.Private vsindex = getattr(private_dict, "vsindex", 0) # At the moment, no PrivateDict has a vsindex key, but let's support # how it should work. See comment at end of # merge_charstrings() - still need to optimize use of vsindex. sub_model, _ = vsindex_dict[vsindex] master_indices = [] for loc in sub_model.locations[1:]: i = var_model.locations.index(loc) - 1 master_indices.append(i) pds = [private_dict] last_pd = private_dict for ri in master_indices: pd = get_private(regionFDArrays, fd_index, ri, fd_map) # If the region font doesn't have this FontDict, just reference # the last one used. if pd is None: pd = last_pd else: last_pd = pd pds.append(pd) num_masters = len(pds) for key, value in private_dict.rawDict.items(): dataList = [] if key not in pd_blend_fields: continue if isinstance(value, list): try: values = [pd.rawDict[key] for pd in pds] except KeyError: print( "Warning: {key} in default font Private dict is " "missing from another font, and was " "discarded.".format(key=key) ) continue try: values = zip(*values) except IndexError: raise VarLibCFFDictMergeError(key, value, values) """ Row 0 contains the first value from each master. Convert each row from absolute values to relative values from the previous row. e.g for three masters, a list of values was: master 0 OtherBlues = [-217,-205] master 1 OtherBlues = [-234,-222] master 1 OtherBlues = [-188,-176] The call to zip() converts this to: [(-217, -234, -188), (-205, -222, -176)] and is converted finally to: OtherBlues = [[-217, 17.0, 46.0], [-205, 0.0, 0.0]] """ prev_val_list = [0] * num_masters any_points_differ = False for val_list in values: rel_list = [ (val - prev_val_list[i]) for (i, val) in enumerate(val_list) ] if (not any_points_differ) and not allEqual(rel_list): any_points_differ = True prev_val_list = val_list deltas = sub_model.getDeltas(rel_list) # For PrivateDict BlueValues, the default font # values are absolute, not relative to the prior value. deltas[0] = val_list[0] dataList.append(deltas) # If there are no blend values,then # we can collapse the blend lists. if not any_points_differ: dataList = [data[0] for data in dataList] else: values = [pd.rawDict[key] for pd in pds] if not allEqual(values): dataList = sub_model.getDeltas(values) else: dataList = values[0] # Convert numbers with no decimal part to an int if isinstance(dataList, list): for i, item in enumerate(dataList): if isinstance(item, list): for j, jtem in enumerate(item): dataList[i][j] = conv_to_int(jtem) else: dataList[i] = conv_to_int(item) else: dataList = conv_to_int(dataList) private_dict.rawDict[key] = dataList def _cff_or_cff2(font): if "CFF " in font: return font["CFF "] return font["CFF2"] def getfd_map(varFont, fonts_list): """Since a subset source font may have fewer FontDicts in their FDArray than the default font, we have to match up the FontDicts in the different fonts . We do this with the FDSelect array, and by assuming that the same glyph will reference matching FontDicts in each source font. We return a mapping from fdIndex in the default font to a dictionary which maps each master list index of each region font to the equivalent fdIndex in the region font.""" fd_map = {} default_font = fonts_list[0] region_fonts = fonts_list[1:] num_regions = len(region_fonts) topDict = _cff_or_cff2(default_font).cff.topDictIndex[0] if not hasattr(topDict, "FDSelect"): # All glyphs reference only one FontDict. # Map the FD index for regions to index 0. fd_map[0] = {ri: 0 for ri in range(num_regions)} return fd_map gname_mapping = {} default_fdSelect = topDict.FDSelect glyphOrder = default_font.getGlyphOrder() for gid, fdIndex in enumerate(default_fdSelect): gname_mapping[glyphOrder[gid]] = fdIndex if fdIndex not in fd_map: fd_map[fdIndex] = {} for ri, region_font in enumerate(region_fonts): region_glyphOrder = region_font.getGlyphOrder() region_topDict = _cff_or_cff2(region_font).cff.topDictIndex[0] if not hasattr(region_topDict, "FDSelect"): # All the glyphs share the same FontDict. Pick any glyph. default_fdIndex = gname_mapping[region_glyphOrder[0]] fd_map[default_fdIndex][ri] = 0 else: region_fdSelect = region_topDict.FDSelect for gid, fdIndex in enumerate(region_fdSelect): default_fdIndex = gname_mapping[region_glyphOrder[gid]] region_map = fd_map[default_fdIndex] if ri not in region_map: region_map[ri] = fdIndex return fd_map def merge_charstrings(glyphOrder, num_masters, top_dicts, masterModel): vsindex_dict = {} vsindex_by_key = {} varDataList = [] masterSupports = [] default_charstrings = top_dicts[0].CharStrings for gid, gname in enumerate(glyphOrder): all_cs = [_get_cs(td.CharStrings, gname) for td in top_dicts] if len([gs for gs in all_cs if gs is not None]) == 1: continue model, model_cs = masterModel.getSubModel(all_cs) # create the first pass CFF2 charstring, from # the default charstring. default_charstring = model_cs[0] var_pen = CFF2CharStringMergePen([], gname, num_masters, 0) # We need to override outlineExtractor because these # charstrings do have widths in the 'program'; we need to drop these # values rather than post assertion error for them. default_charstring.outlineExtractor = MergeOutlineExtractor default_charstring.draw(var_pen) # Add the coordinates from all the other regions to the # blend lists in the CFF2 charstring. region_cs = model_cs[1:] for region_idx, region_charstring in enumerate(region_cs, start=1): var_pen.restart(region_idx) region_charstring.outlineExtractor = MergeOutlineExtractor region_charstring.draw(var_pen) # Collapse each coordinate list to a blend operator and its args. new_cs = var_pen.getCharString( private=default_charstring.private, globalSubrs=default_charstring.globalSubrs, var_model=model, optimize=True, ) default_charstrings[gname] = new_cs if (not var_pen.seen_moveto) or ("blend" not in new_cs.program): # If this is not a marking glyph, or if there are no blend # arguments, then we can use vsindex 0. No need to # check if we need a new vsindex. continue # If the charstring required a new model, create # a VarData table to go with, and set vsindex. key = tuple(v is not None for v in all_cs) try: vsindex = vsindex_by_key[key] except KeyError: vsindex = _add_new_vsindex( model, key, masterSupports, vsindex_dict, vsindex_by_key, varDataList ) # We do not need to check for an existing new_cs.private.vsindex, # as we know it doesn't exist yet. if vsindex != 0: new_cs.program[:0] = [vsindex, "vsindex"] # If there is no variation in any of the charstrings, then vsindex_dict # never gets built. This could still be needed if there is variation # in the PrivatDict, so we will build the default data for vsindex = 0. if not vsindex_dict: key = (True,) * num_masters _add_new_vsindex( masterModel, key, masterSupports, vsindex_dict, vsindex_by_key, varDataList ) cvData = CVarData( varDataList=varDataList, masterSupports=masterSupports, vsindex_dict=vsindex_dict, ) # XXX To do: optimize use of vsindex between the PrivateDicts and # charstrings return cvData def merge_region_fonts(varFont, model, ordered_fonts_list, glyphOrder): topDict = varFont["CFF2"].cff.topDictIndex[0] top_dicts = [topDict] + [ _cff_or_cff2(ttFont).cff.topDictIndex[0] for ttFont in ordered_fonts_list[1:] ] num_masters = len(model.mapping) cvData = merge_charstrings(glyphOrder, num_masters, top_dicts, model) fd_map = getfd_map(varFont, ordered_fonts_list) merge_PrivateDicts(top_dicts, cvData.vsindex_dict, model, fd_map) addCFFVarStore(varFont, model, cvData.varDataList, cvData.masterSupports)
null
175,301
from fontTools.misc.roundTools import noRound, otRound from fontTools.ttLib.tables import otTables as ot from fontTools.varLib.models import supportScalar from fontTools.varLib.builder import ( buildVarRegionList, buildVarStore, buildVarRegion, buildVarData, ) from functools import partial from collections import defaultdict def _getLocationKey(loc): return tuple(sorted(loc.items(), key=lambda kv: kv[0]))
null
175,302
from fontTools.misc.roundTools import noRound, otRound from fontTools.ttLib.tables import otTables as ot from fontTools.varLib.models import supportScalar from fontTools.varLib.builder import ( buildVarRegionList, buildVarStore, buildVarRegion, buildVarData, ) from functools import partial from collections import defaultdict def VarData_addItem(self, deltas, *, round=round): deltas = [round(d) for d in deltas] countUs = self.VarRegionCount countThem = len(deltas) if countUs + 1 == countThem: deltas = tuple(deltas[1:]) else: assert countUs == countThem, (countUs, countThem) deltas = tuple(deltas) self.Item.append(list(deltas)) self.ItemCount = len(self.Item)
null
175,303
from fontTools.misc.roundTools import noRound, otRound from fontTools.ttLib.tables import otTables as ot from fontTools.varLib.models import supportScalar from fontTools.varLib.builder import ( buildVarRegionList, buildVarStore, buildVarRegion, buildVarData, ) from functools import partial from collections import defaultdict def VarRegion_get_support(self, fvar_axes): return { fvar_axes[i].axisTag: (reg.StartCoord, reg.PeakCoord, reg.EndCoord) for i, reg in enumerate(self.VarRegionAxis) if reg.PeakCoord != 0 }
null
175,304
from fontTools.misc.roundTools import noRound, otRound from fontTools.ttLib.tables import otTables as ot from fontTools.varLib.models import supportScalar from fontTools.varLib.builder import ( buildVarRegionList, buildVarStore, buildVarRegion, buildVarData, ) from functools import partial from collections import defaultdict def VarStore___bool__(self): return bool(self.VarData)
null
175,305
from fontTools.misc.roundTools import noRound, otRound from fontTools.ttLib.tables import otTables as ot from fontTools.varLib.models import supportScalar from fontTools.varLib.builder import ( buildVarRegionList, buildVarStore, buildVarRegion, buildVarData, ) from functools import partial from collections import defaultdict NO_VARIATION_INDEX = ot.NO_VARIATION_INDEX def VarStore_subset_varidxes( self, varIdxes, optimize=True, retainFirstMap=False, advIdxes=set() ): # Sort out used varIdxes by major/minor. used = {} for varIdx in varIdxes: if varIdx == NO_VARIATION_INDEX: continue major = varIdx >> 16 minor = varIdx & 0xFFFF d = used.get(major) if d is None: d = used[major] = set() d.add(minor) del varIdxes # # Subset VarData # varData = self.VarData newVarData = [] varDataMap = {NO_VARIATION_INDEX: NO_VARIATION_INDEX} for major, data in enumerate(varData): usedMinors = used.get(major) if usedMinors is None: continue newMajor = len(newVarData) newVarData.append(data) items = data.Item newItems = [] if major == 0 and retainFirstMap: for minor in range(len(items)): newItems.append( items[minor] if minor in usedMinors else [0] * len(items[minor]) ) varDataMap[minor] = minor else: if major == 0: minors = sorted(advIdxes) + sorted(usedMinors - advIdxes) else: minors = sorted(usedMinors) for minor in minors: newMinor = len(newItems) newItems.append(items[minor]) varDataMap[(major << 16) + minor] = (newMajor << 16) + newMinor data.Item = newItems data.ItemCount = len(data.Item) data.calculateNumShorts(optimize=optimize) self.VarData = newVarData self.VarDataCount = len(self.VarData) self.prune_regions() return varDataMap
null
175,306
from fontTools.misc.roundTools import noRound, otRound from fontTools.ttLib.tables import otTables as ot from fontTools.varLib.models import supportScalar from fontTools.varLib.builder import ( buildVarRegionList, buildVarStore, buildVarRegion, buildVarData, ) from functools import partial from collections import defaultdict The provided code snippet includes necessary dependencies for implementing the `VarStore_prune_regions` function. Write a Python function `def VarStore_prune_regions(self)` to solve the following problem: Remove unused VarRegions. Here is the function: def VarStore_prune_regions(self): """Remove unused VarRegions.""" # # Subset VarRegionList # # Collect. usedRegions = set() for data in self.VarData: usedRegions.update(data.VarRegionIndex) # Subset. regionList = self.VarRegionList regions = regionList.Region newRegions = [] regionMap = {} for i in sorted(usedRegions): regionMap[i] = len(newRegions) newRegions.append(regions[i]) regionList.Region = newRegions regionList.RegionCount = len(regionList.Region) # Map. for data in self.VarData: data.VarRegionIndex = [regionMap[i] for i in data.VarRegionIndex]
Remove unused VarRegions.
175,307
from fontTools.misc.roundTools import noRound, otRound from fontTools.ttLib.tables import otTables as ot from fontTools.varLib.models import supportScalar from fontTools.varLib.builder import ( buildVarRegionList, buildVarStore, buildVarRegion, buildVarData, ) from functools import partial from collections import defaultdict def _visit(self, func): """Recurse down from self, if type of an object is ot.Device, call func() on it. Works on otData-style classes.""" if type(self) == ot.Device: func(self) elif isinstance(self, list): for that in self: _visit(that, func) elif hasattr(self, "getConverters") and not hasattr(self, "postRead"): for conv in self.getConverters(): that = getattr(self, conv.name, None) if that is not None: _visit(that, func) elif isinstance(self, ot.ValueRecord): for that in self.__dict__.values(): _visit(that, func) def _Device_recordVarIdx(self, s): """Add VarIdx in this Device table (if any) to the set s.""" if self.DeltaFormat == 0x8000: s.add((self.StartSize << 16) + self.EndSize) class partial(Generic[_T]): func: Callable[..., _T] args: Tuple[Any, ...] keywords: Dict[str, Any] def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... def Object_collect_device_varidxes(self, varidxes): adder = partial(_Device_recordVarIdx, s=varidxes) _visit(self, adder)
null
175,308
from fontTools.misc.roundTools import noRound, otRound from fontTools.ttLib.tables import otTables as ot from fontTools.varLib.models import supportScalar from fontTools.varLib.builder import ( buildVarRegionList, buildVarStore, buildVarRegion, buildVarData, ) from functools import partial from collections import defaultdict def _visit(self, func): """Recurse down from self, if type of an object is ot.Device, call func() on it. Works on otData-style classes.""" if type(self) == ot.Device: func(self) elif isinstance(self, list): for that in self: _visit(that, func) elif hasattr(self, "getConverters") and not hasattr(self, "postRead"): for conv in self.getConverters(): that = getattr(self, conv.name, None) if that is not None: _visit(that, func) elif isinstance(self, ot.ValueRecord): for that in self.__dict__.values(): _visit(that, func) def _Device_mapVarIdx(self, mapping, done): """Map VarIdx in this Device table (if any) through mapping.""" if id(self) in done: return done.add(id(self)) if self.DeltaFormat == 0x8000: varIdx = mapping[(self.StartSize << 16) + self.EndSize] self.StartSize = varIdx >> 16 self.EndSize = varIdx & 0xFFFF class partial(Generic[_T]): func: Callable[..., _T] args: Tuple[Any, ...] keywords: Dict[str, Any] def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... def Object_remap_device_varidxes(self, varidxes_map): mapper = partial(_Device_mapVarIdx, mapping=varidxes_map, done=set()) _visit(self, mapper)
null
175,309
from fontTools.misc.roundTools import noRound, otRound from fontTools.ttLib.tables import otTables as ot from fontTools.varLib.models import supportScalar from fontTools.varLib.builder import ( buildVarRegionList, buildVarStore, buildVarRegion, buildVarData, ) from functools import partial from collections import defaultdict NO_VARIATION_INDEX = ot.NO_VARIATION_INDEX ot.VarStore.NO_VARIATION_INDEX = NO_VARIATION_INDEX ot.VarData.addItem = VarData_addItem ot.VarRegion.get_support = VarRegion_get_support ot.VarStore.__bool__ = VarStore___bool__ ot.VarStore.subset_varidxes = VarStore_subset_varidxes ot.VarStore.prune_regions = VarStore_prune_regions ot.GDEF.collect_device_varidxes = Object_collect_device_varidxes ot.GPOS.collect_device_varidxes = Object_collect_device_varidxes ot.GDEF.remap_device_varidxes = Object_remap_device_varidxes ot.GPOS.remap_device_varidxes = Object_remap_device_varidxes class _Encoding(object): def __init__(self, chars): self.chars = chars self.width = self._popcount(chars) self.overhead = self._characteristic_overhead(chars) self.items = set() def append(self, row): self.items.add(row) def extend(self, lst): self.items.update(lst) def get_room(self): """Maximum number of bytes that can be added to characteristic while still being beneficial to merge it into another one.""" count = len(self.items) return max(0, (self.overhead - 1) // count - self.width) room = property(get_room) def gain(self): """Maximum possible byte gain from merging this into another characteristic.""" count = len(self.items) return max(0, self.overhead - count * (self.width + 1)) def sort_key(self): return self.width, self.chars def __len__(self): return len(self.items) def can_encode(self, chars): return not (chars & ~self.chars) def __sub__(self, other): return self._popcount(self.chars & ~other.chars) def _popcount(n): # Apparently this is the fastest native way to do it... # https://stackoverflow.com/a/9831671 return bin(n).count("1") def _characteristic_overhead(chars): """Returns overhead in bytes of encoding this characteristic as a VarData.""" c = 6 while chars: if chars & 0b1111: c += 2 chars >>= 4 return c def _find_yourself_best_new_encoding(self, done_by_width): self.best_new_encoding = None for new_width in range(self.width + 1, self.width + self.room + 1): for new_encoding in done_by_width[new_width]: if new_encoding.can_encode(self.chars): break else: new_encoding = None self.best_new_encoding = new_encoding class _EncodingDict(dict): def __missing__(self, chars): r = self[chars] = _Encoding(chars) return r def add_row(self, row): chars = self._row_characteristics(row) self[chars].append(row) def _row_characteristics(row): """Returns encoding characteristics for a row.""" longWords = False chars = 0 i = 1 for v in row: if v: chars += i if not (-128 <= v <= 127): chars += i * 0b0010 if not (-32768 <= v <= 32767): longWords = True break i <<= 4 if longWords: # Redo; only allow 2byte/4byte encoding chars = 0 i = 1 for v in row: if v: chars += i * 0b0011 if not (-32768 <= v <= 32767): chars += i * 0b1100 i <<= 4 return chars ot.VarStore.optimize = VarStore_optimize class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): default_factory: Callable[[], _VT] def __init__(self, **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... def __init__( self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT ) -> None: ... def __missing__(self, key: _KT) -> _VT: ... def copy(self: _S) -> _S: ... The provided code snippet includes necessary dependencies for implementing the `VarStore_optimize` function. Write a Python function `def VarStore_optimize(self, use_NO_VARIATION_INDEX=True)` to solve the following problem: Optimize storage. Returns mapping from old VarIdxes to new ones. Here is the function: def VarStore_optimize(self, use_NO_VARIATION_INDEX=True): """Optimize storage. Returns mapping from old VarIdxes to new ones.""" # TODO # Check that no two VarRegions are the same; if they are, fold them. n = len(self.VarRegionList.Region) # Number of columns zeroes = [0] * n front_mapping = {} # Map from old VarIdxes to full row tuples encodings = _EncodingDict() # Collect all items into a set of full rows (with lots of zeroes.) for major, data in enumerate(self.VarData): regionIndices = data.VarRegionIndex for minor, item in enumerate(data.Item): row = list(zeroes) for regionIdx, v in zip(regionIndices, item): row[regionIdx] += v row = tuple(row) if use_NO_VARIATION_INDEX and not any(row): front_mapping[(major << 16) + minor] = None continue encodings.add_row(row) front_mapping[(major << 16) + minor] = row # Separate encodings that have no gain (are decided) and those having # possible gain (possibly to be merged into others.) encodings = sorted(encodings.values(), key=_Encoding.__len__, reverse=True) done_by_width = defaultdict(list) todo = [] for encoding in encodings: if not encoding.gain: done_by_width[encoding.width].append(encoding) else: todo.append(encoding) # For each encoding that is possibly to be merged, find the best match # in the decided encodings, and record that. todo.sort(key=_Encoding.get_room) for encoding in todo: encoding._find_yourself_best_new_encoding(done_by_width) # Walk through todo encodings, for each, see if merging it with # another todo encoding gains more than each of them merging with # their best decided encoding. If yes, merge them and add resulting # encoding back to todo queue. If not, move the enconding to decided # list. Repeat till done. while todo: encoding = todo.pop() best_idx = None best_gain = 0 for i, other_encoding in enumerate(todo): combined_chars = other_encoding.chars | encoding.chars combined_width = _Encoding._popcount(combined_chars) combined_overhead = _Encoding._characteristic_overhead(combined_chars) combined_gain = ( +encoding.overhead + other_encoding.overhead - combined_overhead - (combined_width - encoding.width) * len(encoding) - (combined_width - other_encoding.width) * len(other_encoding) ) this_gain = ( 0 if encoding.best_new_encoding is None else ( +encoding.overhead - (encoding.best_new_encoding.width - encoding.width) * len(encoding) ) ) other_gain = ( 0 if other_encoding.best_new_encoding is None else ( +other_encoding.overhead - (other_encoding.best_new_encoding.width - other_encoding.width) * len(other_encoding) ) ) separate_gain = this_gain + other_gain if combined_gain > separate_gain: best_idx = i best_gain = combined_gain - separate_gain if best_idx is None: # Encoding is decided as is done_by_width[encoding.width].append(encoding) else: other_encoding = todo[best_idx] combined_chars = other_encoding.chars | encoding.chars combined_encoding = _Encoding(combined_chars) combined_encoding.extend(encoding.items) combined_encoding.extend(other_encoding.items) combined_encoding._find_yourself_best_new_encoding(done_by_width) del todo[best_idx] todo.append(combined_encoding) # Assemble final store. back_mapping = {} # Mapping from full rows to new VarIdxes encodings = sum(done_by_width.values(), []) encodings.sort(key=_Encoding.sort_key) self.VarData = [] for major, encoding in enumerate(encodings): data = ot.VarData() self.VarData.append(data) data.VarRegionIndex = range(n) data.VarRegionCount = len(data.VarRegionIndex) data.Item = sorted(encoding.items) for minor, item in enumerate(data.Item): back_mapping[item] = (major << 16) + minor # Compile final mapping. varidx_map = {NO_VARIATION_INDEX: NO_VARIATION_INDEX} for k, v in front_mapping.items(): varidx_map[k] = back_mapping[v] if v is not None else NO_VARIATION_INDEX # Remove unused regions. self.prune_regions() # Recalculate things and go home. self.VarRegionList.RegionCount = len(self.VarRegionList.Region) self.VarDataCount = len(self.VarData) for data in self.VarData: data.ItemCount = len(data.Item) data.optimize() return varidx_map
Optimize storage. Returns mapping from old VarIdxes to new ones.
175,310
from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot def buildVarRegion(support, axisTags): ot.VarData.calculateNumShorts = VarData_calculateNumShorts ot.VarData.optimize = VarData_optimize def buildVarRegionList(supports, axisTags): self = ot.VarRegionList() self.RegionAxisCount = len(axisTags) self.Region = [] for support in supports: self.Region.append(buildVarRegion(support, axisTags)) self.RegionCount = len(self.Region) return self
null
175,311
from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot def VarData_calculateNumShorts(self, optimize=False): count = self.VarRegionCount items = self.Item bit_lengths = [0] * count for item in items: # The "+ (i < -1)" magic is to handle two's-compliment. # That is, we want to get back 7 for -128, whereas # bit_length() returns 8. Similarly for -65536. # The reason "i < -1" is used instead of "i < 0" is that # the latter would make it return 0 for "-1" instead of 1. bl = [(i + (i < -1)).bit_length() for i in item] bit_lengths = [max(*pair) for pair in zip(bl, bit_lengths)] # The addition of 8, instead of seven, is to account for the sign bit. # This "((b + 8) >> 3) if b else 0" when combined with the above # "(i + (i < -1)).bit_length()" is a faster way to compute byte-lengths # conforming to: # # byte_length = (0 if i == 0 else # 1 if -128 <= i < 128 else # 2 if -65536 <= i < 65536 else # ...) byte_lengths = [((b + 8) >> 3) if b else 0 for b in bit_lengths] # https://github.com/fonttools/fonttools/issues/2279 longWords = any(b > 2 for b in byte_lengths) if optimize: # Reorder columns such that wider columns come before narrower columns mapping = [] mapping.extend(i for i, b in enumerate(byte_lengths) if b > 2) mapping.extend(i for i, b in enumerate(byte_lengths) if b == 2) mapping.extend(i for i, b in enumerate(byte_lengths) if b == 1) byte_lengths = _reorderItem(byte_lengths, mapping) self.VarRegionIndex = _reorderItem(self.VarRegionIndex, mapping) self.VarRegionCount = len(self.VarRegionIndex) for i in range(len(items)): items[i] = _reorderItem(items[i], mapping) if longWords: self.NumShorts = ( max((i for i, b in enumerate(byte_lengths) if b > 2), default=-1) + 1 ) self.NumShorts |= 0x8000 else: self.NumShorts = ( max((i for i, b in enumerate(byte_lengths) if b > 1), default=-1) + 1 ) self.VarRegionCount = len(self.VarRegionIndex) return self The provided code snippet includes necessary dependencies for implementing the `VarData_CalculateNumShorts` function. Write a Python function `def VarData_CalculateNumShorts(self, optimize=True)` to solve the following problem: Deprecated name for VarData_calculateNumShorts() which defaults to optimize=True. Use varData.calculateNumShorts() or varData.optimize(). Here is the function: def VarData_CalculateNumShorts(self, optimize=True): """Deprecated name for VarData_calculateNumShorts() which defaults to optimize=True. Use varData.calculateNumShorts() or varData.optimize().""" return VarData_calculateNumShorts(self, optimize=optimize)
Deprecated name for VarData_calculateNumShorts() which defaults to optimize=True. Use varData.calculateNumShorts() or varData.optimize().
175,312
from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot def VarData_calculateNumShorts(self, optimize=False): count = self.VarRegionCount items = self.Item bit_lengths = [0] * count for item in items: # The "+ (i < -1)" magic is to handle two's-compliment. # That is, we want to get back 7 for -128, whereas # bit_length() returns 8. Similarly for -65536. # The reason "i < -1" is used instead of "i < 0" is that # the latter would make it return 0 for "-1" instead of 1. bl = [(i + (i < -1)).bit_length() for i in item] bit_lengths = [max(*pair) for pair in zip(bl, bit_lengths)] # The addition of 8, instead of seven, is to account for the sign bit. # This "((b + 8) >> 3) if b else 0" when combined with the above # "(i + (i < -1)).bit_length()" is a faster way to compute byte-lengths # conforming to: # # byte_length = (0 if i == 0 else # 1 if -128 <= i < 128 else # 2 if -65536 <= i < 65536 else # ...) byte_lengths = [((b + 8) >> 3) if b else 0 for b in bit_lengths] # https://github.com/fonttools/fonttools/issues/2279 longWords = any(b > 2 for b in byte_lengths) if optimize: # Reorder columns such that wider columns come before narrower columns mapping = [] mapping.extend(i for i, b in enumerate(byte_lengths) if b > 2) mapping.extend(i for i, b in enumerate(byte_lengths) if b == 2) mapping.extend(i for i, b in enumerate(byte_lengths) if b == 1) byte_lengths = _reorderItem(byte_lengths, mapping) self.VarRegionIndex = _reorderItem(self.VarRegionIndex, mapping) self.VarRegionCount = len(self.VarRegionIndex) for i in range(len(items)): items[i] = _reorderItem(items[i], mapping) if longWords: self.NumShorts = ( max((i for i, b in enumerate(byte_lengths) if b > 2), default=-1) + 1 ) self.NumShorts |= 0x8000 else: self.NumShorts = ( max((i for i, b in enumerate(byte_lengths) if b > 1), default=-1) + 1 ) self.VarRegionCount = len(self.VarRegionIndex) return self def VarData_optimize(self): return VarData_calculateNumShorts(self, optimize=True)
null
175,313
from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot ot.VarData.calculateNumShorts = VarData_calculateNumShorts ot.VarData.optimize = VarData_optimize def buildVarData(varRegionIndices, items, optimize=True): self = ot.VarData() self.VarRegionIndex = list(varRegionIndices) regionCount = self.VarRegionCount = len(self.VarRegionIndex) records = self.Item = [] if items: for item in items: assert len(item) == regionCount records.append(list(item)) self.ItemCount = len(self.Item) self.calculateNumShorts(optimize=optimize) return self
null
175,314
from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot ot.VarData.calculateNumShorts = VarData_calculateNumShorts ot.VarData.optimize = VarData_optimize def buildVarStore(varRegionList, varDataList): self = ot.VarStore() self.Format = 1 self.VarRegionList = varRegionList self.VarData = list(varDataList) self.VarDataCount = len(self.VarData) return self
null
175,315
from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot ot.VarData.calculateNumShorts = VarData_calculateNumShorts ot.VarData.optimize = VarData_optimize def buildVarIdxMap(varIdxes, glyphOrder): self = ot.VarIdxMap() self.mapping = {g: v for g, v in zip(glyphOrder, varIdxes)} return self
null
175,316
from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot ot.VarData.calculateNumShorts = VarData_calculateNumShorts ot.VarData.optimize = VarData_optimize def buildDeltaSetIndexMap(varIdxes): self = ot.DeltaSetIndexMap() self.mapping = list(varIdxes) self.Format = 1 if len(varIdxes) > 0xFFFF else 0 return self
null
175,317
from fontTools.varLib.models import VariationModel, supportScalar from fontTools.designspaceLib import DesignSpaceDocument from matplotlib import pyplot from mpl_toolkits.mplot3d import axes3d from itertools import cycle import math import logging import sys def plotLocations(locations, fig, names=None, **kwargs): n = len(locations) cols = math.ceil(n**0.5) rows = math.ceil(n / cols) if names is None: names = [None] * len(locations) model = VariationModel(locations) names = [names[model.reverseMapping[i]] for i in range(len(names))] axes = sorted(locations[0].keys()) if len(axes) == 1: _plotLocations2D(model, axes[0], fig, cols, rows, names=names, **kwargs) elif len(axes) == 2: _plotLocations3D(model, axes, fig, cols, rows, names=names, **kwargs) else: raise ValueError("Only 1 or 2 axes are supported") def plotDocument(doc, fig, **kwargs): doc.normalize() locations = [s.location for s in doc.sources] names = [s.name for s in doc.sources] plotLocations(locations, fig, names, **kwargs)
null
175,318
from fontTools.varLib.models import VariationModel, supportScalar from fontTools.designspaceLib import DesignSpaceDocument from matplotlib import pyplot from mpl_toolkits.mplot3d import axes3d from itertools import cycle import math import logging import sys def _plotModelFromMasters2D(model, masterValues, fig, **kwargs): assert len(model.axisOrder) == 1 axis = model.axisOrder[0] axis_min = min(loc.get(axis, 0) for loc in model.locations) axis_max = max(loc.get(axis, 0) for loc in model.locations) import numpy as np X = np.arange(axis_min, axis_max, (axis_max - axis_min) / 100) Y = [] for x in X: loc = {axis: x} v = model.interpolateFromMasters(loc, masterValues) Y.append(v) subplot = fig.add_subplot(111) subplot.plot(X, Y, "-", **kwargs) def _plotModelFromMasters3D(model, masterValues, fig, **kwargs): assert len(model.axisOrder) == 2 axis1, axis2 = model.axisOrder[0], model.axisOrder[1] axis1_min = min(loc.get(axis1, 0) for loc in model.locations) axis1_max = max(loc.get(axis1, 0) for loc in model.locations) axis2_min = min(loc.get(axis2, 0) for loc in model.locations) axis2_max = max(loc.get(axis2, 0) for loc in model.locations) import numpy as np X = np.arange(axis1_min, axis1_max, (axis1_max - axis1_min) / 100) Y = np.arange(axis2_min, axis2_max, (axis2_max - axis2_min) / 100) X, Y = np.meshgrid(X, Y) Z = [] for row_x, row_y in zip(X, Y): z_row = [] Z.append(z_row) for x, y in zip(row_x, row_y): loc = {axis1: x, axis2: y} v = model.interpolateFromMasters(loc, masterValues) z_row.append(v) Z = np.array(Z) axis3D = fig.add_subplot(111, projection="3d") axis3D.plot_surface(X, Y, Z, **kwargs) The provided code snippet includes necessary dependencies for implementing the `plotModelFromMasters` function. Write a Python function `def plotModelFromMasters(model, masterValues, fig, **kwargs)` to solve the following problem: Plot a variation model and set of master values corresponding to the locations to the model into a pyplot figure. Variation model must have axisOrder of size 1 or 2. Here is the function: def plotModelFromMasters(model, masterValues, fig, **kwargs): """Plot a variation model and set of master values corresponding to the locations to the model into a pyplot figure. Variation model must have axisOrder of size 1 or 2.""" if len(model.axisOrder) == 1: _plotModelFromMasters2D(model, masterValues, fig, **kwargs) elif len(model.axisOrder) == 2: _plotModelFromMasters3D(model, masterValues, fig, **kwargs) else: raise ValueError("Only 1 or 2 axes are supported")
Plot a variation model and set of master values corresponding to the locations to the model into a pyplot figure. Variation model must have axisOrder of size 1 or 2.
175,319
from fontTools.merge.unicode import is_Default_Ignorable from fontTools.pens.recordingPen import DecomposingRecordingPen import logging The provided code snippet includes necessary dependencies for implementing the `computeMegaGlyphOrder` function. Write a Python function `def computeMegaGlyphOrder(merger, glyphOrders)` to solve the following problem: Modifies passed-in glyphOrders to reflect new glyph names. Stores merger.glyphOrder. Here is the function: def computeMegaGlyphOrder(merger, glyphOrders): """Modifies passed-in glyphOrders to reflect new glyph names. Stores merger.glyphOrder.""" megaOrder = {} for glyphOrder in glyphOrders: for i, glyphName in enumerate(glyphOrder): if glyphName in megaOrder: n = megaOrder[glyphName] while (glyphName + "." + repr(n)) in megaOrder: n += 1 megaOrder[glyphName] = n glyphName += "." + repr(n) glyphOrder[i] = glyphName megaOrder[glyphName] = 1 merger.glyphOrder = megaOrder = list(megaOrder.keys())
Modifies passed-in glyphOrders to reflect new glyph names. Stores merger.glyphOrder.
175,320
from fontTools.merge.unicode import is_Default_Ignorable from fontTools.pens.recordingPen import DecomposingRecordingPen import logging class DecomposingRecordingPen(DecomposingPen, RecordingPen): """Same as RecordingPen, except that it doesn't keep components as references, but draws them decomposed as regular contours. The constructor takes a single 'glyphSet' positional argument, a dictionary of glyph objects (i.e. with a 'draw' method) keyed by thir name:: >>> class SimpleGlyph(object): ... def draw(self, pen): ... pen.moveTo((0, 0)) ... pen.curveTo((1, 1), (2, 2), (3, 3)) ... pen.closePath() >>> class CompositeGlyph(object): ... def draw(self, pen): ... pen.addComponent('a', (1, 0, 0, 1, -1, 1)) >>> glyphSet = {'a': SimpleGlyph(), 'b': CompositeGlyph()} >>> for name, glyph in sorted(glyphSet.items()): ... pen = DecomposingRecordingPen(glyphSet) ... glyph.draw(pen) ... print("{}: {}".format(name, pen.value)) a: [('moveTo', ((0, 0),)), ('curveTo', ((1, 1), (2, 2), (3, 3))), ('closePath', ())] b: [('moveTo', ((-1, 1),)), ('curveTo', ((0, 2), (1, 3), (2, 4))), ('closePath', ())] """ # raises KeyError if base glyph is not found in glyphSet skipMissingComponents = False def _glyphsAreSame( glyphSet1, glyphSet2, glyph1, glyph2, advanceTolerance=0.05, advanceToleranceEmpty=0.20, ): pen1 = DecomposingRecordingPen(glyphSet1) pen2 = DecomposingRecordingPen(glyphSet2) g1 = glyphSet1[glyph1] g2 = glyphSet2[glyph2] g1.draw(pen1) g2.draw(pen2) if pen1.value != pen2.value: return False # Allow more width tolerance for glyphs with no ink tolerance = advanceTolerance if pen1.value else advanceToleranceEmpty # TODO Warn if advances not the same but within tolerance. if abs(g1.width - g2.width) > g1.width * tolerance: return False if hasattr(g1, "height") and g1.height is not None: if abs(g1.height - g2.height) > g1.height * tolerance: return False return True
null
175,321
from fontTools.merge.unicode import is_Default_Ignorable from fontTools.pens.recordingPen import DecomposingRecordingPen import logging The provided code snippet includes necessary dependencies for implementing the `renameCFFCharStrings` function. Write a Python function `def renameCFFCharStrings(merger, glyphOrder, cffTable)` to solve the following problem: Rename topDictIndex charStrings based on glyphOrder. Here is the function: def renameCFFCharStrings(merger, glyphOrder, cffTable): """Rename topDictIndex charStrings based on glyphOrder.""" td = cffTable.cff.topDictIndex[0] charStrings = {} for i, v in enumerate(td.CharStrings.charStrings.values()): glyphName = glyphOrder[i] charStrings[glyphName] = v td.CharStrings.charStrings = charStrings td.charset = list(glyphOrder)
Rename topDictIndex charStrings based on glyphOrder.
175,322
from fontTools.misc.timeTools import timestampNow from fontTools.ttLib.tables.DefaultTable import DefaultTable from functools import reduce import operator import logging def first(lst): return next(iter(lst)) def equal(lst): lst = list(lst) t = iter(lst) first = next(t) assert all(item == first for item in t), "Expected all items to be equal: %s" % lst return first
null
175,323
from fontTools.misc.timeTools import timestampNow from fontTools.ttLib.tables.DefaultTable import DefaultTable from functools import reduce import operator import logging def recalculate(lst): return NotImplemented
null
175,324
from fontTools.misc.timeTools import timestampNow from fontTools.ttLib.tables.DefaultTable import DefaultTable from functools import reduce import operator import logging def timestampNow(): # https://reproducible-builds.org/specs/source-date-epoch/ source_date_epoch = os.environ.get("SOURCE_DATE_EPOCH") if source_date_epoch is not None: return int(source_date_epoch) - epoch_diff return int(time.time() - epoch_diff) def current_time(lst): return timestampNow()
null
175,325
from fontTools.misc.timeTools import timestampNow from fontTools.ttLib.tables.DefaultTable import DefaultTable from functools import reduce import operator import logging def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... def bitwise_and(lst): return reduce(operator.and_, lst)
null
175,326
from fontTools.misc.timeTools import timestampNow from fontTools.ttLib.tables.DefaultTable import DefaultTable from functools import reduce import operator import logging def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... def bitwise_or(lst): return reduce(operator.or_, lst)
null
175,327
from fontTools.misc.timeTools import timestampNow from fontTools.ttLib.tables.DefaultTable import DefaultTable from functools import reduce import operator import logging def avg_int(lst): lst = list(lst) return sum(lst) // len(lst)
null
175,328
from fontTools.misc.timeTools import timestampNow from fontTools.ttLib.tables.DefaultTable import DefaultTable from functools import reduce import operator import logging The provided code snippet includes necessary dependencies for implementing the `onlyExisting` function. Write a Python function `def onlyExisting(func)` to solve the following problem: Returns a filter func that when called with a list, only calls func on the non-NotImplemented items of the list, and only so if there's at least one item remaining. Otherwise returns NotImplemented. Here is the function: def onlyExisting(func): """Returns a filter func that when called with a list, only calls func on the non-NotImplemented items of the list, and only so if there's at least one item remaining. Otherwise returns NotImplemented.""" def wrapper(lst): items = [item for item in lst if item is not NotImplemented] return func(items) if items else NotImplemented return wrapper
Returns a filter func that when called with a list, only calls func on the non-NotImplemented items of the list, and only so if there's at least one item remaining. Otherwise returns NotImplemented.
175,329
from fontTools.misc.timeTools import timestampNow from fontTools.ttLib.tables.DefaultTable import DefaultTable from functools import reduce import operator import logging def sumLists(lst): l = [] for item in lst: l.extend(item) return l
null
175,330
from fontTools.misc.timeTools import timestampNow from fontTools.ttLib.tables.DefaultTable import DefaultTable from functools import reduce import operator import logging def sumDicts(lst): d = {} for item in lst: d.update(item) return d
null
175,331
from fontTools.misc.timeTools import timestampNow from fontTools.ttLib.tables.DefaultTable import DefaultTable from functools import reduce import operator import logging def mergeBits(bitmap): def wrapper(lst): lst = list(lst) returnValue = 0 for bitNumber in range(bitmap["size"]): try: mergeLogic = bitmap[bitNumber] except KeyError: try: mergeLogic = bitmap["*"] except KeyError: raise Exception("Don't know how to merge bit %s" % bitNumber) shiftedBit = 1 << bitNumber mergedValue = mergeLogic(bool(item & shiftedBit) for item in lst) returnValue |= mergedValue << bitNumber return returnValue return wrapper
null
175,332
from fontTools import ttLib, cffLib from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.merge.base import add_method, mergeObjects from fontTools.merge.cmap import computeMegaCmap from fontTools.merge.util import * import logging os2FsTypeMergeBitMap = { "size": 16, "*": lambda bit: 0, 1: bitwise_or, # no embedding permitted 2: bitwise_and, # allow previewing and printing documents 3: bitwise_and, # allow editing documents 8: bitwise_or, # no subsetting permitted 9: bitwise_or, # no embedding of outlines permitted } def mergeOs2FsType(lst): lst = list(lst) if all(item == 0 for item in lst): return 0 # Compute least restrictive logic for each fsType value for i in range(len(lst)): # unset bit 1 (no embedding permitted) if either bit 2 or 3 is set if lst[i] & 0x000C: lst[i] &= ~0x0002 # set bit 2 (allow previewing) if bit 3 is set (allow editing) elif lst[i] & 0x0008: lst[i] |= 0x0004 # set bits 2 and 3 if everything is allowed elif lst[i] == 0: lst[i] = 0x000C fsType = mergeBits(os2FsTypeMergeBitMap)(lst) # unset bits 2 and 3 if bit 1 is set (some font is "no embedding") if fsType & 0x0002: fsType &= ~0x000C return fsType
null
175,333
from fontTools import ttLib, cffLib from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.merge.base import add_method, mergeObjects from fontTools.merge.cmap import computeMegaCmap from fontTools.merge.util import * import logging class DefaultTable(object): def __init__(self, tag=None): def decompile(self, data, ttFont): def compile(self, ttFont): def toXML(self, writer, ttFont, **kwargs): def fromXML(self, name, attrs, content, ttFont): def __repr__(self): def __eq__(self, other): def __ne__(self, other): def merge(self, m, tables): DefaultTable.merge(self, m, tables) if self.version < 2: # bits 8 and 9 are reserved and should be set to zero self.fsType &= ~0x0300 if self.version >= 3: # Only one of bits 1, 2, and 3 may be set. We already take # care of bit 1 implications in mergeOs2FsType. So unset # bit 2 if bit 3 is already set. if self.fsType & 0x0008: self.fsType &= ~0x0004 return self
null
175,334
from fontTools import ttLib, cffLib from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.merge.base import add_method, mergeObjects from fontTools.merge.cmap import computeMegaCmap from fontTools.merge.util import * import logging class DefaultTable(object): dependencies = [] def __init__(self, tag=None): if tag is None: tag = getClassTag(self.__class__) self.tableTag = Tag(tag) def decompile(self, data, ttFont): self.data = data def compile(self, ttFont): return self.data def toXML(self, writer, ttFont, **kwargs): if hasattr(self, "ERROR"): writer.comment("An error occurred during the decompilation of this table") writer.newline() writer.comment(self.ERROR) writer.newline() writer.begintag("hexdata") writer.newline() writer.dumphex(self.compile(ttFont)) writer.endtag("hexdata") writer.newline() def fromXML(self, name, attrs, content, ttFont): from fontTools.misc.textTools import readHex from fontTools import ttLib if name != "hexdata": raise ttLib.TTLibError("can't handle '%s' element" % name) self.decompile(readHex(content), ttFont) def __repr__(self): return "<'%s' table at %x>" % (self.tableTag, id(self)) def __eq__(self, other): if type(self) != type(other): return NotImplemented return self.__dict__ == other.__dict__ def __ne__(self, other): result = self.__eq__(other) return result if result is NotImplemented else not result def merge(self, m, tables): for i, table in enumerate(tables): for g in table.glyphs.values(): if i: # Drop hints for all but first font, since # we don't map functions / CVT values. g.removeHinting() # Expand composite glyphs to load their # composite glyph names. if g.isComposite() or g.isVarComposite(): g.expand(table) return DefaultTable.merge(self, m, tables)
null
175,335
from fontTools import ttLib, cffLib from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.merge.base import add_method, mergeObjects from fontTools.merge.cmap import computeMegaCmap from fontTools.merge.util import * import logging log = logging.getLogger("fontTools.merge") def merge(self, m, tables): if any(hasattr(table, "FDSelect") for table in tables): raise NotImplementedError("Merging CID-keyed CFF tables is not supported yet") for table in tables: table.cff.desubroutinize() newcff = tables[0] newfont = newcff.cff[0] private = newfont.Private storedNamesStrings = [] glyphOrderStrings = [] glyphOrder = set(newfont.getGlyphOrder()) for name in newfont.strings.strings: if name not in glyphOrder: storedNamesStrings.append(name) else: glyphOrderStrings.append(name) chrset = list(newfont.charset) newcs = newfont.CharStrings log.debug("FONT 0 CharStrings: %d.", len(newcs)) for i, table in enumerate(tables[1:], start=1): font = table.cff[0] font.Private = private fontGlyphOrder = set(font.getGlyphOrder()) for name in font.strings.strings: if name in fontGlyphOrder: glyphOrderStrings.append(name) cs = font.CharStrings gs = table.cff.GlobalSubrs log.debug("Font %d CharStrings: %d.", i, len(cs)) chrset.extend(font.charset) if newcs.charStringsAreIndexed: for i, name in enumerate(cs.charStrings, start=len(newcs)): newcs.charStrings[name] = i newcs.charStringsIndex.items.append(None) for name in cs.charStrings: newcs[name] = cs[name] newfont.charset = chrset newfont.numGlyphs = len(chrset) newfont.strings.strings = glyphOrderStrings + storedNamesStrings return newcff
null
175,336
from fontTools import ttLib, cffLib from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.merge.base import add_method, mergeObjects from fontTools.merge.cmap import computeMegaCmap from fontTools.merge.util import * import logging ttLib.getTableClass("maxp").mergeMap = { "*": max, "tableTag": equal, "tableVersion": equal, "numGlyphs": sum, "maxStorage": first, "maxFunctionDefs": first, "maxInstructionDefs": first, # TODO When we correctly merge hinting data, update these values: # maxFunctionDefs, maxInstructionDefs, maxSizeOfInstructions } ttLib.getTableClass("head").mergeMap = { "tableTag": equal, "tableVersion": max, "fontRevision": max, "checkSumAdjustment": lambda lst: 0, # We need *something* here "magicNumber": equal, "flags": mergeBits(headFlagsMergeBitMap), "unitsPerEm": equal, "created": current_time, "modified": current_time, "xMin": min, "yMin": min, "xMax": max, "yMax": max, "macStyle": first, "lowestRecPPEM": max, "fontDirectionHint": lambda lst: 2, "indexToLocFormat": first, "glyphDataFormat": equal, } ttLib.getTableClass("hhea").mergeMap = { "*": equal, "tableTag": equal, "tableVersion": max, "ascent": max, "descent": min, "lineGap": max, "advanceWidthMax": max, "minLeftSideBearing": min, "minRightSideBearing": min, "xMaxExtent": max, "caretSlopeRise": first, "caretSlopeRun": first, "caretOffset": first, "numberOfHMetrics": recalculate, } ttLib.getTableClass("vhea").mergeMap = { "*": equal, "tableTag": equal, "tableVersion": max, "ascent": max, "descent": min, "lineGap": max, "advanceHeightMax": max, "minTopSideBearing": min, "minBottomSideBearing": min, "yMaxExtent": max, "caretSlopeRise": first, "caretSlopeRun": first, "caretOffset": first, "numberOfVMetrics": recalculate, } ttLib.getTableClass("OS/2").mergeMap = { "*": first, "tableTag": equal, "version": max, "xAvgCharWidth": first, # Will be recalculated at the end on the merged font "fsType": mergeOs2FsType, # Will be overwritten "panose": first, # FIXME: should really be the first Latin font "ulUnicodeRange1": bitwise_or, "ulUnicodeRange2": bitwise_or, "ulUnicodeRange3": bitwise_or, "ulUnicodeRange4": bitwise_or, "fsFirstCharIndex": min, "fsLastCharIndex": max, "sTypoAscender": max, "sTypoDescender": min, "sTypoLineGap": max, "usWinAscent": max, "usWinDescent": max, # Version 1 "ulCodePageRange1": onlyExisting(bitwise_or), "ulCodePageRange2": onlyExisting(bitwise_or), # Version 2, 3, 4 "sxHeight": onlyExisting(max), "sCapHeight": onlyExisting(max), "usDefaultChar": onlyExisting(first), "usBreakChar": onlyExisting(first), "usMaxContext": onlyExisting(max), # version 5 "usLowerOpticalPointSize": onlyExisting(min), "usUpperOpticalPointSize": onlyExisting(max), } ttLib.getTableClass("post").mergeMap = { "*": first, "tableTag": equal, "formatType": max, "isFixedPitch": min, "minMemType42": max, "maxMemType42": lambda lst: 0, "minMemType1": max, "maxMemType1": lambda lst: 0, "mapping": onlyExisting(sumDicts), "extraNames": lambda lst: [], } ttLib.getTableClass("vmtx").mergeMap = ttLib.getTableClass("hmtx").mergeMap = { "tableTag": equal, "metrics": sumDicts, } ttLib.getTableClass("name").mergeMap = { "tableTag": equal, "names": first, # FIXME? Does mixing name records make sense? } ttLib.getTableClass("loca").mergeMap = { "*": recalculate, "tableTag": equal, } ttLib.getTableClass("glyf").mergeMap = { "tableTag": equal, "glyphs": sumDicts, "glyphOrder": sumLists, "axisTags": equal, } ttLib.getTableClass("prep").mergeMap = lambda self, lst: first(lst) ttLib.getTableClass("fpgm").mergeMap = lambda self, lst: first(lst) ttLib.getTableClass("cvt ").mergeMap = lambda self, lst: first(lst) ttLib.getTableClass("gasp").mergeMap = lambda self, lst: first( lst ) def computeMegaCmap(merger, cmapTables): def merge(self, m, tables): # TODO Handle format=14. if not hasattr(m, "cmap"): computeMegaCmap(m, tables) cmap = m.cmap cmapBmpOnly = {uni: gid for uni, gid in cmap.items() if uni <= 0xFFFF} self.tables = [] module = ttLib.getTableModule("cmap") if len(cmapBmpOnly) != len(cmap): # format-12 required. cmapTable = module.cmap_classes[12](12) cmapTable.platformID = 3 cmapTable.platEncID = 10 cmapTable.language = 0 cmapTable.cmap = cmap self.tables.append(cmapTable) # always create format-4 cmapTable = module.cmap_classes[4](4) cmapTable.platformID = 3 cmapTable.platEncID = 1 cmapTable.language = 0 cmapTable.cmap = cmapBmpOnly # ordered by platform then encoding self.tables.insert(0, cmapTable) self.tableVersion = 0 self.numSubTables = len(self.tables) return self
null
175,337
from fontTools import ttLib from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.ttLib.tables import otTables from fontTools.merge.base import add_method, mergeObjects from fontTools.merge.util import * import logging def mergeScripts(lst): assert lst if len(lst) == 1: return lst[0] langSyses = {} for sr in lst: for lsr in sr.LangSysRecord: if lsr.LangSysTag not in langSyses: langSyses[lsr.LangSysTag] = [] langSyses[lsr.LangSysTag].append(lsr.LangSys) lsrecords = [] for tag, langSys_list in sorted(langSyses.items()): lsr = otTables.LangSysRecord() lsr.LangSys = mergeLangSyses(langSys_list) lsr.LangSysTag = tag lsrecords.append(lsr) self = otTables.Script() self.LangSysRecord = lsrecords self.LangSysCount = len(lsrecords) dfltLangSyses = [s.DefaultLangSys for s in lst if s.DefaultLangSys] if dfltLangSyses: self.DefaultLangSys = mergeLangSyses(dfltLangSyses) else: self.DefaultLangSys = None return self otTables.ScriptList.mergeMap = { "ScriptCount": lambda lst: None, # TODO "ScriptRecord": mergeScriptRecords, } otTables.BaseScriptList.mergeMap = { "BaseScriptCount": lambda lst: None, # TODO # TODO: Merge duplicate entries "BaseScriptRecord": lambda lst: sorted( sumLists(lst), key=lambda s: s.BaseScriptTag ), } otTables.FeatureList.mergeMap = { "FeatureCount": sum, "FeatureRecord": lambda lst: sorted(sumLists(lst), key=lambda s: s.FeatureTag), } otTables.LookupList.mergeMap = { "LookupCount": sum, "Lookup": sumLists, } otTables.Coverage.mergeMap = { "Format": min, "glyphs": sumLists, } otTables.ClassDef.mergeMap = { "Format": min, "classDefs": sumDicts, } otTables.LigCaretList.mergeMap = { "Coverage": mergeObjects, "LigGlyphCount": sum, "LigGlyph": sumLists, } otTables.AttachList.mergeMap = { "Coverage": mergeObjects, "GlyphCount": sum, "AttachPoint": sumLists, } otTables.MarkGlyphSetsDef.mergeMap = { "MarkSetTableFormat": equal, "MarkSetCount": sum, "Coverage": sumLists, } otTables.Axis.mergeMap = { "*": mergeObjects, } otTables.BaseTagList.mergeMap = { "BaseTagCount": sum, "BaselineTag": sumLists, } otTables.GDEF.mergeMap = ( otTables.GSUB.mergeMap ) = ( otTables.GPOS.mergeMap ) = otTables.BASE.mergeMap = otTables.JSTF.mergeMap = otTables.MATH.mergeMap = { "*": mergeObjects, "Version": max, } def mergeScriptRecords(lst): d = {} for l in lst: for s in l: tag = s.ScriptTag if tag not in d: d[tag] = [] d[tag].append(s.Script) ret = [] for tag in sorted(d.keys()): rec = otTables.ScriptRecord() rec.ScriptTag = tag rec.Script = mergeScripts(d[tag]) ret.append(rec) return ret
null
175,338
from fontTools import ttLib from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.ttLib.tables import otTables from fontTools.merge.base import add_method, mergeObjects from fontTools.merge.util import * import logging log = logging.getLogger("fontTools.merge") otTables.ScriptList.mergeMap = { "ScriptCount": lambda lst: None, # TODO "ScriptRecord": mergeScriptRecords, } otTables.BaseScriptList.mergeMap = { "BaseScriptCount": lambda lst: None, # TODO # TODO: Merge duplicate entries "BaseScriptRecord": lambda lst: sorted( sumLists(lst), key=lambda s: s.BaseScriptTag ), } otTables.FeatureList.mergeMap = { "FeatureCount": sum, "FeatureRecord": lambda lst: sorted(sumLists(lst), key=lambda s: s.FeatureTag), } otTables.LookupList.mergeMap = { "LookupCount": sum, "Lookup": sumLists, } otTables.Coverage.mergeMap = { "Format": min, "glyphs": sumLists, } otTables.ClassDef.mergeMap = { "Format": min, "classDefs": sumDicts, } otTables.LigCaretList.mergeMap = { "Coverage": mergeObjects, "LigGlyphCount": sum, "LigGlyph": sumLists, } otTables.AttachList.mergeMap = { "Coverage": mergeObjects, "GlyphCount": sum, "AttachPoint": sumLists, } otTables.MarkGlyphSetsDef.mergeMap = { "MarkSetTableFormat": equal, "MarkSetCount": sum, "Coverage": sumLists, } otTables.Axis.mergeMap = { "*": mergeObjects, } otTables.BaseTagList.mergeMap = { "BaseTagCount": sum, "BaselineTag": sumLists, } otTables.GDEF.mergeMap = ( otTables.GSUB.mergeMap ) = ( otTables.GPOS.mergeMap ) = otTables.BASE.mergeMap = otTables.JSTF.mergeMap = otTables.MATH.mergeMap = { "*": mergeObjects, "Version": max, } class DefaultTable(object): dependencies = [] def __init__(self, tag=None): if tag is None: tag = getClassTag(self.__class__) self.tableTag = Tag(tag) def decompile(self, data, ttFont): self.data = data def compile(self, ttFont): return self.data def toXML(self, writer, ttFont, **kwargs): if hasattr(self, "ERROR"): writer.comment("An error occurred during the decompilation of this table") writer.newline() writer.comment(self.ERROR) writer.newline() writer.begintag("hexdata") writer.newline() writer.dumphex(self.compile(ttFont)) writer.endtag("hexdata") writer.newline() def fromXML(self, name, attrs, content, ttFont): from fontTools.misc.textTools import readHex from fontTools import ttLib if name != "hexdata": raise ttLib.TTLibError("can't handle '%s' element" % name) self.decompile(readHex(content), ttFont) def __repr__(self): return "<'%s' table at %x>" % (self.tableTag, id(self)) def __eq__(self, other): if type(self) != type(other): return NotImplemented return self.__dict__ == other.__dict__ def __ne__(self, other): result = self.__eq__(other) return result if result is NotImplemented else not result def merge(self, m, tables): assert len(tables) == len(m.duplicateGlyphsPerFont) for i, (table, dups) in enumerate(zip(tables, m.duplicateGlyphsPerFont)): if not dups: continue if table is None or table is NotImplemented: log.warning( "Have non-identical duplicates to resolve for '%s' but no GSUB. Are duplicates intended?: %s", m.fonts[i]._merger__name, dups, ) continue synthFeature = None synthLookup = None for script in table.table.ScriptList.ScriptRecord: if script.ScriptTag == "DFLT": continue # XXX for langsys in [script.Script.DefaultLangSys] + [ l.LangSys for l in script.Script.LangSysRecord ]: if langsys is None: continue # XXX Create! feature = [v for v in langsys.FeatureIndex if v.FeatureTag == "locl"] assert len(feature) <= 1 if feature: feature = feature[0] else: if not synthFeature: synthFeature = otTables.FeatureRecord() synthFeature.FeatureTag = "locl" f = synthFeature.Feature = otTables.Feature() f.FeatureParams = None f.LookupCount = 0 f.LookupListIndex = [] table.table.FeatureList.FeatureRecord.append(synthFeature) table.table.FeatureList.FeatureCount += 1 feature = synthFeature langsys.FeatureIndex.append(feature) langsys.FeatureIndex.sort(key=lambda v: v.FeatureTag) if not synthLookup: subtable = otTables.SingleSubst() subtable.mapping = dups synthLookup = otTables.Lookup() synthLookup.LookupFlag = 0 synthLookup.LookupType = 1 synthLookup.SubTableCount = 1 synthLookup.SubTable = [subtable] if table.table.LookupList is None: # mtiLib uses None as default value for LookupList, # while feaLib points to an empty array with count 0 # TODO: make them do the same table.table.LookupList = otTables.LookupList() table.table.LookupList.Lookup = [] table.table.LookupList.LookupCount = 0 table.table.LookupList.Lookup.append(synthLookup) table.table.LookupList.LookupCount += 1 if feature.Feature.LookupListIndex[:1] != [synthLookup]: feature.Feature.LookupListIndex[:0] = [synthLookup] feature.Feature.LookupCount += 1 DefaultTable.merge(self, m, tables) return self
null
175,339
from fontTools import ttLib from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.ttLib.tables import otTables from fontTools.merge.base import add_method, mergeObjects from fontTools.merge.util import * import logging def mapLookups(self, lookupMap): pass otTables.ContextSubst, otTables.ChainContextSubst, otTables.ContextPos, otTables.ChainContextPos, def mapLookups(self, lookupMap): c = self.__merge_classify_context() if self.Format in [1, 2]: for rs in getattr(self, c.RuleSet): if not rs: continue for r in getattr(rs, c.Rule): if not r: continue for ll in getattr(r, c.LookupRecord): if not ll: continue ll.LookupListIndex = lookupMap[ll.LookupListIndex] elif self.Format == 3: for ll in getattr(self, c.LookupRecord): if not ll: continue ll.LookupListIndex = lookupMap[ll.LookupListIndex] else: assert 0, "unknown format: %s" % self.Format def mapLookups(self, lookupMap): if self.Format == 1: self.ExtSubTable.mapLookups(lookupMap) else: assert 0, "unknown format: %s" % self.Format def mapLookups(self, lookupMap): for st in self.SubTable: if not st: continue st.mapLookups(lookupMap) def mapLookups(self, lookupMap): for l in self.Lookup: if not l: continue l.mapLookups(lookupMap) def mapMarkFilteringSets(self, markFilteringSetMap): if self.LookupFlag & 0x0010: self.MarkFilteringSet = markFilteringSetMap[self.MarkFilteringSet] def mapMarkFilteringSets(self, markFilteringSetMap): for l in self.Lookup: if not l: continue l.mapMarkFilteringSets(markFilteringSetMap) def mapLookups(self, lookupMap): self.LookupListIndex = [lookupMap[i] for i in self.LookupListIndex] def mapLookups(self, lookupMap): for f in self.FeatureRecord: if not f or not f.Feature: continue f.Feature.mapLookups(lookupMap) def mapFeatures(self, featureMap): self.FeatureIndex = [featureMap[i] for i in self.FeatureIndex] if self.ReqFeatureIndex != 65535: self.ReqFeatureIndex = featureMap[self.ReqFeatureIndex] def mapFeatures(self, featureMap): if self.DefaultLangSys: self.DefaultLangSys.mapFeatures(featureMap) for l in self.LangSysRecord: if not l or not l.LangSys: continue l.LangSys.mapFeatures(featureMap) def mapFeatures(self, featureMap): for s in self.ScriptRecord: if not s or not s.Script: continue s.Script.mapFeatures(featureMap) def layoutPreMerge(font): # Map indices to references GDEF = font.get("GDEF") GSUB = font.get("GSUB") GPOS = font.get("GPOS") for t in [GSUB, GPOS]: if not t: continue if t.table.LookupList: lookupMap = {i: v for i, v in enumerate(t.table.LookupList.Lookup)} t.table.LookupList.mapLookups(lookupMap) t.table.FeatureList.mapLookups(lookupMap) if GDEF and GDEF.table.Version >= 0x00010002: markFilteringSetMap = { i: v for i, v in enumerate(GDEF.table.MarkGlyphSetsDef.Coverage) } t.table.LookupList.mapMarkFilteringSets(markFilteringSetMap) if t.table.FeatureList and t.table.ScriptList: featureMap = {i: v for i, v in enumerate(t.table.FeatureList.FeatureRecord)} t.table.ScriptList.mapFeatures(featureMap) # TODO FeatureParams nameIDs
null
175,340
from fontTools import ttLib from fontTools.ttLib.tables.DefaultTable import DefaultTable from fontTools.ttLib.tables import otTables from fontTools.merge.base import add_method, mergeObjects from fontTools.merge.util import * import logging def mapLookups(self, lookupMap): pass otTables.ContextSubst, otTables.ChainContextSubst, otTables.ContextPos, otTables.ChainContextPos, def mapLookups(self, lookupMap): c = self.__merge_classify_context() if self.Format in [1, 2]: for rs in getattr(self, c.RuleSet): if not rs: continue for r in getattr(rs, c.Rule): if not r: continue for ll in getattr(r, c.LookupRecord): if not ll: continue ll.LookupListIndex = lookupMap[ll.LookupListIndex] elif self.Format == 3: for ll in getattr(self, c.LookupRecord): if not ll: continue ll.LookupListIndex = lookupMap[ll.LookupListIndex] else: assert 0, "unknown format: %s" % self.Format def mapLookups(self, lookupMap): if self.Format == 1: self.ExtSubTable.mapLookups(lookupMap) else: assert 0, "unknown format: %s" % self.Format def mapLookups(self, lookupMap): for st in self.SubTable: if not st: continue st.mapLookups(lookupMap) def mapLookups(self, lookupMap): for l in self.Lookup: if not l: continue l.mapLookups(lookupMap) def mapMarkFilteringSets(self, markFilteringSetMap): if self.LookupFlag & 0x0010: self.MarkFilteringSet = markFilteringSetMap[self.MarkFilteringSet] def mapMarkFilteringSets(self, markFilteringSetMap): for l in self.Lookup: if not l: continue l.mapMarkFilteringSets(markFilteringSetMap) def mapLookups(self, lookupMap): self.LookupListIndex = [lookupMap[i] for i in self.LookupListIndex] def mapLookups(self, lookupMap): for f in self.FeatureRecord: if not f or not f.Feature: continue f.Feature.mapLookups(lookupMap) def mapFeatures(self, featureMap): self.FeatureIndex = [featureMap[i] for i in self.FeatureIndex] if self.ReqFeatureIndex != 65535: self.ReqFeatureIndex = featureMap[self.ReqFeatureIndex] def mapFeatures(self, featureMap): if self.DefaultLangSys: self.DefaultLangSys.mapFeatures(featureMap) for l in self.LangSysRecord: if not l or not l.LangSys: continue l.LangSys.mapFeatures(featureMap) def mapFeatures(self, featureMap): for s in self.ScriptRecord: if not s or not s.Script: continue s.Script.mapFeatures(featureMap) def layoutPostMerge(font): # Map references back to indices GDEF = font.get("GDEF") GSUB = font.get("GSUB") GPOS = font.get("GPOS") for t in [GSUB, GPOS]: if not t: continue if t.table.FeatureList and t.table.ScriptList: # Collect unregistered (new) features. featureMap = GregariousIdentityDict(t.table.FeatureList.FeatureRecord) t.table.ScriptList.mapFeatures(featureMap) # Record used features. featureMap = AttendanceRecordingIdentityDict( t.table.FeatureList.FeatureRecord ) t.table.ScriptList.mapFeatures(featureMap) usedIndices = featureMap.s # Remove unused features t.table.FeatureList.FeatureRecord = [ f for i, f in enumerate(t.table.FeatureList.FeatureRecord) if i in usedIndices ] # Map back to indices. featureMap = NonhashableDict(t.table.FeatureList.FeatureRecord) t.table.ScriptList.mapFeatures(featureMap) t.table.FeatureList.FeatureCount = len(t.table.FeatureList.FeatureRecord) if t.table.LookupList: # Collect unregistered (new) lookups. lookupMap = GregariousIdentityDict(t.table.LookupList.Lookup) t.table.FeatureList.mapLookups(lookupMap) t.table.LookupList.mapLookups(lookupMap) # Record used lookups. lookupMap = AttendanceRecordingIdentityDict(t.table.LookupList.Lookup) t.table.FeatureList.mapLookups(lookupMap) t.table.LookupList.mapLookups(lookupMap) usedIndices = lookupMap.s # Remove unused lookups t.table.LookupList.Lookup = [ l for i, l in enumerate(t.table.LookupList.Lookup) if i in usedIndices ] # Map back to indices. lookupMap = NonhashableDict(t.table.LookupList.Lookup) t.table.FeatureList.mapLookups(lookupMap) t.table.LookupList.mapLookups(lookupMap) t.table.LookupList.LookupCount = len(t.table.LookupList.Lookup) if GDEF and GDEF.table.Version >= 0x00010002: markFilteringSetMap = NonhashableDict( GDEF.table.MarkGlyphSetsDef.Coverage ) t.table.LookupList.mapMarkFilteringSets(markFilteringSetMap) # TODO FeatureParams nameIDs
null
175,341
from fontTools.ttLib.tables.DefaultTable import DefaultTable import logging class DefaultTable(object): dependencies = [] def __init__(self, tag=None): if tag is None: tag = getClassTag(self.__class__) self.tableTag = Tag(tag) def decompile(self, data, ttFont): self.data = data def compile(self, ttFont): return self.data def toXML(self, writer, ttFont, **kwargs): if hasattr(self, "ERROR"): writer.comment("An error occurred during the decompilation of this table") writer.newline() writer.comment(self.ERROR) writer.newline() writer.begintag("hexdata") writer.newline() writer.dumphex(self.compile(ttFont)) writer.endtag("hexdata") writer.newline() def fromXML(self, name, attrs, content, ttFont): from fontTools.misc.textTools import readHex from fontTools import ttLib if name != "hexdata": raise ttLib.TTLibError("can't handle '%s' element" % name) self.decompile(readHex(content), ttFont) def __repr__(self): return "<'%s' table at %x>" % (self.tableTag, id(self)) def __eq__(self, other): if type(self) != type(other): return NotImplemented return self.__dict__ == other.__dict__ def __ne__(self, other): result = self.__eq__(other) return result if result is NotImplemented else not result The provided code snippet includes necessary dependencies for implementing the `add_method` function. Write a Python function `def add_method(*clazzes, **kwargs)` to solve the following problem: Returns a decorator function that adds a new method to one or more classes. Here is the function: def add_method(*clazzes, **kwargs): """Returns a decorator function that adds a new method to one or more classes.""" allowDefault = kwargs.get("allowDefaultTable", False) def wrapper(method): done = [] for clazz in clazzes: if clazz in done: continue # Support multiple names of a clazz done.append(clazz) assert allowDefault or clazz != DefaultTable, "Oops, table class not found." assert ( method.__name__ not in clazz.__dict__ ), "Oops, class '%s' has method '%s'." % (clazz.__name__, method.__name__) setattr(clazz, method.__name__, method) return None return wrapper
Returns a decorator function that adds a new method to one or more classes.
175,342
from fontTools.ttLib.tables.DefaultTable import DefaultTable import logging log = logging.getLogger("fontTools.merge") def mergeObjects(lst): lst = [item for item in lst if item is not NotImplemented] if not lst: return NotImplemented lst = [item for item in lst if item is not None] if not lst: return None clazz = lst[0].__class__ assert all(type(item) == clazz for item in lst), lst logic = clazz.mergeMap returnTable = clazz() returnDict = {} allKeys = set.union(set(), *(vars(table).keys() for table in lst)) for key in allKeys: try: mergeLogic = logic[key] except KeyError: try: mergeLogic = logic["*"] except KeyError: raise Exception( "Don't know how to merge key %s of class %s" % (key, clazz.__name__) ) if mergeLogic is NotImplemented: continue value = mergeLogic(getattr(table, key, NotImplemented) for table in lst) if value is not NotImplemented: returnDict[key] = value returnTable.__dict__ = returnDict return returnTable def merge(self, m, tables): if not hasattr(self, "mergeMap"): log.info("Don't know how to merge '%s'.", self.tableTag) return NotImplemented logic = self.mergeMap if isinstance(logic, dict): return m.mergeObjects(self, self.mergeMap, tables) else: return logic(tables)
null
175,343
import re def readlines(path): with open(path, "r", encoding="ascii") as f: data = f.read() return data.splitlines()
null
175,344
import re def writelines(path, lines, sep="\r"): with open(path, "w", encoding="ascii", newline=sep) as f: f.write("\n".join(lines) + "\n")
null
175,345
from fontTools.ttLib import TTFont, TTLibError from fontTools.misc.macCreatorType import getMacCreatorAndType from fontTools.unicode import setUnicodeData from fontTools.misc.textTools import Tag, tostr from fontTools.misc.timeTools import timestampSinceEpoch from fontTools.misc.loggingTools import Timer from fontTools.misc.cliTools import makeOutputFileName import os import sys import getopt import re import logging class Options(object): listTables = False outputDir = None outputFile = None overWrite = False verbose = False quiet = False splitTables = False splitGlyphs = False disassembleInstructions = True mergeFile = None recalcBBoxes = True ignoreDecompileErrors = True bitmapGlyphDataFormat = "raw" unicodedata = None newlinestr = "\n" recalcTimestamp = None flavor = None useZopfli = False def __init__(self, rawOptions, numFiles): self.onlyTables = [] self.skipTables = [] self.fontNumber = -1 for option, value in rawOptions: # general options if option == "-h": print(__doc__) sys.exit(0) elif option == "--version": from fontTools import version print(version) sys.exit(0) elif option == "-d": if not os.path.isdir(value): raise getopt.GetoptError( "The -d option value must be an existing directory" ) self.outputDir = value elif option == "-o": self.outputFile = value elif option == "-f": self.overWrite = True elif option == "-v": self.verbose = True elif option == "-q": self.quiet = True # dump options elif option == "-l": self.listTables = True elif option == "-t": # pad with space if table tag length is less than 4 value = value.ljust(4) self.onlyTables.append(value) elif option == "-x": # pad with space if table tag length is less than 4 value = value.ljust(4) self.skipTables.append(value) elif option == "-s": self.splitTables = True elif option == "-g": # -g implies (and forces) splitTables self.splitGlyphs = True self.splitTables = True elif option == "-i": self.disassembleInstructions = False elif option == "-z": validOptions = ("raw", "row", "bitwise", "extfile") if value not in validOptions: raise getopt.GetoptError( "-z does not allow %s as a format. Use %s" % (option, validOptions) ) self.bitmapGlyphDataFormat = value elif option == "-y": self.fontNumber = int(value) # compile options elif option == "-m": self.mergeFile = value elif option == "-b": self.recalcBBoxes = False elif option == "-e": self.ignoreDecompileErrors = False elif option == "--unicodedata": self.unicodedata = value elif option == "--newline": validOptions = ("LF", "CR", "CRLF") if value == "LF": self.newlinestr = "\n" elif value == "CR": self.newlinestr = "\r" elif value == "CRLF": self.newlinestr = "\r\n" else: raise getopt.GetoptError( "Invalid choice for --newline: %r (choose from %s)" % (value, ", ".join(map(repr, validOptions))) ) elif option == "--recalc-timestamp": self.recalcTimestamp = True elif option == "--no-recalc-timestamp": self.recalcTimestamp = False elif option == "--flavor": self.flavor = value elif option == "--with-zopfli": self.useZopfli = True if self.verbose and self.quiet: raise getopt.GetoptError("-q and -v options are mutually exclusive") if self.verbose: self.logLevel = logging.DEBUG elif self.quiet: self.logLevel = logging.WARNING else: self.logLevel = logging.INFO if self.mergeFile and self.flavor: raise getopt.GetoptError("-m and --flavor options are mutually exclusive") if self.onlyTables and self.skipTables: raise getopt.GetoptError("-t and -x options are mutually exclusive") if self.mergeFile and numFiles > 1: raise getopt.GetoptError( "Must specify exactly one TTX source file when using -m" ) if self.flavor != "woff" and self.useZopfli: raise getopt.GetoptError("--with-zopfli option requires --flavor 'woff'") def ttList(input, output, options): ttf = TTFont(input, fontNumber=options.fontNumber, lazy=True) reader = ttf.reader tags = sorted(reader.keys()) print('Listing table info for "%s":' % input) format = " %4s %10s %8s %8s" print(format % ("tag ", " checksum", " length", " offset")) print(format % ("----", "----------", "--------", "--------")) for tag in tags: entry = reader.tables[tag] if ttf.flavor == "woff2": # WOFF2 doesn't store table checksums, so they must be calculated from fontTools.ttLib.sfnt import calcChecksum data = entry.loadData(reader.transformBuffer) checkSum = calcChecksum(data) else: checkSum = int(entry.checkSum) if checkSum < 0: checkSum = checkSum + 0x100000000 checksum = "0x%08X" % checkSum print(format % (tag, checksum, entry.length, entry.offset)) print() ttf.close() def ttDump(input, output, options): input_name = input if input == "-": input, input_name = sys.stdin.buffer, sys.stdin.name output_name = output if output == "-": output, output_name = sys.stdout, sys.stdout.name log.info('Dumping "%s" to "%s"...', input_name, output_name) if options.unicodedata: setUnicodeData(options.unicodedata) ttf = TTFont( input, 0, ignoreDecompileErrors=options.ignoreDecompileErrors, fontNumber=options.fontNumber, ) ttf.saveXML( output, tables=options.onlyTables, skipTables=options.skipTables, splitTables=options.splitTables, splitGlyphs=options.splitGlyphs, disassembleInstructions=options.disassembleInstructions, bitmapGlyphDataFormat=options.bitmapGlyphDataFormat, newlinestr=options.newlinestr, ) ttf.close() def ttCompile(input, output, options): input_name = input if input == "-": input, input_name = sys.stdin, sys.stdin.name output_name = output if output == "-": output, output_name = sys.stdout.buffer, sys.stdout.name log.info('Compiling "%s" to "%s"...' % (input_name, output)) if options.useZopfli: from fontTools.ttLib import sfnt sfnt.USE_ZOPFLI = True ttf = TTFont( options.mergeFile, flavor=options.flavor, recalcBBoxes=options.recalcBBoxes, recalcTimestamp=options.recalcTimestamp, ) ttf.importXML(input) if options.recalcTimestamp is None and "head" in ttf and input is not sys.stdin: # use TTX file modification time for head "modified" timestamp mtime = os.path.getmtime(input) ttf["head"].modified = timestampSinceEpoch(mtime) ttf.save(output) def guessFileType(fileName): if fileName == "-": header = sys.stdin.buffer.peek(256) ext = "" else: base, ext = os.path.splitext(fileName) try: with open(fileName, "rb") as f: header = f.read(256) except IOError: return None if header.startswith(b"\xef\xbb\xbf<?xml"): header = header.lstrip(b"\xef\xbb\xbf") cr, tp = getMacCreatorAndType(fileName) if tp in ("sfnt", "FFIL"): return "TTF" if ext == ".dfont": return "TTF" head = Tag(header[:4]) if head == "OTTO": return "OTF" elif head == "ttcf": return "TTC" elif head in ("\0\1\0\0", "true"): return "TTF" elif head == "wOFF": return "WOFF" elif head == "wOF2": return "WOFF2" elif head == "<?xm": # Use 'latin1' because that can't fail. header = tostr(header, "latin1") if opentypeheaderRE.search(header): return "OTX" else: return "TTX" return None def makeOutputFileName( input, outputDir=None, extension=None, overWrite=False, suffix="" ): """Generates a suitable file name for writing output. Often tools will want to take a file, do some kind of transformation to it, and write it out again. This function determines an appropriate name for the output file, through one or more of the following steps: - changing the output directory - appending suffix before file extension - replacing the file extension - suffixing the filename with a number (``#1``, ``#2``, etc.) to avoid overwriting an existing file. Args: input: Name of input file. outputDir: Optionally, a new directory to write the file into. suffix: Optionally, a string suffix is appended to file name before the extension. extension: Optionally, a replacement for the current file extension. overWrite: Overwriting an existing file is permitted if true; if false and the proposed filename exists, a new name will be generated by adding an appropriate number suffix. Returns: str: Suitable output filename """ dirName, fileName = os.path.split(input) fileName, ext = os.path.splitext(fileName) if outputDir: dirName = outputDir fileName = numberAddedRE.split(fileName)[0] if extension is None: extension = os.path.splitext(input)[1] output = os.path.join(dirName, fileName + suffix + extension) n = 1 if not overWrite: while os.path.exists(output): output = os.path.join( dirName, fileName + suffix + "#" + repr(n) + extension ) n += 1 return output def parseOptions(args): rawOptions, files = getopt.getopt( args, "ld:o:fvqht:x:sgim:z:baey:", [ "unicodedata=", "recalc-timestamp", "no-recalc-timestamp", "flavor=", "version", "with-zopfli", "newline=", ], ) options = Options(rawOptions, len(files)) jobs = [] if not files: raise getopt.GetoptError("Must specify at least one input file") for input in files: if input != "-" and not os.path.isfile(input): raise getopt.GetoptError('File not found: "%s"' % input) tp = guessFileType(input) if tp in ("OTF", "TTF", "TTC", "WOFF", "WOFF2"): extension = ".ttx" if options.listTables: action = ttList else: action = ttDump elif tp == "TTX": extension = "." + options.flavor if options.flavor else ".ttf" action = ttCompile elif tp == "OTX": extension = "." + options.flavor if options.flavor else ".otf" action = ttCompile else: raise getopt.GetoptError('Unknown file type: "%s"' % input) if options.outputFile: output = options.outputFile else: if input == "-": raise getopt.GetoptError("Must provide -o when reading from stdin") output = makeOutputFileName( input, options.outputDir, extension, options.overWrite ) # 'touch' output file to avoid race condition in choosing file names if action != ttList: open(output, "a").close() jobs.append((action, input, output)) return jobs, options
null
175,346
from fontTools.ttLib import TTFont, TTLibError from fontTools.misc.macCreatorType import getMacCreatorAndType from fontTools.unicode import setUnicodeData from fontTools.misc.textTools import Tag, tostr from fontTools.misc.timeTools import timestampSinceEpoch from fontTools.misc.loggingTools import Timer from fontTools.misc.cliTools import makeOutputFileName import os import sys import getopt import re import logging def process(jobs, options): for action, input, output in jobs: action(input, output, options)
null
175,347
import os import argparse import logging from fontTools.misc.cliTools import makeOutputFileName from fontTools.ttLib import TTFont from fontTools.pens.qu2cuPen import Qu2CuPen from fontTools.pens.ttGlyphPen import TTGlyphPen import fontTools logger = logging.getLogger("fontTools.qu2cu") class Qu2CuPen(ContourFilterPen): """A filter pen to convert quadratic bezier splines to cubic curves using the FontTools SegmentPen protocol. Args: other_pen: another SegmentPen used to draw the transformed outline. max_err: maximum approximation error in font units. For optimal results, if you know the UPEM of the font, we recommend setting this to a value equal, or close to UPEM / 1000. reverse_direction: flip the contours' direction but keep starting point. stats: a dictionary counting the point numbers of cubic segments. """ def __init__( self, other_pen, max_err, all_cubic=False, reverse_direction=False, stats=None, ): if reverse_direction: other_pen = ReverseContourPen(other_pen) super().__init__(other_pen) self.all_cubic = all_cubic self.max_err = max_err self.stats = stats def _quadratics_to_curve(self, q): curves = quadratic_to_curves(q, self.max_err, all_cubic=self.all_cubic) if self.stats is not None: for curve in curves: n = str(len(curve) - 2) self.stats[n] = self.stats.get(n, 0) + 1 for curve in curves: if len(curve) == 4: yield ("curveTo", curve[1:]) else: yield ("qCurveTo", curve[1:]) def filterContour(self, contour): quadratics = [] currentPt = None newContour = [] for op, args in contour: if op == "qCurveTo" and ( self.all_cubic or (len(args) > 2 and args[-1] is not None) ): if args[-1] is None: raise NotImplementedError( "oncurve-less contours with all_cubic not implemented" ) quadratics.append((currentPt,) + args) else: if quadratics: newContour.extend(self._quadratics_to_curve(quadratics)) quadratics = [] newContour.append((op, args)) currentPt = args[-1] if args else None if quadratics: newContour.extend(self._quadratics_to_curve(quadratics)) if not self.all_cubic: # Add back implicit oncurve points contour = newContour newContour = [] for op, args in contour: if op == "qCurveTo" and newContour and newContour[-1][0] == "qCurveTo": pt0 = newContour[-1][1][-2] pt1 = newContour[-1][1][-1] pt2 = args[0] if ( pt1 is not None and math.isclose(pt2[0] - pt1[0], pt1[0] - pt0[0]) and math.isclose(pt2[1] - pt1[1], pt1[1] - pt0[1]) ): newArgs = newContour[-1][1][:-1] + args newContour[-1] = (op, newArgs) continue newContour.append((op, args)) return newContour class TTGlyphPen(_TTGlyphBasePen, LoggingPen): """ Pen used for drawing to a TrueType glyph. This pen can be used to construct or modify glyphs in a TrueType format font. After using the pen to draw, use the ``.glyph()`` method to retrieve a :py:class:`~._g_l_y_f.Glyph` object representing the glyph. """ drawMethod = "draw" transformPen = TransformPen def __init__( self, glyphSet: Optional[Dict[str, Any]] = None, handleOverflowingTransforms: bool = True, outputImpliedClosingLine: bool = False, ) -> None: super().__init__(glyphSet, handleOverflowingTransforms) self.outputImpliedClosingLine = outputImpliedClosingLine def _addPoint(self, pt: Tuple[float, float], tp: int) -> None: self.points.append(pt) self.types.append(tp) def _popPoint(self) -> None: self.points.pop() self.types.pop() def _isClosed(self) -> bool: return (not self.points) or ( self.endPts and self.endPts[-1] == len(self.points) - 1 ) def lineTo(self, pt: Tuple[float, float]) -> None: self._addPoint(pt, flagOnCurve) def moveTo(self, pt: Tuple[float, float]) -> None: if not self._isClosed(): raise PenError('"move"-type point must begin a new contour.') self._addPoint(pt, flagOnCurve) def curveTo(self, *points) -> None: assert len(points) % 2 == 1 for pt in points[:-1]: self._addPoint(pt, flagCubic) # last point is None if there are no on-curve points if points[-1] is not None: self._addPoint(points[-1], 1) def qCurveTo(self, *points) -> None: assert len(points) >= 1 for pt in points[:-1]: self._addPoint(pt, 0) # last point is None if there are no on-curve points if points[-1] is not None: self._addPoint(points[-1], 1) def closePath(self) -> None: endPt = len(self.points) - 1 # ignore anchors (one-point paths) if endPt == 0 or (self.endPts and endPt == self.endPts[-1] + 1): self._popPoint() return if not self.outputImpliedClosingLine: # if first and last point on this path are the same, remove last startPt = 0 if self.endPts: startPt = self.endPts[-1] + 1 if self.points[startPt] == self.points[endPt]: self._popPoint() endPt -= 1 self.endPts.append(endPt) def endPath(self) -> None: # TrueType contours are always "closed" self.closePath() def _font_to_cubic(input_path, output_path=None, **kwargs): font = TTFont(input_path) logger.info("Converting curves for %s", input_path) stats = {} if kwargs["dump_stats"] else None qu2cu_kwargs = { "stats": stats, "max_err": kwargs["max_err_em"] * font["head"].unitsPerEm, "all_cubic": kwargs["all_cubic"], } assert "gvar" not in font, "Cannot convert variable font" glyphSet = font.getGlyphSet() glyphOrder = font.getGlyphOrder() glyf = font["glyf"] for glyphName in glyphOrder: glyph = glyphSet[glyphName] ttpen = TTGlyphPen(glyphSet) pen = Qu2CuPen(ttpen, **qu2cu_kwargs) glyph.draw(pen) glyf[glyphName] = ttpen.glyph(dropImpliedOnCurves=True) font["head"].glyphDataFormat = 1 if kwargs["dump_stats"]: logger.info("Stats: %s", stats) logger.info("Saving %s", output_path) font.save(output_path)
null
175,348
from fontTools.misc.bezierTools import splitCubicAtTC from collections import namedtuple import math from typing import ( List, Tuple, Union, ) def add_implicit_on_curves(p): q = list(p) count = 0 num_offcurves = len(p) - 2 for i in range(1, num_offcurves): off1 = p[i] off2 = p[i + 1] on = off1 + (off2 - off1) * 0.5 q.insert(i + 1 + count, on) count += 1 return q Point = Union[Tuple[float, float], complex] cost=cython.int, is_complex=cython.int, i=cython.int, def spline_to_curves(q, costs, tolerance=0.5, all_cubic=False): """ q: quadratic spline with alternating on-curve / off-curve points. costs: cumulative list of encoding cost of q in terms of number of points that need to be encoded. Implied on-curve points do not contribute to the cost. If all points need to be encoded, then costs will be range(1, len(q)+1). """ assert len(q) >= 3, "quadratic spline requires at least 3 points" # Elevate quadratic segments to cubic elevated_quadratics = [ elevate_quadratic(*q[i : i + 3]) for i in range(0, len(q) - 2, 2) ] # Find sharp corners; they have to be oncurves for sure. forced = set() for i in range(1, len(elevated_quadratics)): p0 = elevated_quadratics[i - 1][2] p1 = elevated_quadratics[i][0] p2 = elevated_quadratics[i][1] if abs(p1 - p0) + abs(p2 - p1) > tolerance + abs(p2 - p0): forced.add(i) # Dynamic-Programming to find the solution with fewest number of # cubic curves, and within those the one with smallest error. sols = [Solution(0, 0, 0, False)] impossible = Solution(len(elevated_quadratics) * 3 + 1, 0, 1, False) start = 0 for i in range(1, len(elevated_quadratics) + 1): best_sol = impossible for j in range(start, i): j_sol_count, j_sol_error = sols[j].num_points, sols[j].error if not all_cubic: # Solution with quadratics between j:i this_count = costs[2 * i - 1] - costs[2 * j] + 1 i_sol_count = j_sol_count + this_count i_sol_error = j_sol_error i_sol = Solution(i_sol_count, i_sol_error, i - j, False) if i_sol < best_sol: best_sol = i_sol if this_count <= 3: # Can't get any better than this in the path below continue # Fit elevated_quadratics[j:i] into one cubic try: curve, ts = merge_curves(elevated_quadratics, j, i - j) except ZeroDivisionError: continue # Now reconstruct the segments from the fitted curve reconstructed_iter = splitCubicAtTC(*curve, *ts) reconstructed = [] # Knot errors error = 0 for k, reconst in enumerate(reconstructed_iter): orig = elevated_quadratics[j + k] err = abs(reconst[3] - orig[3]) error = max(error, err) if error > tolerance: break reconstructed.append(reconst) if error > tolerance: # Not feasible continue # Interior errors for k, reconst in enumerate(reconstructed): orig = elevated_quadratics[j + k] p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig)) if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): error = tolerance + 1 break if error > tolerance: # Not feasible continue # Save best solution i_sol_count = j_sol_count + 3 i_sol_error = max(j_sol_error, error) i_sol = Solution(i_sol_count, i_sol_error, i - j, True) if i_sol < best_sol: best_sol = i_sol if i_sol_count == 3: # Can't get any better than this break sols.append(best_sol) if i in forced: start = i # Reconstruct solution splits = [] cubic = [] i = len(sols) - 1 while i: count, is_cubic = sols[i].start_index, sols[i].is_cubic splits.append(i) cubic.append(is_cubic) i -= count curves = [] j = 0 for i, is_cubic in reversed(list(zip(splits, cubic))): if is_cubic: curves.append(merge_curves(elevated_quadratics, j, i - j)[0]) else: for k in range(j, i): curves.append(q[k * 2 : k * 2 + 3]) j = i return curves List = _Alias() class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict The provided code snippet includes necessary dependencies for implementing the `quadratic_to_curves` function. Write a Python function `def quadratic_to_curves( quads: List[List[Point]], max_err: float = 0.5, all_cubic: bool = False, ) -> List[Tuple[Point, ...]]` to solve the following problem: Converts a connecting list of quadratic splines to a list of quadratic and cubic curves. A quadratic spline is specified as a list of points. Either each point is a 2-tuple of X,Y coordinates, or each point is a complex number with real/imaginary components representing X,Y coordinates. The first and last points are on-curve points and the rest are off-curve points, with an implied on-curve point in the middle between every two consequtive off-curve points. Returns: The output is a list of tuples of points. Points are represented in the same format as the input, either as 2-tuples or complex numbers. Each tuple is either of length three, for a quadratic curve, or four, for a cubic curve. Each curve's last point is the same as the next curve's first point. Args: quads: quadratic splines max_err: absolute error tolerance; defaults to 0.5 all_cubic: if True, only cubic curves are generated; defaults to False Here is the function: def quadratic_to_curves( quads: List[List[Point]], max_err: float = 0.5, all_cubic: bool = False, ) -> List[Tuple[Point, ...]]: """Converts a connecting list of quadratic splines to a list of quadratic and cubic curves. A quadratic spline is specified as a list of points. Either each point is a 2-tuple of X,Y coordinates, or each point is a complex number with real/imaginary components representing X,Y coordinates. The first and last points are on-curve points and the rest are off-curve points, with an implied on-curve point in the middle between every two consequtive off-curve points. Returns: The output is a list of tuples of points. Points are represented in the same format as the input, either as 2-tuples or complex numbers. Each tuple is either of length three, for a quadratic curve, or four, for a cubic curve. Each curve's last point is the same as the next curve's first point. Args: quads: quadratic splines max_err: absolute error tolerance; defaults to 0.5 all_cubic: if True, only cubic curves are generated; defaults to False """ is_complex = type(quads[0][0]) is complex if not is_complex: quads = [[complex(x, y) for (x, y) in p] for p in quads] q = [quads[0][0]] costs = [1] cost = 1 for p in quads: assert q[-1] == p[0] for i in range(len(p) - 2): cost += 1 costs.append(cost) costs.append(cost) qq = add_implicit_on_curves(p)[1:] costs.pop() q.extend(qq) cost += 1 costs.append(cost) curves = spline_to_curves(q, costs, max_err, all_cubic) if not is_complex: curves = [tuple((c.real, c.imag) for c in curve) for curve in curves] return curves
Converts a connecting list of quadratic splines to a list of quadratic and cubic curves. A quadratic spline is specified as a list of points. Either each point is a 2-tuple of X,Y coordinates, or each point is a complex number with real/imaginary components representing X,Y coordinates. The first and last points are on-curve points and the rest are off-curve points, with an implied on-curve point in the middle between every two consequtive off-curve points. Returns: The output is a list of tuples of points. Points are represented in the same format as the input, either as 2-tuples or complex numbers. Each tuple is either of length three, for a quadratic curve, or four, for a cubic curve. Each curve's last point is the same as the next curve's first point. Args: quads: quadratic splines max_err: absolute error tolerance; defaults to 0.5 all_cubic: if True, only cubic curves are generated; defaults to False
175,349
from .qu2cu import * from fontTools.cu2qu import curve_to_quadratic import random import timeit MAX_ERR = 0.5 NUM_CURVES = 5 def generate_curves(n): ) ) ) ) ) ) def setup_quadratic_to_curves(): curves = generate_curves(NUM_CURVES) quadratics = [curve_to_quadratic(curve, MAX_ERR) for curve in curves] return quadratics, MAX_ERR
null
175,350
from .qu2cu import * from fontTools.cu2qu import curve_to_quadratic import random import timeit ) ) ) ) ) ) def run_benchmark(module, function, setup_suffix="", repeat=25, number=1): setup_func = "setup_" + function if setup_suffix: print("%s with %s:" % (function, setup_suffix), end="") setup_func += "_" + setup_suffix else: print("%s:" % function, end="") def wrapper(function, setup_func): function = globals()[function] setup_func = globals()[setup_func] def wrapped(): return function(*setup_func()) return wrapped results = timeit.repeat(wrapper(function, setup_func), repeat=repeat, number=number) print("\t%5.1fus" % (min(results) * 1000000.0 / number))
null
175,351
def maxCtxSubtable(maxCtx, tag, lookupType, st): """Calculate usMaxContext based on a single lookup table (and an existing max value). """ # single positioning, single / multiple substitution if (tag == "GPOS" and lookupType == 1) or ( tag == "GSUB" and lookupType in (1, 2, 3) ): maxCtx = max(maxCtx, 1) # pair positioning elif tag == "GPOS" and lookupType == 2: maxCtx = max(maxCtx, 2) # ligatures elif tag == "GSUB" and lookupType == 4: for ligatures in st.ligatures.values(): for ligature in ligatures: maxCtx = max(maxCtx, ligature.CompCount) # context elif (tag == "GPOS" and lookupType == 7) or (tag == "GSUB" and lookupType == 5): maxCtx = maxCtxContextualSubtable(maxCtx, st, "Pos" if tag == "GPOS" else "Sub") # chained context elif (tag == "GPOS" and lookupType == 8) or (tag == "GSUB" and lookupType == 6): maxCtx = maxCtxContextualSubtable( maxCtx, st, "Pos" if tag == "GPOS" else "Sub", "Chain" ) # extensions elif (tag == "GPOS" and lookupType == 9) or (tag == "GSUB" and lookupType == 7): maxCtx = maxCtxSubtable(maxCtx, tag, st.ExtensionLookupType, st.ExtSubTable) # reverse-chained context elif tag == "GSUB" and lookupType == 8: maxCtx = maxCtxContextualRule(maxCtx, st, "Reverse") return maxCtx The provided code snippet includes necessary dependencies for implementing the `maxCtxFont` function. Write a Python function `def maxCtxFont(font)` to solve the following problem: Calculate the usMaxContext value for an entire font. Here is the function: def maxCtxFont(font): """Calculate the usMaxContext value for an entire font.""" maxCtx = 0 for tag in ("GSUB", "GPOS"): if tag not in font: continue table = font[tag].table if not table.LookupList: continue for lookup in table.LookupList.Lookup: for st in lookup.SubTable: maxCtx = maxCtxSubtable(maxCtx, tag, lookup.LookupType, st) return maxCtx
Calculate the usMaxContext value for an entire font.
175,352
from collections import namedtuple, OrderedDict import os from fontTools.misc.fixedTools import fixedToFloat from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables.otBase import ( ValueRecord, valueRecordFormatDict, OTTableWriter, CountReference, ) from fontTools.ttLib.tables import otBase from fontTools.feaLib.ast import STATNameStatement from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_lookup, ) from fontTools.otlLib.error import OpenTypeLibError from functools import reduce import logging import copy The provided code snippet includes necessary dependencies for implementing the `buildMultipleSubstSubtable` function. Write a Python function `def buildMultipleSubstSubtable(mapping)` to solve the following problem: Builds a multiple substitution (GSUB2) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MultipleSubstBuilder` instead. Example:: # sub uni06C0 by uni06D5.fina hamza.above # sub uni06C2 by uni06C1.fina hamza.above; subtable = buildMultipleSubstSubtable({ "uni06C0": [ "uni06D5.fina", "hamza.above"], "uni06C2": [ "uni06D1.fina", "hamza.above"] }) Args: mapping: A dictionary mapping input glyph names to a list of output glyph names. Returns: An ``otTables.MultipleSubst`` object or ``None`` if the mapping dictionary is empty. Here is the function: def buildMultipleSubstSubtable(mapping): """Builds a multiple substitution (GSUB2) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MultipleSubstBuilder` instead. Example:: # sub uni06C0 by uni06D5.fina hamza.above # sub uni06C2 by uni06C1.fina hamza.above; subtable = buildMultipleSubstSubtable({ "uni06C0": [ "uni06D5.fina", "hamza.above"], "uni06C2": [ "uni06D1.fina", "hamza.above"] }) Args: mapping: A dictionary mapping input glyph names to a list of output glyph names. Returns: An ``otTables.MultipleSubst`` object or ``None`` if the mapping dictionary is empty. """ if not mapping: return None self = ot.MultipleSubst() self.mapping = dict(mapping) return self
Builds a multiple substitution (GSUB2) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MultipleSubstBuilder` instead. Example:: # sub uni06C0 by uni06D5.fina hamza.above # sub uni06C2 by uni06C1.fina hamza.above; subtable = buildMultipleSubstSubtable({ "uni06C0": [ "uni06D5.fina", "hamza.above"], "uni06C2": [ "uni06D1.fina", "hamza.above"] }) Args: mapping: A dictionary mapping input glyph names to a list of output glyph names. Returns: An ``otTables.MultipleSubst`` object or ``None`` if the mapping dictionary is empty.
175,353
from collections import namedtuple, OrderedDict import os from fontTools.misc.fixedTools import fixedToFloat from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables.otBase import ( ValueRecord, valueRecordFormatDict, OTTableWriter, CountReference, ) from fontTools.ttLib.tables import otBase from fontTools.feaLib.ast import STATNameStatement from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_lookup, ) from fontTools.otlLib.error import OpenTypeLibError from functools import reduce import logging import copy The provided code snippet includes necessary dependencies for implementing the `buildAlternateSubstSubtable` function. Write a Python function `def buildAlternateSubstSubtable(mapping)` to solve the following problem: Builds an alternate substitution (GSUB3) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.AlternateSubstBuilder` instead. Args: mapping: A dictionary mapping input glyph names to a list of output glyph names. Returns: An ``otTables.AlternateSubst`` object or ``None`` if the mapping dictionary is empty. Here is the function: def buildAlternateSubstSubtable(mapping): """Builds an alternate substitution (GSUB3) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.AlternateSubstBuilder` instead. Args: mapping: A dictionary mapping input glyph names to a list of output glyph names. Returns: An ``otTables.AlternateSubst`` object or ``None`` if the mapping dictionary is empty. """ if not mapping: return None self = ot.AlternateSubst() self.alternates = dict(mapping) return self
Builds an alternate substitution (GSUB3) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.AlternateSubstBuilder` instead. Args: mapping: A dictionary mapping input glyph names to a list of output glyph names. Returns: An ``otTables.AlternateSubst`` object or ``None`` if the mapping dictionary is empty.
175,354
from collections import namedtuple, OrderedDict import os from fontTools.misc.fixedTools import fixedToFloat from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables.otBase import ( ValueRecord, valueRecordFormatDict, OTTableWriter, CountReference, ) from fontTools.ttLib.tables import otBase from fontTools.feaLib.ast import STATNameStatement from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_lookup, ) from fontTools.otlLib.error import OpenTypeLibError from functools import reduce import logging import copy def _getLigatureKey(components): # Computes a key for ordering ligatures in a GSUB Type-4 lookup. # When building the OpenType lookup, we need to make sure that # the longest sequence of components is listed first, so we # use the negative length as the primary key for sorting. # To make buildLigatureSubstSubtable() deterministic, we use the # component sequence as the secondary key. # For example, this will sort (f,f,f) < (f,f,i) < (f,f) < (f,i) < (f,l). return (-len(components), components) The provided code snippet includes necessary dependencies for implementing the `buildLigatureSubstSubtable` function. Write a Python function `def buildLigatureSubstSubtable(mapping)` to solve the following problem: Builds a ligature substitution (GSUB4) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.LigatureSubstBuilder` instead. Example:: # sub f f i by f_f_i; # sub f i by f_i; subtable = buildLigatureSubstSubtable({ ("f", "f", "i"): "f_f_i", ("f", "i"): "f_i", }) Args: mapping: A dictionary mapping tuples of glyph names to output glyph names. Returns: An ``otTables.LigatureSubst`` object or ``None`` if the mapping dictionary is empty. Here is the function: def buildLigatureSubstSubtable(mapping): """Builds a ligature substitution (GSUB4) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.LigatureSubstBuilder` instead. Example:: # sub f f i by f_f_i; # sub f i by f_i; subtable = buildLigatureSubstSubtable({ ("f", "f", "i"): "f_f_i", ("f", "i"): "f_i", }) Args: mapping: A dictionary mapping tuples of glyph names to output glyph names. Returns: An ``otTables.LigatureSubst`` object or ``None`` if the mapping dictionary is empty. """ if not mapping: return None self = ot.LigatureSubst() # The following single line can replace the rest of this function # with fontTools >= 3.1: # self.ligatures = dict(mapping) self.ligatures = {} for components in sorted(mapping.keys(), key=_getLigatureKey): ligature = ot.Ligature() ligature.Component = components[1:] ligature.CompCount = len(ligature.Component) + 1 ligature.LigGlyph = mapping[components] firstGlyph = components[0] self.ligatures.setdefault(firstGlyph, []).append(ligature) return self
Builds a ligature substitution (GSUB4) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.LigatureSubstBuilder` instead. Example:: # sub f f i by f_f_i; # sub f i by f_i; subtable = buildLigatureSubstSubtable({ ("f", "f", "i"): "f_f_i", ("f", "i"): "f_i", }) Args: mapping: A dictionary mapping tuples of glyph names to output glyph names. Returns: An ``otTables.LigatureSubst`` object or ``None`` if the mapping dictionary is empty.
175,355
from collections import namedtuple, OrderedDict import os from fontTools.misc.fixedTools import fixedToFloat from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables.otBase import ( ValueRecord, valueRecordFormatDict, OTTableWriter, CountReference, ) from fontTools.ttLib.tables import otBase from fontTools.feaLib.ast import STATNameStatement from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_lookup, ) from fontTools.otlLib.error import OpenTypeLibError from functools import reduce import logging import copy The provided code snippet includes necessary dependencies for implementing the `buildAnchor` function. Write a Python function `def buildAnchor(x, y, point=None, deviceX=None, deviceY=None)` to solve the following problem: Builds an Anchor table. This determines the appropriate anchor format based on the passed parameters. Args: x (int): X coordinate. y (int): Y coordinate. point (int): Index of glyph contour point, if provided. deviceX (``otTables.Device``): X coordinate device table, if provided. deviceY (``otTables.Device``): Y coordinate device table, if provided. Returns: An ``otTables.Anchor`` object. Here is the function: def buildAnchor(x, y, point=None, deviceX=None, deviceY=None): """Builds an Anchor table. This determines the appropriate anchor format based on the passed parameters. Args: x (int): X coordinate. y (int): Y coordinate. point (int): Index of glyph contour point, if provided. deviceX (``otTables.Device``): X coordinate device table, if provided. deviceY (``otTables.Device``): Y coordinate device table, if provided. Returns: An ``otTables.Anchor`` object. """ self = ot.Anchor() self.XCoordinate, self.YCoordinate = x, y self.Format = 1 if point is not None: self.AnchorPoint = point self.Format = 2 if deviceX is not None or deviceY is not None: assert ( self.Format == 1 ), "Either point, or both of deviceX/deviceY, must be None." self.XDeviceTable = deviceX self.YDeviceTable = deviceY self.Format = 3 return self
Builds an Anchor table. This determines the appropriate anchor format based on the passed parameters. Args: x (int): X coordinate. y (int): Y coordinate. point (int): Index of glyph contour point, if provided. deviceX (``otTables.Device``): X coordinate device table, if provided. deviceY (``otTables.Device``): Y coordinate device table, if provided. Returns: An ``otTables.Anchor`` object.
175,356
from collections import namedtuple, OrderedDict import os from fontTools.misc.fixedTools import fixedToFloat from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables.otBase import ( ValueRecord, valueRecordFormatDict, OTTableWriter, CountReference, ) from fontTools.ttLib.tables import otBase from fontTools.feaLib.ast import STATNameStatement from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_lookup, ) from fontTools.otlLib.error import OpenTypeLibError from functools import reduce import logging import copy def buildCoverage(glyphs, glyphMap): """Builds a coverage table. Coverage tables (as defined in the `OpenType spec <https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#coverage-table>`__) are used in all OpenType Layout lookups apart from the Extension type, and define the glyphs involved in a layout subtable. This allows shaping engines to compare the glyph stream with the coverage table and quickly determine whether a subtable should be involved in a shaping operation. This function takes a list of glyphs and a glyphname-to-ID map, and returns a ``Coverage`` object representing the coverage table. Example:: glyphMap = font.getReverseGlyphMap() glyphs = [ "A", "B", "C" ] coverage = buildCoverage(glyphs, glyphMap) Args: glyphs: a sequence of glyph names. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.Coverage`` object or ``None`` if there are no glyphs supplied. """ if not glyphs: return None self = ot.Coverage() self.glyphs = sorted(set(glyphs), key=glyphMap.__getitem__) return self The provided code snippet includes necessary dependencies for implementing the `buildCursivePosSubtable` function. Write a Python function `def buildCursivePosSubtable(attach, glyphMap)` to solve the following problem: Builds a cursive positioning (GPOS3) subtable. Cursive positioning lookups are made up of a coverage table of glyphs, and a set of ``EntryExitRecord`` records containing the anchors for each glyph. This function builds the cursive positioning subtable. Example:: subtable = buildCursivePosSubtable({ "AlifIni": (None, buildAnchor(0, 50)), "BehMed": (buildAnchor(500,250), buildAnchor(0,50)), # ... }, font.getReverseGlyphMap()) Args: attach (dict): A mapping between glyph names and a tuple of two ``otTables.Anchor`` objects representing entry and exit anchors. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.CursivePos`` object, or ``None`` if the attachment dictionary was empty. Here is the function: def buildCursivePosSubtable(attach, glyphMap): """Builds a cursive positioning (GPOS3) subtable. Cursive positioning lookups are made up of a coverage table of glyphs, and a set of ``EntryExitRecord`` records containing the anchors for each glyph. This function builds the cursive positioning subtable. Example:: subtable = buildCursivePosSubtable({ "AlifIni": (None, buildAnchor(0, 50)), "BehMed": (buildAnchor(500,250), buildAnchor(0,50)), # ... }, font.getReverseGlyphMap()) Args: attach (dict): A mapping between glyph names and a tuple of two ``otTables.Anchor`` objects representing entry and exit anchors. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.CursivePos`` object, or ``None`` if the attachment dictionary was empty. """ if not attach: return None self = ot.CursivePos() self.Format = 1 self.Coverage = buildCoverage(attach.keys(), glyphMap) self.EntryExitRecord = [] for glyph in self.Coverage.glyphs: entryAnchor, exitAnchor = attach[glyph] rec = ot.EntryExitRecord() rec.EntryAnchor = entryAnchor rec.ExitAnchor = exitAnchor self.EntryExitRecord.append(rec) self.EntryExitCount = len(self.EntryExitRecord) return self
Builds a cursive positioning (GPOS3) subtable. Cursive positioning lookups are made up of a coverage table of glyphs, and a set of ``EntryExitRecord`` records containing the anchors for each glyph. This function builds the cursive positioning subtable. Example:: subtable = buildCursivePosSubtable({ "AlifIni": (None, buildAnchor(0, 50)), "BehMed": (buildAnchor(500,250), buildAnchor(0,50)), # ... }, font.getReverseGlyphMap()) Args: attach (dict): A mapping between glyph names and a tuple of two ``otTables.Anchor`` objects representing entry and exit anchors. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.CursivePos`` object, or ``None`` if the attachment dictionary was empty.
175,357
from collections import namedtuple, OrderedDict import os from fontTools.misc.fixedTools import fixedToFloat from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables.otBase import ( ValueRecord, valueRecordFormatDict, OTTableWriter, CountReference, ) from fontTools.ttLib.tables import otBase from fontTools.feaLib.ast import STATNameStatement from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_lookup, ) from fontTools.otlLib.error import OpenTypeLibError from functools import reduce import logging import copy The provided code snippet includes necessary dependencies for implementing the `buildDevice` function. Write a Python function `def buildDevice(deltas)` to solve the following problem: Builds a Device record as part of a ValueRecord or Anchor. Device tables specify size-specific adjustments to value records and anchors to reflect changes based on the resolution of the output. For example, one could specify that an anchor's Y position should be increased by 1 pixel when displayed at 8 pixels per em. This routine builds device records. Args: deltas: A dictionary mapping pixels-per-em sizes to the delta adjustment in pixels when the font is displayed at that size. Returns: An ``otTables.Device`` object if any deltas were supplied, or ``None`` otherwise. Here is the function: def buildDevice(deltas): """Builds a Device record as part of a ValueRecord or Anchor. Device tables specify size-specific adjustments to value records and anchors to reflect changes based on the resolution of the output. For example, one could specify that an anchor's Y position should be increased by 1 pixel when displayed at 8 pixels per em. This routine builds device records. Args: deltas: A dictionary mapping pixels-per-em sizes to the delta adjustment in pixels when the font is displayed at that size. Returns: An ``otTables.Device`` object if any deltas were supplied, or ``None`` otherwise. """ if not deltas: return None self = ot.Device() keys = deltas.keys() self.StartSize = startSize = min(keys) self.EndSize = endSize = max(keys) assert 0 <= startSize <= endSize self.DeltaValue = deltaValues = [ deltas.get(size, 0) for size in range(startSize, endSize + 1) ] maxDelta = max(deltaValues) minDelta = min(deltaValues) assert minDelta > -129 and maxDelta < 128 if minDelta > -3 and maxDelta < 2: self.DeltaFormat = 1 elif minDelta > -9 and maxDelta < 8: self.DeltaFormat = 2 else: self.DeltaFormat = 3 return self
Builds a Device record as part of a ValueRecord or Anchor. Device tables specify size-specific adjustments to value records and anchors to reflect changes based on the resolution of the output. For example, one could specify that an anchor's Y position should be increased by 1 pixel when displayed at 8 pixels per em. This routine builds device records. Args: deltas: A dictionary mapping pixels-per-em sizes to the delta adjustment in pixels when the font is displayed at that size. Returns: An ``otTables.Device`` object if any deltas were supplied, or ``None`` otherwise.
175,358
from collections import namedtuple, OrderedDict import os from fontTools.misc.fixedTools import fixedToFloat from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables.otBase import ( ValueRecord, valueRecordFormatDict, OTTableWriter, CountReference, ) from fontTools.ttLib.tables import otBase from fontTools.feaLib.ast import STATNameStatement from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_lookup, ) from fontTools.otlLib.error import OpenTypeLibError from functools import reduce import logging import copy def buildMarkBasePosSubtable(marks, bases, glyphMap): """Build a single MarkBasePos (GPOS4) subtable. This builds a mark-to-base lookup subtable containing all of the referenced marks and bases. See :func:`buildMarkBasePos`. Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. (See :func:`buildMarkArray`.) bases (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being dictionaries mapping mark class ID to the appropriate ``otTables.Anchor`` object used for attaching marks of that class. (See :func:`buildBaseArray`.) glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A ``otTables.MarkBasePos`` object. """ self = ot.MarkBasePos() self.Format = 1 self.MarkCoverage = buildCoverage(marks, glyphMap) self.MarkArray = buildMarkArray(marks, glyphMap) self.ClassCount = max([mc for mc, _ in marks.values()]) + 1 self.BaseCoverage = buildCoverage(bases, glyphMap) self.BaseArray = buildBaseArray(bases, self.ClassCount, glyphMap) return self The provided code snippet includes necessary dependencies for implementing the `buildMarkBasePos` function. Write a Python function `def buildMarkBasePos(marks, bases, glyphMap)` to solve the following problem: Build a list of MarkBasePos (GPOS4) subtables. This routine turns a set of marks and bases into a list of mark-to-base positioning subtables. Currently the list will contain a single subtable containing all marks and bases, although at a later date it may return the optimal list of subtables subsetting the marks and bases into groups which save space. See :func:`buildMarkBasePosSubtable` below. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MarkBasePosBuilder` instead. Example:: # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ... marks = {"acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2)} bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}} markbaseposes = buildMarkBasePos(marks, bases, font.getReverseGlyphMap()) Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. (See :func:`buildMarkArray`.) bases (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being dictionaries mapping mark class ID to the appropriate ``otTables.Anchor`` object used for attaching marks of that class. (See :func:`buildBaseArray`.) glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.MarkBasePos`` objects. Here is the function: def buildMarkBasePos(marks, bases, glyphMap): """Build a list of MarkBasePos (GPOS4) subtables. This routine turns a set of marks and bases into a list of mark-to-base positioning subtables. Currently the list will contain a single subtable containing all marks and bases, although at a later date it may return the optimal list of subtables subsetting the marks and bases into groups which save space. See :func:`buildMarkBasePosSubtable` below. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MarkBasePosBuilder` instead. Example:: # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ... marks = {"acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2)} bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}} markbaseposes = buildMarkBasePos(marks, bases, font.getReverseGlyphMap()) Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. (See :func:`buildMarkArray`.) bases (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being dictionaries mapping mark class ID to the appropriate ``otTables.Anchor`` object used for attaching marks of that class. (See :func:`buildBaseArray`.) glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.MarkBasePos`` objects. """ # TODO: Consider emitting multiple subtables to save space. # Partition the marks and bases into disjoint subsets, so that # MarkBasePos rules would only access glyphs from a single # subset. This would likely lead to smaller mark/base # matrices, so we might be able to omit many of the empty # anchor tables that we currently produce. Of course, this # would only work if the MarkBasePos rules of real-world fonts # allow partitioning into multiple subsets. We should find out # whether this is the case; if so, implement the optimization. # On the other hand, a very large number of subtables could # slow down layout engines; so this would need profiling. return [buildMarkBasePosSubtable(marks, bases, glyphMap)]
Build a list of MarkBasePos (GPOS4) subtables. This routine turns a set of marks and bases into a list of mark-to-base positioning subtables. Currently the list will contain a single subtable containing all marks and bases, although at a later date it may return the optimal list of subtables subsetting the marks and bases into groups which save space. See :func:`buildMarkBasePosSubtable` below. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MarkBasePosBuilder` instead. Example:: # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ... marks = {"acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2)} bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}} markbaseposes = buildMarkBasePos(marks, bases, font.getReverseGlyphMap()) Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. (See :func:`buildMarkArray`.) bases (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being dictionaries mapping mark class ID to the appropriate ``otTables.Anchor`` object used for attaching marks of that class. (See :func:`buildBaseArray`.) glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.MarkBasePos`` objects.
175,359
from collections import namedtuple, OrderedDict import os from fontTools.misc.fixedTools import fixedToFloat from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables.otBase import ( ValueRecord, valueRecordFormatDict, OTTableWriter, CountReference, ) from fontTools.ttLib.tables import otBase from fontTools.feaLib.ast import STATNameStatement from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_lookup, ) from fontTools.otlLib.error import OpenTypeLibError from functools import reduce import logging import copy def buildMarkLigPosSubtable(marks, ligs, glyphMap): """Build a single MarkLigPos (GPOS5) subtable. This builds a mark-to-base lookup subtable containing all of the referenced marks and bases. See :func:`buildMarkLigPos`. Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. (See :func:`buildMarkArray`.) ligs (dict): A mapping of ligature names to an array of dictionaries: for each component glyph in the ligature, an dictionary mapping mark class IDs to anchors. (See :func:`buildLigatureArray`.) glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A ``otTables.MarkLigPos`` object. """ self = ot.MarkLigPos() self.Format = 1 self.MarkCoverage = buildCoverage(marks, glyphMap) self.MarkArray = buildMarkArray(marks, glyphMap) self.ClassCount = max([mc for mc, _ in marks.values()]) + 1 self.LigatureCoverage = buildCoverage(ligs, glyphMap) self.LigatureArray = buildLigatureArray(ligs, self.ClassCount, glyphMap) return self The provided code snippet includes necessary dependencies for implementing the `buildMarkLigPos` function. Write a Python function `def buildMarkLigPos(marks, ligs, glyphMap)` to solve the following problem: Build a list of MarkLigPos (GPOS5) subtables. This routine turns a set of marks and ligatures into a list of mark-to-ligature positioning subtables. Currently the list will contain a single subtable containing all marks and ligatures, although at a later date it may return the optimal list of subtables subsetting the marks and ligatures into groups which save space. See :func:`buildMarkLigPosSubtable` below. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MarkLigPosBuilder` instead. Example:: # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ... marks = { "acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2) } ligs = { "f_i": [ { 0: a3, 1: a5 }, # f { 0: a4, 1: a5 } # i ], # "c_t": [{...}, {...}] } markligposes = buildMarkLigPos(marks, ligs, font.getReverseGlyphMap()) Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. (See :func:`buildMarkArray`.) ligs (dict): A mapping of ligature names to an array of dictionaries: for each component glyph in the ligature, an dictionary mapping mark class IDs to anchors. (See :func:`buildLigatureArray`.) glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.MarkLigPos`` objects. Here is the function: def buildMarkLigPos(marks, ligs, glyphMap): """Build a list of MarkLigPos (GPOS5) subtables. This routine turns a set of marks and ligatures into a list of mark-to-ligature positioning subtables. Currently the list will contain a single subtable containing all marks and ligatures, although at a later date it may return the optimal list of subtables subsetting the marks and ligatures into groups which save space. See :func:`buildMarkLigPosSubtable` below. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MarkLigPosBuilder` instead. Example:: # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ... marks = { "acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2) } ligs = { "f_i": [ { 0: a3, 1: a5 }, # f { 0: a4, 1: a5 } # i ], # "c_t": [{...}, {...}] } markligposes = buildMarkLigPos(marks, ligs, font.getReverseGlyphMap()) Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. (See :func:`buildMarkArray`.) ligs (dict): A mapping of ligature names to an array of dictionaries: for each component glyph in the ligature, an dictionary mapping mark class IDs to anchors. (See :func:`buildLigatureArray`.) glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.MarkLigPos`` objects. """ # TODO: Consider splitting into multiple subtables to save space, # as with MarkBasePos, this would be a trade-off that would need # profiling. And, depending on how typical fonts are structured, # it might not be worth doing at all. return [buildMarkLigPosSubtable(marks, ligs, glyphMap)]
Build a list of MarkLigPos (GPOS5) subtables. This routine turns a set of marks and ligatures into a list of mark-to-ligature positioning subtables. Currently the list will contain a single subtable containing all marks and ligatures, although at a later date it may return the optimal list of subtables subsetting the marks and ligatures into groups which save space. See :func:`buildMarkLigPosSubtable` below. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MarkLigPosBuilder` instead. Example:: # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ... marks = { "acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2) } ligs = { "f_i": [ { 0: a3, 1: a5 }, # f { 0: a4, 1: a5 } # i ], # "c_t": [{...}, {...}] } markligposes = buildMarkLigPos(marks, ligs, font.getReverseGlyphMap()) Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. (See :func:`buildMarkArray`.) ligs (dict): A mapping of ligature names to an array of dictionaries: for each component glyph in the ligature, an dictionary mapping mark class IDs to anchors. (See :func:`buildLigatureArray`.) glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.MarkLigPos`` objects.
175,360
from collections import namedtuple, OrderedDict import os from fontTools.misc.fixedTools import fixedToFloat from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables.otBase import ( ValueRecord, valueRecordFormatDict, OTTableWriter, CountReference, ) from fontTools.ttLib.tables import otBase from fontTools.feaLib.ast import STATNameStatement from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_lookup, ) from fontTools.otlLib.error import OpenTypeLibError from functools import reduce import logging import copy def buildMark2Record(anchors): # [otTables.Anchor, otTables.Anchor, ...] --> otTables.Mark2Record self = ot.Mark2Record() self.Mark2Anchor = anchors return self
null
175,361
from collections import namedtuple, OrderedDict import os from fontTools.misc.fixedTools import fixedToFloat from fontTools import ttLib from fontTools.ttLib.tables import otTables as ot from fontTools.ttLib.tables.otBase import ( ValueRecord, valueRecordFormatDict, OTTableWriter, CountReference, ) from fontTools.ttLib.tables import otBase from fontTools.feaLib.ast import STATNameStatement from fontTools.otlLib.optimize.gpos import ( _compression_level_from_env, compact_lookup, ) from fontTools.otlLib.error import OpenTypeLibError from functools import reduce import logging import copy def buildPairPosGlyphsSubtable(pairs, glyphMap, valueFormat1=None, valueFormat2=None): """Builds a single glyph-based pair adjustment (GPOS2 format 1) subtable. This builds a PairPos subtable from a dictionary of glyph pairs and their positioning adjustments. See also :func:`buildPairPosGlyphs`. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder` instead. Example:: pairs = { ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ), ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ), # ... } pairpos = buildPairPosGlyphsSubtable(pairs, font.getReverseGlyphMap()) Args: pairs (dict): Pair positioning data; the keys being a two-element tuple of glyphnames, and the values being a two-element tuple of ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. valueFormat1: Force the "left" value records to the given format. valueFormat2: Force the "right" value records to the given format. Returns: A ``otTables.PairPos`` object. """ self = ot.PairPos() self.Format = 1 valueFormat1 = self.ValueFormat1 = _getValueFormat(valueFormat1, pairs.values(), 0) valueFormat2 = self.ValueFormat2 = _getValueFormat(valueFormat2, pairs.values(), 1) p = {} for (glyphA, glyphB), (valA, valB) in pairs.items(): p.setdefault(glyphA, []).append((glyphB, valA, valB)) self.Coverage = buildCoverage({g for g, _ in pairs.keys()}, glyphMap) self.PairSet = [] for glyph in self.Coverage.glyphs: ps = ot.PairSet() ps.PairValueRecord = [] self.PairSet.append(ps) for glyph2, val1, val2 in sorted(p[glyph], key=lambda x: glyphMap[x[0]]): pvr = ot.PairValueRecord() pvr.SecondGlyph = glyph2 pvr.Value1 = ( ValueRecord(src=val1, valueFormat=valueFormat1) if valueFormat1 else None ) pvr.Value2 = ( ValueRecord(src=val2, valueFormat=valueFormat2) if valueFormat2 else None ) ps.PairValueRecord.append(pvr) ps.PairValueCount = len(ps.PairValueRecord) self.PairSetCount = len(self.PairSet) return self The provided code snippet includes necessary dependencies for implementing the `buildPairPosGlyphs` function. Write a Python function `def buildPairPosGlyphs(pairs, glyphMap)` to solve the following problem: Builds a list of glyph-based pair adjustment (GPOS2 format 1) subtables. This organises a list of pair positioning adjustments into subtables based on common value record formats. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder` instead. Example:: pairs = { ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ), ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ), # ... } subtables = buildPairPosGlyphs(pairs, font.getReverseGlyphMap()) Args: pairs (dict): Pair positioning data; the keys being a two-element tuple of glyphnames, and the values being a two-element tuple of ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.PairPos`` objects. Here is the function: def buildPairPosGlyphs(pairs, glyphMap): """Builds a list of glyph-based pair adjustment (GPOS2 format 1) subtables. This organises a list of pair positioning adjustments into subtables based on common value record formats. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder` instead. Example:: pairs = { ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ), ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ), # ... } subtables = buildPairPosGlyphs(pairs, font.getReverseGlyphMap()) Args: pairs (dict): Pair positioning data; the keys being a two-element tuple of glyphnames, and the values being a two-element tuple of ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.PairPos`` objects. """ p = {} # (formatA, formatB) --> {(glyphA, glyphB): (valA, valB)} for (glyphA, glyphB), (valA, valB) in pairs.items(): formatA = valA.getFormat() if valA is not None else 0 formatB = valB.getFormat() if valB is not None else 0 pos = p.setdefault((formatA, formatB), {}) pos[(glyphA, glyphB)] = (valA, valB) return [ buildPairPosGlyphsSubtable(pos, glyphMap, formatA, formatB) for ((formatA, formatB), pos) in sorted(p.items()) ]
Builds a list of glyph-based pair adjustment (GPOS2 format 1) subtables. This organises a list of pair positioning adjustments into subtables based on common value record formats. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder` instead. Example:: pairs = { ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ), ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ), # ... } subtables = buildPairPosGlyphs(pairs, font.getReverseGlyphMap()) Args: pairs (dict): Pair positioning data; the keys being a two-element tuple of glyphnames, and the values being a two-element tuple of ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.PairPos`` objects.