fonttools/Lib/fontTools/subset.py

2154 lines
75 KiB
Python
Raw Normal View History

2013-07-23 11:17:35 -04:00
# Copyright 2013 Google, Inc. All Rights Reserved.
#
# Google Author(s): Behdad Esfahbod
2013-08-13 20:02:59 -04:00
"""Python OpenType Layout Subsetter.
Later grown into full OpenType subsetter, supporting all standard tables.
"""
2013-08-13 20:25:37 -04:00
import sys
import struct
2013-08-13 20:25:37 -04:00
import time
import array
2013-08-13 20:25:37 -04:00
2013-08-19 14:44:49 -04:00
import fontTools.ttLib
import fontTools.ttLib.tables
import fontTools.ttLib.tables.otTables
import fontTools.cffLib
import fontTools.misc.psCharStrings
import fontTools.pens.basePen
2013-07-21 18:16:55 -04:00
2013-08-13 20:25:37 -04:00
def _add_method(*clazzes):
2013-08-13 20:02:59 -04:00
"""Returns a decorator function that adds a new method to one or
more classes."""
2013-08-13 19:53:30 -04:00
def wrapper(method):
2013-08-13 19:50:38 -04:00
for clazz in clazzes:
assert clazz.__name__ != 'DefaultTable', 'Oops, table class not found.'
2013-08-16 10:56:30 -04:00
assert not hasattr(clazz, method.func_name), \
"Oops, class '%s' has method '%s'." % (clazz.__name__,
method.func_name)
2013-08-13 19:53:30 -04:00
setattr(clazz, method.func_name, method)
2013-08-13 19:50:38 -04:00
return None
return wrapper
2013-07-21 18:16:55 -04:00
2013-08-13 20:25:37 -04:00
def _uniq_sort(l):
2013-08-13 19:53:30 -04:00
return sorted(set(l))
def _set_update(s, *others):
# Jython's set.update only takes one other argument.
# Emulate real set.update...
for other in others:
s.update(other)
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Coverage)
2013-08-13 19:53:30 -04:00
def intersect(self, glyphs):
2013-08-13 19:50:38 -04:00
"Returns ascending list of matching coverage values."
2013-08-14 19:47:42 -04:00
return [i for i,g in enumerate(self.glyphs) if g in glyphs]
2013-07-23 14:52:18 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Coverage)
2013-08-13 19:53:30 -04:00
def intersect_glyphs(self, glyphs):
2013-08-13 19:50:38 -04:00
"Returns set of intersecting glyphs."
2013-08-13 19:53:30 -04:00
return set(g for g in self.glyphs if g in glyphs)
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Coverage)
2013-08-13 19:53:30 -04:00
def subset(self, glyphs):
2013-08-13 19:50:38 -04:00
"Returns ascending list of remaining coverage values."
2013-08-13 19:53:30 -04:00
indices = self.intersect(glyphs)
2013-08-13 19:50:38 -04:00
self.glyphs = [g for g in self.glyphs if g in glyphs]
return indices
2013-07-21 23:15:32 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Coverage)
2013-08-13 19:53:30 -04:00
def remap(self, coverage_map):
2013-08-13 19:50:38 -04:00
"Remaps coverage."
self.glyphs = [self.glyphs[i] for i in coverage_map]
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ClassDef)
2013-08-13 19:53:30 -04:00
def intersect(self, glyphs):
2013-08-13 19:50:38 -04:00
"Returns ascending list of matching class values."
2013-08-13 20:25:37 -04:00
return _uniq_sort(
2013-08-13 19:53:30 -04:00
([0] if any(g not in self.classDefs for g in glyphs) else []) +
2013-08-13 19:50:38 -04:00
[v for g,v in self.classDefs.iteritems() if g in glyphs])
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ClassDef)
2013-08-13 19:53:30 -04:00
def intersect_class(self, glyphs, klass):
2013-08-13 19:50:38 -04:00
"Returns set of glyphs matching class."
if klass == 0:
2013-08-13 19:53:30 -04:00
return set(g for g in glyphs if g not in self.classDefs)
return set(g for g,v in self.classDefs.iteritems()
2013-08-13 19:50:38 -04:00
if v == klass and g in glyphs)
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ClassDef)
2013-08-13 19:53:30 -04:00
def subset(self, glyphs, remap=False):
2013-08-13 19:50:38 -04:00
"Returns ascending list of remaining classes."
2013-08-16 10:58:25 -04:00
self.classDefs = dict((g,v) for g,v in self.classDefs.iteritems() if g in glyphs)
2013-08-13 19:50:38 -04:00
# Note: while class 0 has the special meaning of "not matched",
# if no glyph will ever /not match/, we can optimize class 0 out too.
2013-08-13 20:25:37 -04:00
indices = _uniq_sort(
2013-08-13 19:53:30 -04:00
([0] if any(g not in self.classDefs for g in glyphs) else []) +
2013-08-14 19:49:53 -04:00
self.classDefs.values())
2013-08-13 19:50:38 -04:00
if remap:
2013-08-13 19:53:30 -04:00
self.remap(indices)
2013-08-13 19:50:38 -04:00
return indices
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ClassDef)
2013-08-13 19:53:30 -04:00
def remap(self, class_map):
2013-08-13 19:50:38 -04:00
"Remaps classes."
2013-08-16 10:58:25 -04:00
self.classDefs = dict((g,class_map.index(v))
for g,v in self.classDefs.iteritems())
2013-07-21 23:15:32 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.SingleSubst)
2013-08-13 19:53:30 -04:00
def closure_glyphs(self, s, cur_glyphs=None):
2013-08-13 19:50:38 -04:00
if cur_glyphs == None: cur_glyphs = s.glyphs
if self.Format in [1, 2]:
2013-08-13 19:53:30 -04:00
s.glyphs.update(v for g,v in self.mapping.iteritems() if g in cur_glyphs)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-23 14:52:18 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.SingleSubst)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
if self.Format in [1, 2]:
2013-08-16 10:58:25 -04:00
self.mapping = dict((g,v) for g,v in self.mapping.iteritems()
if g in s.glyphs and v in s.glyphs)
2013-08-13 19:53:30 -04:00
return bool(self.mapping)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-21 18:16:55 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
2013-08-13 19:53:30 -04:00
def closure_glyphs(self, s, cur_glyphs=None):
2013-08-13 19:50:38 -04:00
if cur_glyphs == None: cur_glyphs = s.glyphs
if self.Format == 1:
2013-08-13 19:53:30 -04:00
indices = self.Coverage.intersect(cur_glyphs)
2013-08-16 16:21:25 -04:00
_set_update(s.glyphs, *(self.Sequence[i].Substitute for i in indices))
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-23 14:52:18 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
indices = self.Coverage.subset(s.glyphs)
2013-08-13 19:50:38 -04:00
self.Sequence = [self.Sequence[i] for i in indices]
# Now drop rules generating glyphs we don't want
2013-08-13 19:53:30 -04:00
indices = [i for i,seq in enumerate(self.Sequence)
if all(sub in s.glyphs for sub in seq.Substitute)]
2013-08-13 19:50:38 -04:00
self.Sequence = [self.Sequence[i] for i in indices]
2013-08-13 19:53:30 -04:00
self.Coverage.remap(indices)
self.SequenceCount = len(self.Sequence)
return bool(self.SequenceCount)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-21 18:16:55 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
2013-08-13 19:53:30 -04:00
def closure_glyphs(self, s, cur_glyphs=None):
2013-08-13 19:50:38 -04:00
if cur_glyphs == None: cur_glyphs = s.glyphs
if self.Format == 1:
_set_update(s.glyphs, *(vlist for g,vlist in self.alternates.iteritems()
if g in cur_glyphs))
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-23 14:52:18 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-16 10:58:25 -04:00
self.alternates = dict((g,vlist)
for g,vlist in self.alternates.iteritems()
if g in s.glyphs and
all(v in s.glyphs for v in vlist))
2013-08-13 19:53:30 -04:00
return bool(self.alternates)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-21 18:16:55 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
2013-08-13 19:53:30 -04:00
def closure_glyphs(self, s, cur_glyphs=None):
2013-08-13 19:50:38 -04:00
if cur_glyphs == None: cur_glyphs = s.glyphs
if self.Format == 1:
_set_update(s.glyphs, *([seq.LigGlyph for seq in seqs
if all(c in s.glyphs for c in seq.Component)]
for g,seqs in self.ligatures.iteritems()
if g in cur_glyphs))
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-23 14:52:18 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-16 10:58:25 -04:00
self.ligatures = dict((g,v) for g,v in self.ligatures.iteritems()
if g in s.glyphs)
self.ligatures = dict((g,[seq for seq in seqs
if seq.LigGlyph in s.glyphs and
all(c in s.glyphs for c in seq.Component)])
for g,seqs in self.ligatures.iteritems())
self.ligatures = dict((g,v) for g,v in self.ligatures.iteritems() if v)
2013-08-13 19:53:30 -04:00
return bool(self.ligatures)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-21 18:16:55 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
2013-08-13 19:53:30 -04:00
def closure_glyphs(self, s, cur_glyphs=None):
2013-08-13 19:50:38 -04:00
if cur_glyphs == None: cur_glyphs = s.glyphs
if self.Format == 1:
2013-08-13 19:53:30 -04:00
indices = self.Coverage.intersect(cur_glyphs)
if(not indices or
not all(c.intersect(s.glyphs)
2013-08-13 19:50:38 -04:00
for c in self.LookAheadCoverage + self.BacktrackCoverage)):
return
2013-08-13 19:53:30 -04:00
s.glyphs.update(self.Substitute[i] for i in indices)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-23 14:52:18 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
indices = self.Coverage.subset(s.glyphs)
2013-08-13 19:50:38 -04:00
self.Substitute = [self.Substitute[i] for i in indices]
# Now drop rules generating glyphs we don't want
2013-08-13 19:53:30 -04:00
indices = [i for i,sub in enumerate(self.Substitute)
2013-08-13 19:50:38 -04:00
if sub in s.glyphs]
self.Substitute = [self.Substitute[i] for i in indices]
2013-08-13 19:53:30 -04:00
self.Coverage.remap(indices)
self.GlyphCount = len(self.Substitute)
return bool(self.GlyphCount and
all(c.subset(s.glyphs)
2013-08-13 19:50:38 -04:00
for c in self.LookAheadCoverage+self.BacktrackCoverage))
else:
assert 0, "unknown format: %s" % self.Format
2013-07-21 18:16:55 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.SinglePos)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
return len(self.Coverage.subset(s.glyphs))
2013-08-13 19:50:38 -04:00
elif self.Format == 2:
2013-08-13 19:53:30 -04:00
indices = self.Coverage.subset(s.glyphs)
2013-08-13 19:50:38 -04:00
self.Value = [self.Value[i] for i in indices]
2013-08-13 19:53:30 -04:00
self.ValueCount = len(self.Value)
return bool(self.ValueCount)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-21 18:16:55 -04:00
@_add_method(fontTools.ttLib.tables.otTables.SinglePos)
def prune_post_subset(self, options):
if not options.hinting:
# Drop device tables
self.ValueFormat &= ~0x00F0
return True
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.PairPos)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
indices = self.Coverage.subset(s.glyphs)
2013-08-13 19:50:38 -04:00
self.PairSet = [self.PairSet[i] for i in indices]
for p in self.PairSet:
p.PairValueRecord = [r for r in p.PairValueRecord
if r.SecondGlyph in s.glyphs]
2013-08-13 19:53:30 -04:00
p.PairValueCount = len(p.PairValueRecord)
2013-08-13 19:50:38 -04:00
self.PairSet = [p for p in self.PairSet if p.PairValueCount]
2013-08-13 19:53:30 -04:00
self.PairSetCount = len(self.PairSet)
return bool(self.PairSetCount)
2013-08-13 19:50:38 -04:00
elif self.Format == 2:
2013-08-13 19:53:30 -04:00
class1_map = self.ClassDef1.subset(s.glyphs, remap=True)
class2_map = self.ClassDef2.subset(s.glyphs, remap=True)
2013-08-13 19:50:38 -04:00
self.Class1Record = [self.Class1Record[i] for i in class1_map]
for c in self.Class1Record:
c.Class2Record = [c.Class2Record[i] for i in class2_map]
2013-08-13 19:53:30 -04:00
self.Class1Count = len(class1_map)
self.Class2Count = len(class2_map)
return bool(self.Class1Count and
2013-08-13 19:50:38 -04:00
self.Class2Count and
2013-08-13 19:53:30 -04:00
self.Coverage.subset(s.glyphs))
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-21 18:16:55 -04:00
@_add_method(fontTools.ttLib.tables.otTables.PairPos)
def prune_post_subset(self, options):
if not options.hinting:
# Drop device tables
self.ValueFormat1 &= ~0x00F0
self.ValueFormat2 &= ~0x00F0
return True
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.CursivePos)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
indices = self.Coverage.subset(s.glyphs)
2013-08-13 19:50:38 -04:00
self.EntryExitRecord = [self.EntryExitRecord[i] for i in indices]
2013-08-13 19:53:30 -04:00
self.EntryExitCount = len(self.EntryExitRecord)
return bool(self.EntryExitCount)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-21 18:16:55 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Anchor)
def prune_hints(self):
# Drop device tables / contour anchor point
self.Format = 1
@_add_method(fontTools.ttLib.tables.otTables.CursivePos)
def prune_post_subset(self, options):
if not options.hinting:
for rec in self.EntryExitRecord:
if rec.EntryAnchor: rec.EntryAnchor.prune_hints()
if rec.ExitAnchor: rec.ExitAnchor.prune_hints()
return True
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.MarkBasePos)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
mark_indices = self.MarkCoverage.subset(s.glyphs)
2013-08-13 19:50:38 -04:00
self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i]
for i in mark_indices]
2013-08-13 19:53:30 -04:00
self.MarkArray.MarkCount = len(self.MarkArray.MarkRecord)
base_indices = self.BaseCoverage.subset(s.glyphs)
2013-08-13 19:50:38 -04:00
self.BaseArray.BaseRecord = [self.BaseArray.BaseRecord[i]
for i in base_indices]
2013-08-13 19:53:30 -04:00
self.BaseArray.BaseCount = len(self.BaseArray.BaseRecord)
2013-08-13 19:50:38 -04:00
# Prune empty classes
2013-08-13 20:25:37 -04:00
class_indices = _uniq_sort(v.Class for v in self.MarkArray.MarkRecord)
2013-08-13 19:53:30 -04:00
self.ClassCount = len(class_indices)
2013-08-13 19:50:38 -04:00
for m in self.MarkArray.MarkRecord:
2013-08-13 19:53:30 -04:00
m.Class = class_indices.index(m.Class)
2013-08-13 19:50:38 -04:00
for b in self.BaseArray.BaseRecord:
b.BaseAnchor = [b.BaseAnchor[i] for i in class_indices]
2013-08-13 19:53:30 -04:00
return bool(self.ClassCount and
2013-08-13 19:50:38 -04:00
self.MarkArray.MarkCount and
self.BaseArray.BaseCount)
else:
assert 0, "unknown format: %s" % self.Format
2013-07-21 18:16:55 -04:00
@_add_method(fontTools.ttLib.tables.otTables.MarkBasePos)
def prune_post_subset(self, options):
if not options.hinting:
for m in self.MarkArray.MarkRecord:
m.MarkAnchor.prune_hints()
for b in self.BaseArray.BaseRecord:
for a in b.BaseAnchor:
a.prune_hints()
return True
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.MarkLigPos)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
mark_indices = self.MarkCoverage.subset(s.glyphs)
2013-08-13 19:50:38 -04:00
self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i]
for i in mark_indices]
2013-08-13 19:53:30 -04:00
self.MarkArray.MarkCount = len(self.MarkArray.MarkRecord)
ligature_indices = self.LigatureCoverage.subset(s.glyphs)
2013-08-13 19:50:38 -04:00
self.LigatureArray.LigatureAttach = [self.LigatureArray.LigatureAttach[i]
for i in ligature_indices]
2013-08-13 19:53:30 -04:00
self.LigatureArray.LigatureCount = len(self.LigatureArray.LigatureAttach)
2013-08-13 19:50:38 -04:00
# Prune empty classes
2013-08-13 20:25:37 -04:00
class_indices = _uniq_sort(v.Class for v in self.MarkArray.MarkRecord)
2013-08-13 19:53:30 -04:00
self.ClassCount = len(class_indices)
2013-08-13 19:50:38 -04:00
for m in self.MarkArray.MarkRecord:
2013-08-13 19:53:30 -04:00
m.Class = class_indices.index(m.Class)
2013-08-13 19:50:38 -04:00
for l in self.LigatureArray.LigatureAttach:
for c in l.ComponentRecord:
c.LigatureAnchor = [c.LigatureAnchor[i] for i in class_indices]
2013-08-13 19:53:30 -04:00
return bool(self.ClassCount and
2013-08-13 19:50:38 -04:00
self.MarkArray.MarkCount and
self.LigatureArray.LigatureCount)
else:
assert 0, "unknown format: %s" % self.Format
2013-07-21 18:16:55 -04:00
@_add_method(fontTools.ttLib.tables.otTables.MarkLigPos)
def prune_post_subset(self, options):
if not options.hinting:
for m in self.MarkArray.MarkRecord:
m.MarkAnchor.prune_hints()
for l in self.LigatureArray.LigatureAttach:
for c in l.ComponentRecord:
for a in c.LigatureAnchor:
a.prune_hints()
return True
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.MarkMarkPos)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
mark1_indices = self.Mark1Coverage.subset(s.glyphs)
2013-08-13 19:50:38 -04:00
self.Mark1Array.MarkRecord = [self.Mark1Array.MarkRecord[i]
for i in mark1_indices]
2013-08-13 19:53:30 -04:00
self.Mark1Array.MarkCount = len(self.Mark1Array.MarkRecord)
mark2_indices = self.Mark2Coverage.subset(s.glyphs)
2013-08-13 19:50:38 -04:00
self.Mark2Array.Mark2Record = [self.Mark2Array.Mark2Record[i]
for i in mark2_indices]
2013-08-13 19:53:30 -04:00
self.Mark2Array.MarkCount = len(self.Mark2Array.Mark2Record)
2013-08-13 19:50:38 -04:00
# Prune empty classes
2013-08-13 20:25:37 -04:00
class_indices = _uniq_sort(v.Class for v in self.Mark1Array.MarkRecord)
2013-08-13 19:53:30 -04:00
self.ClassCount = len(class_indices)
2013-08-13 19:50:38 -04:00
for m in self.Mark1Array.MarkRecord:
2013-08-13 19:53:30 -04:00
m.Class = class_indices.index(m.Class)
2013-08-13 19:50:38 -04:00
for b in self.Mark2Array.Mark2Record:
b.Mark2Anchor = [b.Mark2Anchor[i] for i in class_indices]
2013-08-13 19:53:30 -04:00
return bool(self.ClassCount and
2013-08-13 19:50:38 -04:00
self.Mark1Array.MarkCount and
self.Mark2Array.MarkCount)
else:
assert 0, "unknown format: %s" % self.Format
2013-07-21 18:16:55 -04:00
@_add_method(fontTools.ttLib.tables.otTables.MarkMarkPos)
def prune_post_subset(self, options):
if not options.hinting:
# Drop device tables or contour anchor point
for m in self.Mark1Array.MarkRecord:
m.MarkAnchor.prune_hints()
for b in self.Mark2Array.Mark2Record:
for m in b.Mark2Anchor:
m.prune_hints()
return True
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.SingleSubst,
fontTools.ttLib.tables.otTables.MultipleSubst,
fontTools.ttLib.tables.otTables.AlternateSubst,
fontTools.ttLib.tables.otTables.LigatureSubst,
fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
fontTools.ttLib.tables.otTables.SinglePos,
fontTools.ttLib.tables.otTables.PairPos,
fontTools.ttLib.tables.otTables.CursivePos,
fontTools.ttLib.tables.otTables.MarkBasePos,
fontTools.ttLib.tables.otTables.MarkLigPos,
fontTools.ttLib.tables.otTables.MarkMarkPos)
2013-08-13 19:53:30 -04:00
def subset_lookups(self, lookup_indices):
2013-08-13 19:50:38 -04:00
pass
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.SingleSubst,
fontTools.ttLib.tables.otTables.MultipleSubst,
fontTools.ttLib.tables.otTables.AlternateSubst,
fontTools.ttLib.tables.otTables.LigatureSubst,
fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
fontTools.ttLib.tables.otTables.SinglePos,
fontTools.ttLib.tables.otTables.PairPos,
fontTools.ttLib.tables.otTables.CursivePos,
fontTools.ttLib.tables.otTables.MarkBasePos,
fontTools.ttLib.tables.otTables.MarkLigPos,
fontTools.ttLib.tables.otTables.MarkMarkPos)
2013-08-13 19:53:30 -04:00
def collect_lookups(self):
2013-08-13 19:50:38 -04:00
return []
@_add_method(fontTools.ttLib.tables.otTables.SingleSubst,
fontTools.ttLib.tables.otTables.MultipleSubst,
fontTools.ttLib.tables.otTables.AlternateSubst,
fontTools.ttLib.tables.otTables.LigatureSubst,
fontTools.ttLib.tables.otTables.ContextSubst,
fontTools.ttLib.tables.otTables.ChainContextSubst,
fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
fontTools.ttLib.tables.otTables.SinglePos,
fontTools.ttLib.tables.otTables.PairPos,
fontTools.ttLib.tables.otTables.CursivePos,
fontTools.ttLib.tables.otTables.MarkBasePos,
fontTools.ttLib.tables.otTables.MarkLigPos,
fontTools.ttLib.tables.otTables.MarkMarkPos,
fontTools.ttLib.tables.otTables.ContextPos,
fontTools.ttLib.tables.otTables.ChainContextPos)
def prune_pre_subset(self, options):
return True
@_add_method(fontTools.ttLib.tables.otTables.SingleSubst,
fontTools.ttLib.tables.otTables.MultipleSubst,
fontTools.ttLib.tables.otTables.AlternateSubst,
fontTools.ttLib.tables.otTables.LigatureSubst,
fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
fontTools.ttLib.tables.otTables.ContextSubst,
fontTools.ttLib.tables.otTables.ChainContextSubst,
fontTools.ttLib.tables.otTables.ContextPos,
fontTools.ttLib.tables.otTables.ChainContextPos)
def prune_post_subset(self, options):
return True
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.SingleSubst,
fontTools.ttLib.tables.otTables.AlternateSubst,
fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
2013-08-13 19:53:30 -04:00
def may_have_non_1to1(self):
2013-08-13 19:50:38 -04:00
return False
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.MultipleSubst,
fontTools.ttLib.tables.otTables.LigatureSubst,
fontTools.ttLib.tables.otTables.ContextSubst,
fontTools.ttLib.tables.otTables.ChainContextSubst)
2013-08-13 19:53:30 -04:00
def may_have_non_1to1(self):
2013-08-13 19:50:38 -04:00
return True
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ContextSubst,
fontTools.ttLib.tables.otTables.ChainContextSubst,
fontTools.ttLib.tables.otTables.ContextPos,
fontTools.ttLib.tables.otTables.ChainContextPos)
2013-08-13 19:53:30 -04:00
def __classify_context(self):
2013-07-23 22:51:50 -04:00
2013-08-13 20:10:17 -04:00
class ContextHelper(object):
2013-08-13 19:53:30 -04:00
def __init__(self, klass, Format):
if klass.__name__.endswith('Subst'):
2013-08-13 19:50:38 -04:00
Typ = 'Sub'
Type = 'Subst'
else:
Typ = 'Pos'
Type = 'Pos'
2013-08-13 19:53:30 -04:00
if klass.__name__.startswith('Chain'):
2013-08-13 19:50:38 -04:00
Chain = 'Chain'
else:
Chain = ''
ChainTyp = Chain+Typ
self.Typ = Typ
self.Type = Type
self.Chain = Chain
self.ChainTyp = ChainTyp
self.LookupRecord = Type+'LookupRecord'
if Format == 1:
Coverage = lambda r: r.Coverage
ChainCoverage = lambda r: r.Coverage
2013-08-13 19:53:30 -04:00
ContextData = lambda r:(None,)
ChainContextData = lambda r:(None, None, None)
RuleData = lambda r:(r.Input,)
ChainRuleData = lambda r:(r.Backtrack, r.Input, r.LookAhead)
2013-08-13 19:50:38 -04:00
SetRuleData = None
ChainSetRuleData = None
elif Format == 2:
Coverage = lambda r: r.Coverage
ChainCoverage = lambda r: r.Coverage
2013-08-13 19:53:30 -04:00
ContextData = lambda r:(r.ClassDef,)
ChainContextData = lambda r:(r.LookAheadClassDef,
2013-08-13 19:50:38 -04:00
r.InputClassDef,
r.BacktrackClassDef)
2013-08-13 19:53:30 -04:00
RuleData = lambda r:(r.Class,)
ChainRuleData = lambda r:(r.LookAhead, r.Input, r.Backtrack)
def SetRuleData(r, d):(r.Class,) = d
def ChainSetRuleData(r, d):(r.LookAhead, r.Input, r.Backtrack) = d
2013-08-13 19:50:38 -04:00
elif Format == 3:
Coverage = lambda r: r.Coverage[0]
ChainCoverage = lambda r: r.InputCoverage[0]
ContextData = None
ChainContextData = None
RuleData = lambda r: r.Coverage
2013-08-13 19:53:30 -04:00
ChainRuleData = lambda r:(r.LookAheadCoverage +
2013-08-13 19:50:38 -04:00
r.InputCoverage +
r.BacktrackCoverage)
SetRuleData = None
ChainSetRuleData = None
else:
assert 0, "unknown format: %s" % Format
if Chain:
self.Coverage = ChainCoverage
self.ContextData = ChainContextData
self.RuleData = ChainRuleData
self.SetRuleData = ChainSetRuleData
else:
self.Coverage = Coverage
self.ContextData = ContextData
self.RuleData = RuleData
self.SetRuleData = SetRuleData
if Format == 1:
self.Rule = ChainTyp+'Rule'
self.RuleCount = ChainTyp+'RuleCount'
self.RuleSet = ChainTyp+'RuleSet'
self.RuleSetCount = ChainTyp+'RuleSetCount'
self.Intersect = lambda glyphs, c, r: [r] if r in glyphs else []
elif Format == 2:
self.Rule = ChainTyp+'ClassRule'
self.RuleCount = ChainTyp+'ClassRuleCount'
self.RuleSet = ChainTyp+'ClassSet'
self.RuleSetCount = ChainTyp+'ClassSetCount'
2013-08-13 19:53:30 -04:00
self.Intersect = lambda glyphs, c, r: c.intersect_class(glyphs, r)
2013-08-13 19:50:38 -04:00
self.ClassDef = 'InputClassDef' if Chain else 'ClassDef'
2013-08-14 15:33:08 -04:00
self.Input = 'Input' if Chain else 'Class'
2013-08-13 19:50:38 -04:00
if self.Format not in [1, 2, 3]:
2013-08-13 20:09:28 -04:00
return None # Don't shoot the messenger; let it go
2013-08-13 19:53:30 -04:00
if not hasattr(self.__class__, "__ContextHelpers"):
2013-08-13 19:50:38 -04:00
self.__class__.__ContextHelpers = {}
if self.Format not in self.__class__.__ContextHelpers:
2013-08-13 19:53:30 -04:00
helper = ContextHelper(self.__class__, self.Format)
2013-08-13 19:50:38 -04:00
self.__class__.__ContextHelpers[self.Format] = helper
return self.__class__.__ContextHelpers[self.Format]
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ContextSubst,
fontTools.ttLib.tables.otTables.ChainContextSubst)
2013-08-13 19:53:30 -04:00
def closure_glyphs(self, s, cur_glyphs=None):
2013-08-13 19:50:38 -04:00
if cur_glyphs == None: cur_glyphs = s.glyphs
2013-08-13 19:53:30 -04:00
c = self.__classify_context()
2013-08-13 19:50:38 -04:00
2013-08-13 19:53:30 -04:00
indices = c.Coverage(self).intersect(s.glyphs)
2013-08-13 19:50:38 -04:00
if not indices:
return []
2013-08-13 19:53:30 -04:00
cur_glyphs = c.Coverage(self).intersect_glyphs(s.glyphs);
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
ContextData = c.ContextData(self)
rss = getattr(self, c.RuleSet)
2013-08-13 19:50:38 -04:00
for i in indices:
if not rss[i]: continue
2013-08-13 19:53:30 -04:00
for r in getattr(rss[i], c.Rule):
2013-08-13 19:50:38 -04:00
if not r: continue
2013-08-13 19:53:30 -04:00
if all(all(c.Intersect(s.glyphs, cd, k) for k in klist)
for cd,klist in zip(ContextData, c.RuleData(r))):
2013-08-13 19:50:38 -04:00
chaos = False
2013-08-13 19:53:30 -04:00
for ll in getattr(r, c.LookupRecord):
2013-08-13 19:50:38 -04:00
if not ll: continue
seqi = ll.SequenceIndex
if chaos:
pos_glyphs = s.glyphs
2013-08-13 19:50:38 -04:00
else:
if seqi == 0:
pos_glyphs = set([c.Coverage(self).glyphs[i]])
2013-08-13 19:50:38 -04:00
else:
pos_glyphs = set([r.Input[seqi - 1]])
2013-08-13 19:50:38 -04:00
lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
2013-08-13 19:53:30 -04:00
chaos = chaos or lookup.may_have_non_1to1()
lookup.closure_glyphs(s, cur_glyphs=pos_glyphs)
2013-08-13 19:50:38 -04:00
elif self.Format == 2:
2013-08-13 19:53:30 -04:00
ClassDef = getattr(self, c.ClassDef)
indices = ClassDef.intersect(cur_glyphs)
ContextData = c.ContextData(self)
rss = getattr(self, c.RuleSet)
2013-08-13 19:50:38 -04:00
for i in indices:
if not rss[i]: continue
2013-08-13 19:53:30 -04:00
for r in getattr(rss[i], c.Rule):
2013-08-13 19:50:38 -04:00
if not r: continue
2013-08-13 19:53:30 -04:00
if all(all(c.Intersect(s.glyphs, cd, k) for k in klist)
for cd,klist in zip(ContextData, c.RuleData(r))):
2013-08-13 19:50:38 -04:00
chaos = False
2013-08-13 19:53:30 -04:00
for ll in getattr(r, c.LookupRecord):
2013-08-13 19:50:38 -04:00
if not ll: continue
seqi = ll.SequenceIndex
if chaos:
pos_glyphs = s.glyphs
2013-08-13 19:50:38 -04:00
else:
if seqi == 0:
pos_glyphs = ClassDef.intersect_class(cur_glyphs, i)
2013-08-13 19:50:38 -04:00
else:
2013-08-13 19:53:30 -04:00
pos_glyphs = ClassDef.intersect_class(s.glyphs,
2013-08-14 15:33:08 -04:00
getattr(r, c.Input)[seqi - 1])
2013-08-13 19:50:38 -04:00
lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
2013-08-13 19:53:30 -04:00
chaos = chaos or lookup.may_have_non_1to1()
lookup.closure_glyphs(s, cur_glyphs=pos_glyphs)
2013-08-13 19:50:38 -04:00
elif self.Format == 3:
2013-08-13 19:53:30 -04:00
if not all(x.intersect(s.glyphs) for x in c.RuleData(self)):
2013-08-13 19:50:38 -04:00
return []
r = self
chaos = False
2013-08-13 19:53:30 -04:00
for ll in getattr(r, c.LookupRecord):
2013-08-13 19:50:38 -04:00
if not ll: continue
seqi = ll.SequenceIndex
if chaos:
pos_glyphs = s.glyphs
2013-08-13 19:50:38 -04:00
else:
if seqi == 0:
pos_glyphs = cur_glyphs
2013-08-13 19:50:38 -04:00
else:
2013-08-13 19:53:30 -04:00
pos_glyphs = r.InputCoverage[seqi].intersect_glyphs(s.glyphs)
2013-08-13 19:50:38 -04:00
lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
2013-08-13 19:53:30 -04:00
chaos = chaos or lookup.may_have_non_1to1()
lookup.closure_glyphs(s, cur_glyphs=pos_glyphs)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ContextSubst,
fontTools.ttLib.tables.otTables.ContextPos,
fontTools.ttLib.tables.otTables.ChainContextSubst,
fontTools.ttLib.tables.otTables.ChainContextPos)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
c = self.__classify_context()
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
indices = self.Coverage.subset(s.glyphs)
rss = getattr(self, c.RuleSet)
2013-08-13 19:50:38 -04:00
rss = [rss[i] for i in indices]
for rs in rss:
if not rs: continue
2013-08-13 19:53:30 -04:00
ss = getattr(rs, c.Rule)
2013-08-13 19:50:38 -04:00
ss = [r for r in ss
2013-08-13 19:53:30 -04:00
if r and all(all(g in s.glyphs for g in glist)
for glist in c.RuleData(r))]
setattr(rs, c.Rule, ss)
setattr(rs, c.RuleCount, len(ss))
2013-08-13 19:50:38 -04:00
# Prune empty subrulesets
2013-08-13 19:53:30 -04:00
rss = [rs for rs in rss if rs and getattr(rs, c.Rule)]
setattr(self, c.RuleSet, rss)
setattr(self, c.RuleSetCount, len(rss))
return bool(rss)
2013-08-13 19:50:38 -04:00
elif self.Format == 2:
2013-08-13 19:53:30 -04:00
if not self.Coverage.subset(s.glyphs):
2013-08-13 19:50:38 -04:00
return False
2013-08-13 19:53:30 -04:00
indices = getattr(self, c.ClassDef).subset(self.Coverage.glyphs,
2013-08-13 19:50:38 -04:00
remap=False)
2013-08-13 19:53:30 -04:00
rss = getattr(self, c.RuleSet)
2013-08-13 19:50:38 -04:00
rss = [rss[i] for i in indices]
2013-08-13 19:53:30 -04:00
ContextData = c.ContextData(self)
klass_maps = [x.subset(s.glyphs, remap=True) for x in ContextData]
2013-08-13 19:50:38 -04:00
for rs in rss:
if not rs: continue
2013-08-13 19:53:30 -04:00
ss = getattr(rs, c.Rule)
2013-08-13 19:50:38 -04:00
ss = [r for r in ss
2013-08-13 19:53:30 -04:00
if r and all(all(k in klass_map for k in klist)
for klass_map,klist in zip(klass_maps, c.RuleData(r)))]
setattr(rs, c.Rule, ss)
setattr(rs, c.RuleCount, len(ss))
2013-08-13 19:50:38 -04:00
# Remap rule classes
for r in ss:
2013-08-13 19:53:30 -04:00
c.SetRuleData(r, [[klass_map.index(k) for k in klist]
for klass_map,klist in zip(klass_maps, c.RuleData(r))])
2013-08-13 19:50:38 -04:00
# Prune empty subrulesets
2013-08-13 19:53:30 -04:00
rss = [rs for rs in rss if rs and getattr(rs, c.Rule)]
setattr(self, c.RuleSet, rss)
setattr(self, c.RuleSetCount, len(rss))
return bool(rss)
2013-08-13 19:50:38 -04:00
elif self.Format == 3:
2013-08-13 19:53:30 -04:00
return all(x.subset(s.glyphs) for x in c.RuleData(self))
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ContextSubst,
fontTools.ttLib.tables.otTables.ChainContextSubst,
fontTools.ttLib.tables.otTables.ContextPos,
fontTools.ttLib.tables.otTables.ChainContextPos)
2013-08-13 19:53:30 -04:00
def subset_lookups(self, lookup_indices):
c = self.__classify_context()
2013-08-13 19:50:38 -04:00
if self.Format in [1, 2]:
2013-08-13 19:53:30 -04:00
for rs in getattr(self, c.RuleSet):
2013-08-13 19:50:38 -04:00
if not rs: continue
2013-08-13 19:53:30 -04:00
for r in getattr(rs, c.Rule):
2013-08-13 19:50:38 -04:00
if not r: continue
2013-08-13 19:53:30 -04:00
setattr(r, c.LookupRecord,
[ll for ll in getattr(r, c.LookupRecord)
2013-08-13 19:50:38 -04:00
if ll and ll.LookupListIndex in lookup_indices])
2013-08-13 19:53:30 -04:00
for ll in getattr(r, c.LookupRecord):
2013-08-13 19:50:38 -04:00
if not ll: continue
2013-08-13 19:53:30 -04:00
ll.LookupListIndex = lookup_indices.index(ll.LookupListIndex)
2013-08-13 19:50:38 -04:00
elif self.Format == 3:
2013-08-13 19:53:30 -04:00
setattr(self, c.LookupRecord,
[ll for ll in getattr(self, c.LookupRecord)
2013-08-13 19:50:38 -04:00
if ll and ll.LookupListIndex in lookup_indices])
2013-08-13 19:53:30 -04:00
for ll in getattr(self, c.LookupRecord):
2013-08-13 19:50:38 -04:00
if not ll: continue
2013-08-13 19:53:30 -04:00
ll.LookupListIndex = lookup_indices.index(ll.LookupListIndex)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ContextSubst,
fontTools.ttLib.tables.otTables.ChainContextSubst,
fontTools.ttLib.tables.otTables.ContextPos,
fontTools.ttLib.tables.otTables.ChainContextPos)
2013-08-13 19:53:30 -04:00
def collect_lookups(self):
c = self.__classify_context()
2013-08-13 19:50:38 -04:00
if self.Format in [1, 2]:
return [ll.LookupListIndex
2013-08-13 19:53:30 -04:00
for rs in getattr(self, c.RuleSet) if rs
for r in getattr(rs, c.Rule) if r
for ll in getattr(r, c.LookupRecord) if ll]
2013-08-13 19:50:38 -04:00
elif self.Format == 3:
return [ll.LookupListIndex
2013-08-13 19:53:30 -04:00
for ll in getattr(self, c.LookupRecord) if ll]
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
2013-08-13 19:53:30 -04:00
def closure_glyphs(self, s, cur_glyphs=None):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
self.ExtSubTable.closure_glyphs(s, cur_glyphs)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-23 14:52:18 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
2013-08-13 19:53:30 -04:00
def may_have_non_1to1(self):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
return self.ExtSubTable.may_have_non_1to1()
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
@_add_method(fontTools.ttLib.tables.otTables.ExtensionSubst,
fontTools.ttLib.tables.otTables.ExtensionPos)
def prune_pre_subset(self, options):
if self.Format == 1:
return self.ExtSubTable.prune_pre_subset(options)
else:
assert 0, "unknown format: %s" % self.Format
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ExtensionSubst,
fontTools.ttLib.tables.otTables.ExtensionPos)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
return self.ExtSubTable.subset_glyphs(s)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-07-21 18:16:55 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ExtensionSubst,
fontTools.ttLib.tables.otTables.ExtensionPos)
def prune_post_subset(self, options):
if self.Format == 1:
return self.ExtSubTable.prune_post_subset(options)
else:
assert 0, "unknown format: %s" % self.Format
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ExtensionSubst,
fontTools.ttLib.tables.otTables.ExtensionPos)
2013-08-13 19:53:30 -04:00
def subset_lookups(self, lookup_indices):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
return self.ExtSubTable.subset_lookups(lookup_indices)
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ExtensionSubst,
fontTools.ttLib.tables.otTables.ExtensionPos)
2013-08-13 19:53:30 -04:00
def collect_lookups(self):
2013-08-13 19:50:38 -04:00
if self.Format == 1:
2013-08-13 19:53:30 -04:00
return self.ExtSubTable.collect_lookups()
2013-08-13 19:50:38 -04:00
else:
assert 0, "unknown format: %s" % self.Format
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Lookup)
2013-08-13 19:53:30 -04:00
def closure_glyphs(self, s, cur_glyphs=None):
2013-08-13 19:50:38 -04:00
for st in self.SubTable:
if not st: continue
2013-08-13 19:53:30 -04:00
st.closure_glyphs(s, cur_glyphs)
2013-07-23 14:52:18 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Lookup)
def prune_pre_subset(self, options):
ret = False
for st in self.SubTable:
if not st: continue
if st.prune_pre_subset(options): ret = True
return ret
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Lookup)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
self.SubTable = [st for st in self.SubTable if st and st.subset_glyphs(s)]
self.SubTableCount = len(self.SubTable)
return bool(self.SubTableCount)
2013-07-21 23:15:32 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Lookup)
def prune_post_subset(self, options):
ret = False
for st in self.SubTable:
if not st: continue
if st.prune_post_subset(options): ret = True
return ret
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Lookup)
2013-08-13 19:53:30 -04:00
def subset_lookups(self, lookup_indices):
2013-08-13 19:50:38 -04:00
for s in self.SubTable:
2013-08-13 19:53:30 -04:00
s.subset_lookups(lookup_indices)
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Lookup)
2013-08-13 19:53:30 -04:00
def collect_lookups(self):
2013-08-13 20:25:37 -04:00
return _uniq_sort(sum((st.collect_lookups() for st in self.SubTable
if st), []))
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Lookup)
2013-08-13 19:53:30 -04:00
def may_have_non_1to1(self):
return any(st.may_have_non_1to1() for st in self.SubTable if st)
@_add_method(fontTools.ttLib.tables.otTables.LookupList)
def prune_pre_subset(self, options):
ret = False
for l in self.Lookup:
if not l: continue
if l.prune_pre_subset(options): ret = True
return ret
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.LookupList)
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
"Returns the indices of nonempty lookups."
2013-08-14 19:47:42 -04:00
return [i for i,l in enumerate(self.Lookup) if l and l.subset_glyphs(s)]
@_add_method(fontTools.ttLib.tables.otTables.LookupList)
def prune_post_subset(self, options):
ret = False
for l in self.Lookup:
if not l: continue
if l.prune_post_subset(options): ret = True
return ret
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.LookupList)
2013-08-13 19:53:30 -04:00
def subset_lookups(self, lookup_indices):
2013-08-13 19:50:38 -04:00
self.Lookup = [self.Lookup[i] for i in lookup_indices
if i < self.LookupCount]
2013-08-13 19:53:30 -04:00
self.LookupCount = len(self.Lookup)
2013-08-13 19:50:38 -04:00
for l in self.Lookup:
2013-08-13 19:53:30 -04:00
l.subset_lookups(lookup_indices)
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.LookupList)
2013-08-13 19:53:30 -04:00
def closure_lookups(self, lookup_indices):
2013-08-13 20:25:37 -04:00
lookup_indices = _uniq_sort(lookup_indices)
2013-08-13 19:50:38 -04:00
recurse = lookup_indices
while True:
2013-08-13 19:53:30 -04:00
recurse_lookups = sum((self.Lookup[i].collect_lookups()
2013-08-13 19:50:38 -04:00
for i in recurse if i < self.LookupCount), [])
recurse_lookups = [l for l in recurse_lookups
if l not in lookup_indices and l < self.LookupCount]
if not recurse_lookups:
2013-08-13 20:25:37 -04:00
return _uniq_sort(lookup_indices)
recurse_lookups = _uniq_sort(recurse_lookups)
2013-08-13 19:53:30 -04:00
lookup_indices.extend(recurse_lookups)
2013-08-13 19:50:38 -04:00
recurse = recurse_lookups
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Feature)
2013-08-13 19:53:30 -04:00
def subset_lookups(self, lookup_indices):
2013-08-13 19:50:38 -04:00
self.LookupListIndex = [l for l in self.LookupListIndex
if l in lookup_indices]
# Now map them.
2013-08-13 19:53:30 -04:00
self.LookupListIndex = [lookup_indices.index(l)
2013-08-13 19:50:38 -04:00
for l in self.LookupListIndex]
2013-08-13 19:53:30 -04:00
self.LookupCount = len(self.LookupListIndex)
2013-08-13 19:50:38 -04:00
return self.LookupCount
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Feature)
2013-08-13 19:53:30 -04:00
def collect_lookups(self):
2013-08-13 19:50:38 -04:00
return self.LookupListIndex[:]
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.FeatureList)
2013-08-13 19:53:30 -04:00
def subset_lookups(self, lookup_indices):
2013-08-13 19:50:38 -04:00
"Returns the indices of nonempty features."
2013-08-14 19:47:42 -04:00
feature_indices = [i for i,f in enumerate(self.FeatureRecord)
2013-08-13 19:53:30 -04:00
if f.Feature.subset_lookups(lookup_indices)]
self.subset_features(feature_indices)
2013-08-13 19:50:38 -04:00
return feature_indices
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.FeatureList)
2013-08-13 19:53:30 -04:00
def collect_lookups(self, feature_indices):
2013-08-13 20:25:37 -04:00
return _uniq_sort(sum((self.FeatureRecord[i].Feature.collect_lookups()
for i in feature_indices
2013-08-13 20:07:09 -04:00
if i < self.FeatureCount), []))
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.FeatureList)
2013-08-13 19:53:30 -04:00
def subset_features(self, feature_indices):
2013-08-13 19:50:38 -04:00
self.FeatureRecord = [self.FeatureRecord[i] for i in feature_indices]
2013-08-13 19:53:30 -04:00
self.FeatureCount = len(self.FeatureRecord)
return bool(self.FeatureCount)
2013-07-23 12:10:46 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.DefaultLangSys,
fontTools.ttLib.tables.otTables.LangSys)
2013-08-13 19:53:30 -04:00
def subset_features(self, feature_indices):
2013-08-13 19:50:38 -04:00
if self.ReqFeatureIndex in feature_indices:
2013-08-13 19:53:30 -04:00
self.ReqFeatureIndex = feature_indices.index(self.ReqFeatureIndex)
2013-08-13 19:50:38 -04:00
else:
self.ReqFeatureIndex = 65535
self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
# Now map them.
2013-08-13 19:53:30 -04:00
self.FeatureIndex = [feature_indices.index(f) for f in self.FeatureIndex
2013-08-13 19:50:38 -04:00
if f in feature_indices]
2013-08-13 19:53:30 -04:00
self.FeatureCount = len(self.FeatureIndex)
return bool(self.FeatureCount or self.ReqFeatureIndex != 65535)
2013-08-13 19:50:38 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.DefaultLangSys,
fontTools.ttLib.tables.otTables.LangSys)
2013-08-13 19:53:30 -04:00
def collect_features(self):
2013-08-13 19:50:38 -04:00
feature_indices = self.FeatureIndex[:]
if self.ReqFeatureIndex != 65535:
2013-08-13 19:53:30 -04:00
feature_indices.append(self.ReqFeatureIndex)
2013-08-13 20:25:37 -04:00
return _uniq_sort(feature_indices)
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Script)
2013-08-13 19:53:30 -04:00
def subset_features(self, feature_indices):
if(self.DefaultLangSys and
not self.DefaultLangSys.subset_features(feature_indices)):
2013-08-13 19:50:38 -04:00
self.DefaultLangSys = None
self.LangSysRecord = [l for l in self.LangSysRecord
2013-08-13 19:53:30 -04:00
if l.LangSys.subset_features(feature_indices)]
self.LangSysCount = len(self.LangSysRecord)
return bool(self.LangSysCount or self.DefaultLangSys)
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.Script)
2013-08-13 19:53:30 -04:00
def collect_features(self):
feature_indices = [l.LangSys.collect_features() for l in self.LangSysRecord]
2013-08-13 19:50:38 -04:00
if self.DefaultLangSys:
2013-08-13 19:53:30 -04:00
feature_indices.append(self.DefaultLangSys.collect_features())
2013-08-13 20:25:37 -04:00
return _uniq_sort(sum(feature_indices, []))
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ScriptList)
2013-08-13 19:53:30 -04:00
def subset_features(self, feature_indices):
2013-08-13 19:50:38 -04:00
self.ScriptRecord = [s for s in self.ScriptRecord
2013-08-13 19:53:30 -04:00
if s.Script.subset_features(feature_indices)]
self.ScriptCount = len(self.ScriptRecord)
return bool(self.ScriptCount)
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.tables.otTables.ScriptList)
2013-08-13 19:53:30 -04:00
def collect_features(self):
2013-08-13 20:25:37 -04:00
return _uniq_sort(sum((s.Script.collect_features()
for s in self.ScriptRecord), []))
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('GSUB'))
2013-08-13 19:53:30 -04:00
def closure_glyphs(self, s):
2013-08-13 19:50:38 -04:00
s.table = self.table
2013-08-13 19:53:30 -04:00
feature_indices = self.table.ScriptList.collect_features()
lookup_indices = self.table.FeatureList.collect_lookups(feature_indices)
2013-08-13 19:50:38 -04:00
while True:
2013-08-13 19:53:30 -04:00
orig_glyphs = s.glyphs.copy()
2013-08-13 19:50:38 -04:00
for i in lookup_indices:
if i >= self.table.LookupList.LookupCount: continue
if not self.table.LookupList.Lookup[i]: continue
2013-08-13 19:53:30 -04:00
self.table.LookupList.Lookup[i].closure_glyphs(s)
2013-08-13 19:50:38 -04:00
if orig_glyphs == s.glyphs:
break
del s.table
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('GSUB'),
fontTools.ttLib.getTableClass('GPOS'))
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
s.glyphs = s.glyphs_gsubed
2013-08-13 19:53:30 -04:00
lookup_indices = self.table.LookupList.subset_glyphs(s)
self.subset_lookups(lookup_indices)
self.prune_lookups()
2013-08-13 19:50:38 -04:00
return True
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('GSUB'),
fontTools.ttLib.getTableClass('GPOS'))
2013-08-13 19:53:30 -04:00
def subset_lookups(self, lookup_indices):
2013-08-13 19:50:38 -04:00
"""Retrains specified lookups, then removes empty features, language
systems, and scripts."""
2013-08-13 19:53:30 -04:00
self.table.LookupList.subset_lookups(lookup_indices)
feature_indices = self.table.FeatureList.subset_lookups(lookup_indices)
self.table.ScriptList.subset_features(feature_indices)
2013-08-13 19:50:38 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('GSUB'),
fontTools.ttLib.getTableClass('GPOS'))
2013-08-13 19:53:30 -04:00
def prune_lookups(self):
2013-08-13 19:50:38 -04:00
"Remove unreferenced lookups"
2013-08-13 19:53:30 -04:00
feature_indices = self.table.ScriptList.collect_features()
lookup_indices = self.table.FeatureList.collect_lookups(feature_indices)
lookup_indices = self.table.LookupList.closure_lookups(lookup_indices)
self.subset_lookups(lookup_indices)
2013-08-13 19:50:38 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('GSUB'),
fontTools.ttLib.getTableClass('GPOS'))
2013-08-13 19:53:30 -04:00
def subset_feature_tags(self, feature_tags):
2013-08-14 19:47:42 -04:00
feature_indices = [i for i,f in
2013-08-13 19:53:30 -04:00
enumerate(self.table.FeatureList.FeatureRecord)
2013-08-13 19:50:38 -04:00
if f.FeatureTag in feature_tags]
2013-08-13 19:53:30 -04:00
self.table.FeatureList.subset_features(feature_indices)
self.table.ScriptList.subset_features(feature_indices)
2013-08-13 19:50:38 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('GSUB'),
fontTools.ttLib.getTableClass('GPOS'))
2013-08-13 19:53:30 -04:00
def prune_pre_subset(self, options):
if '*' not in options.layout_features:
2013-08-13 19:53:30 -04:00
self.subset_feature_tags(options.layout_features)
self.prune_lookups()
self.table.LookupList.prune_pre_subset(options);
return True
@_add_method(fontTools.ttLib.getTableClass('GSUB'),
fontTools.ttLib.getTableClass('GPOS'))
def prune_post_subset(self, options):
self.table.LookupList.prune_post_subset(options);
2013-08-13 19:50:38 -04:00
return True
2013-07-23 12:10:46 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('GDEF'))
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
glyphs = s.glyphs_gsubed
table = self.table
if table.LigCaretList:
2013-08-13 19:53:30 -04:00
indices = table.LigCaretList.Coverage.subset(glyphs)
2013-08-13 19:50:38 -04:00
table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i]
for i in indices]
2013-08-13 19:53:30 -04:00
table.LigCaretList.LigGlyphCount = len(table.LigCaretList.LigGlyph)
2013-08-13 19:50:38 -04:00
if not table.LigCaretList.LigGlyphCount:
table.LigCaretList = None
if table.MarkAttachClassDef:
2013-08-16 10:58:25 -04:00
table.MarkAttachClassDef.classDefs = dict((g,v) for g,v in
table.MarkAttachClassDef.
classDefs.iteritems()
if g in glyphs)
2013-08-13 19:50:38 -04:00
if not table.MarkAttachClassDef.classDefs:
table.MarkAttachClassDef = None
if table.GlyphClassDef:
2013-08-16 10:58:25 -04:00
table.GlyphClassDef.classDefs = dict((g,v) for g,v in
table.GlyphClassDef.
classDefs.iteritems()
if g in glyphs)
2013-08-13 19:50:38 -04:00
if not table.GlyphClassDef.classDefs:
table.GlyphClassDef = None
if table.AttachList:
2013-08-13 19:53:30 -04:00
indices = table.AttachList.Coverage.subset(glyphs)
2013-08-13 19:50:38 -04:00
table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i]
for i in indices]
2013-08-13 19:53:30 -04:00
table.AttachList.GlyphCount = len(table.AttachList.AttachPoint)
2013-08-13 19:50:38 -04:00
if not table.AttachList.GlyphCount:
table.AttachList = None
2013-08-13 19:53:30 -04:00
return bool(table.LigCaretList or
2013-08-13 19:50:38 -04:00
table.MarkAttachClassDef or
table.GlyphClassDef or
table.AttachList)
2013-07-22 12:48:17 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('kern'))
2013-08-13 19:53:30 -04:00
def prune_pre_subset(self, options):
2013-08-13 19:50:38 -04:00
# Prune unknown kern table types
2013-08-13 19:53:30 -04:00
self.kernTables = [t for t in self.kernTables if hasattr(t, 'kernTable')]
return bool(self.kernTables)
2013-07-24 18:51:05 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('kern'))
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
glyphs = s.glyphs_gsubed
for t in self.kernTables:
2013-08-16 10:58:25 -04:00
t.kernTable = dict(((a,b),v) for (a,b),v in t.kernTable.iteritems()
if a in glyphs and b in glyphs)
2013-08-13 19:50:38 -04:00
self.kernTables = [t for t in self.kernTables if t.kernTable]
2013-08-13 19:53:30 -04:00
return bool(self.kernTables)
2013-08-13 19:50:38 -04:00
2013-08-16 10:56:30 -04:00
@_add_method(fontTools.ttLib.getTableClass('vmtx'),
fontTools.ttLib.getTableClass('hmtx'))
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-16 10:58:25 -04:00
self.metrics = dict((g,v) for g,v in self.metrics.iteritems() if g in s.glyphs)
2013-08-13 19:53:30 -04:00
return bool(self.metrics)
2013-07-22 14:29:08 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('hdmx'))
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-16 10:58:25 -04:00
self.hdmx = dict((sz,_dict((g,v) for g,v in l.iteritems() if g in s.glyphs))
for sz,l in self.hdmx.iteritems())
2013-08-13 19:53:30 -04:00
return bool(self.hdmx)
2013-07-22 14:49:54 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('VORG'))
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-16 10:58:25 -04:00
self.VOriginRecords = dict((g,v) for g,v in self.VOriginRecords.iteritems()
if g in s.glyphs)
2013-08-13 19:53:30 -04:00
self.numVertOriginYMetrics = len(self.VOriginRecords)
2013-08-13 20:09:28 -04:00
return True # Never drop; has default metrics
2013-07-22 15:29:17 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('post'))
2013-08-13 19:53:30 -04:00
def prune_pre_subset(self, options):
2013-08-13 19:50:38 -04:00
if not options.glyph_names:
self.formatType = 3.0
return True
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('post'))
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 20:09:28 -04:00
self.extraNames = [] # This seems to do it
2013-08-13 19:50:38 -04:00
return True
2013-07-22 15:17:12 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
2013-08-13 19:53:30 -04:00
def getComponentNamesFast(self, glyfTable):
2013-08-29 18:02:48 -04:00
if not self.data or struct.unpack(">h", self.data[:2])[0] >= 0:
2013-08-13 20:09:28 -04:00
return [] # Not composite
2013-08-13 19:50:38 -04:00
data = self.data
i = 10
components = []
more = 1
while more:
flags, glyphID = struct.unpack(">HH", data[i:i+4])
i += 4
flags = int(flags)
2013-08-13 19:53:30 -04:00
components.append(glyfTable.getGlyphName(int(glyphID)))
2013-08-13 19:50:38 -04:00
2013-08-14 12:55:42 -04:00
if flags & 0x0001: i += 4 # ARG_1_AND_2_ARE_WORDS
2013-08-13 20:51:44 -04:00
else: i += 2
2013-08-14 12:55:42 -04:00
if flags & 0x0008: i += 2 # WE_HAVE_A_SCALE
elif flags & 0x0040: i += 4 # WE_HAVE_AN_X_AND_Y_SCALE
elif flags & 0x0080: i += 8 # WE_HAVE_A_TWO_BY_TWO
more = flags & 0x0020 # MORE_COMPONENTS
2013-08-13 19:50:38 -04:00
return components
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
2013-08-13 19:53:30 -04:00
def remapComponentsFast(self, indices):
2013-08-29 18:02:48 -04:00
if not self.data or struct.unpack(">h", self.data[:2])[0] >= 0:
2013-08-13 20:09:28 -04:00
return # Not composite
data = array.array("B", self.data)
2013-08-13 19:50:38 -04:00
i = 10
more = 1
while more:
2013-08-13 19:53:30 -04:00
flags =(data[i] << 8) | data[i+1]
glyphID =(data[i+2] << 8) | data[i+3]
2013-08-13 19:50:38 -04:00
# Remap
2013-08-13 19:53:30 -04:00
glyphID = indices.index(glyphID)
2013-08-13 19:50:38 -04:00
data[i+2] = glyphID >> 8
data[i+3] = glyphID & 0xFF
i += 4
flags = int(flags)
2013-08-14 12:55:42 -04:00
if flags & 0x0001: i += 4 # ARG_1_AND_2_ARE_WORDS
2013-08-13 20:51:44 -04:00
else: i += 2
2013-08-14 12:55:42 -04:00
if flags & 0x0008: i += 2 # WE_HAVE_A_SCALE
elif flags & 0x0040: i += 4 # WE_HAVE_AN_X_AND_Y_SCALE
elif flags & 0x0080: i += 8 # WE_HAVE_A_TWO_BY_TWO
more = flags & 0x0020 # MORE_COMPONENTS
self.data = data.tostring()
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
2013-08-13 19:53:30 -04:00
def dropInstructionsFast(self):
2013-08-29 18:02:48 -04:00
if not self.data:
return
2013-08-13 19:50:38 -04:00
numContours = struct.unpack(">h", self.data[:2])[0]
data = array.array("B", self.data)
2013-08-13 19:50:38 -04:00
i = 10
if numContours >= 0:
2013-08-13 20:09:28 -04:00
i += 2 * numContours # endPtsOfContours
2013-08-13 19:53:30 -04:00
instructionLen =(data[i] << 8) | data[i+1]
2013-08-13 19:50:38 -04:00
# Zero it
data[i] = data [i+1] = 0
i += 2
if instructionLen:
# Splice it out
data = data[:i] + data[i+instructionLen:]
else:
more = 1
while more:
2013-08-13 19:53:30 -04:00
flags =(data[i] << 8) | data[i+1]
2013-08-13 19:50:38 -04:00
# Turn instruction flag off
2013-08-14 12:55:42 -04:00
flags &= ~0x0100 # WE_HAVE_INSTRUCTIONS
2013-08-13 19:50:38 -04:00
data[i+0] = flags >> 8
data[i+1] = flags & 0xFF
i += 4
flags = int(flags)
2013-08-14 12:55:42 -04:00
if flags & 0x0001: i += 4 # ARG_1_AND_2_ARE_WORDS
2013-08-13 20:51:44 -04:00
else: i += 2
2013-08-14 12:55:42 -04:00
if flags & 0x0008: i += 2 # WE_HAVE_A_SCALE
elif flags & 0x0040: i += 4 # WE_HAVE_AN_X_AND_Y_SCALE
elif flags & 0x0080: i += 8 # WE_HAVE_A_TWO_BY_TWO
more = flags & 0x0020 # MORE_COMPONENTS
2013-08-13 19:50:38 -04:00
# Cut off
data = data[:i]
if len(data) % 4:
# add pad bytes
2013-08-13 19:53:30 -04:00
nPadBytes = 4 -(len(data) % 4)
for i in range(nPadBytes):
data.append(0)
self.data = data.tostring()
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('glyf'))
2013-08-13 19:53:30 -04:00
def closure_glyphs(self, s):
2013-08-13 19:50:38 -04:00
decompose = s.glyphs
# I don't know if component glyphs can be composite themselves.
# We handle them anyway.
while True:
2013-08-13 19:53:30 -04:00
components = set()
2013-08-13 19:50:38 -04:00
for g in decompose:
if g not in self.glyphs:
continue
gl = self.glyphs[g]
2013-08-13 19:53:30 -04:00
if hasattr(gl, "data"):
for c in gl.getComponentNamesFast(self):
2013-08-13 19:50:38 -04:00
if c not in s.glyphs:
2013-08-13 19:53:30 -04:00
components.add(c)
2013-08-13 19:50:38 -04:00
else:
# TTX seems to expand gid0..3 always
2013-08-13 19:53:30 -04:00
if gl.isComposite():
2013-08-13 19:50:38 -04:00
for c in gl.components:
if c.glyphName not in s.glyphs:
2013-08-13 19:53:30 -04:00
components.add(c.glyphName)
components = set(c for c in components if c not in s.glyphs)
2013-08-13 19:50:38 -04:00
if not components:
break
decompose = components
2013-08-13 19:53:30 -04:00
s.glyphs.update(components)
2013-07-23 12:58:37 -04:00
2013-08-29 18:02:48 -04:00
@_add_method(fontTools.ttLib.getTableClass('glyf'))
def prune_pre_subset(self, options):
if options.notdef_glyph and not options.notdef_outline:
g = self[self.glyphOrder[0]]
# Yay, easy!
g.__dict__.clear()
g.data = ""
return True
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('glyf'))
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-16 10:58:25 -04:00
self.glyphs = dict((g,v) for g,v in self.glyphs.iteritems() if g in s.glyphs)
2013-08-13 19:53:30 -04:00
indices = [i for i,g in enumerate(self.glyphOrder) if g in s.glyphs]
2013-08-13 19:50:38 -04:00
for v in self.glyphs.itervalues():
2013-08-13 19:53:30 -04:00
if hasattr(v, "data"):
v.remapComponentsFast(indices)
2013-08-13 19:50:38 -04:00
else:
2013-08-13 20:09:28 -04:00
pass # No need
2013-08-13 19:50:38 -04:00
self.glyphOrder = [g for g in self.glyphOrder if g in s.glyphs]
2013-08-29 18:17:31 -04:00
# Don't drop empty 'glyf' tables, otherwise 'loca' doesn't get subset.
return True
2013-07-22 16:47:24 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('glyf'))
2013-08-13 19:53:30 -04:00
def prune_post_subset(self, options):
2013-08-13 19:50:38 -04:00
if not options.hinting:
for v in self.glyphs.itervalues():
2013-08-13 19:53:30 -04:00
if hasattr(v, "data"):
v.dropInstructionsFast()
2013-08-13 19:50:38 -04:00
else:
v.program = fontTools.ttLib.tables.ttProgram.Program()
v.program.fromBytecode([])
return True
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('CFF '))
def prune_pre_subset(self, options):
2013-08-13 19:50:38 -04:00
cff = self.cff
# CFF table must have one font only
2013-08-13 19:50:38 -04:00
cff.fontNames = cff.fontNames[:1]
2013-08-29 18:02:48 -04:00
if options.notdef_glyph and not options.notdef_outline:
for fontname in cff.keys():
font = cff[fontname]
c,_ = font.CharStrings.getItemAndSelector('.notdef')
2013-09-12 16:47:52 -04:00
# XXX we should preserve the glyph width
2013-08-29 18:02:48 -04:00
c.bytecode = '\x0e' # endchar
c.program = None
2013-08-29 18:18:17 -04:00
return True # bool(cff.fontNames)
2013-08-13 15:46:37 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('CFF '))
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
cff = self.cff
for fontname in cff.keys():
font = cff[fontname]
cs = font.CharStrings
# Load all glyphs
for g in font.charset:
if g not in s.glyphs: continue
c,sel = cs.getItemAndSelector(g)
2013-08-13 19:50:38 -04:00
if cs.charStringsAreIndexed:
2013-08-13 19:53:30 -04:00
indices = [i for i,g in enumerate(font.charset) if g in s.glyphs]
2013-08-13 19:50:38 -04:00
csi = cs.charStringsIndex
csi.items = [csi.items[i] for i in indices]
csi.count = len(csi.items)
del csi.file, csi.offsets
2013-08-13 19:53:30 -04:00
if hasattr(font, "FDSelect"):
2013-08-13 19:50:38 -04:00
sel = font.FDSelect
sel.format = None
sel.gidArray = [sel.gidArray[i] for i in indices]
2013-08-16 10:58:25 -04:00
cs.charStrings = dict((g,indices.index(v))
for g,v in cs.charStrings.iteritems()
if g in s.glyphs)
2013-08-13 19:50:38 -04:00
else:
2013-08-16 10:58:25 -04:00
cs.charStrings = dict((g,v)
for g,v in cs.charStrings.iteritems()
if g in s.glyphs)
2013-08-13 19:50:38 -04:00
font.charset = [g for g in font.charset if g in s.glyphs]
2013-08-13 19:53:30 -04:00
font.numGlyphs = len(font.charset)
2013-08-29 18:18:17 -04:00
return True # any(cff[fontname].numGlyphs for fontname in cff.keys())
2013-08-14 19:37:39 -04:00
@_add_method(fontTools.misc.psCharStrings.T2CharString)
def subset_subroutines(self, subrs, gsubrs):
p = self.program
assert len(p)
2013-08-16 14:44:09 -04:00
for i in xrange(1, len(p)):
2013-08-14 19:37:39 -04:00
if p[i] == 'callsubr':
assert type(p[i-1]) is int
p[i-1] = subrs._used.index(p[i-1] + subrs._old_bias) - subrs._new_bias
elif p[i] == 'callgsubr':
assert type(p[i-1]) is int
p[i-1] = gsubrs._used.index(p[i-1] + gsubrs._old_bias) - gsubrs._new_bias
@_add_method(fontTools.misc.psCharStrings.T2CharString)
def drop_hints(self):
hints = self._hints
if hints.has_hint:
self.program = self.program[hints.last_hint:]
if hasattr(self, 'width'):
# Insert width back if needed
if self.width != self.private.defaultWidthX:
self.program.insert(0, self.width - self.private.nominalWidthX)
if hints.has_hintmask:
i = 0
p = self.program
while i < len(p):
if p[i] in ['hintmask', 'cntrmask']:
assert i + 1 <= len(p)
del p[i:i+2]
continue
i += 1
assert len(self.program)
del self._hints
class _MarkingT2Decompiler(fontTools.misc.psCharStrings.SimpleT2Decompiler):
def __init__(self, localSubrs, globalSubrs):
fontTools.misc.psCharStrings.SimpleT2Decompiler.__init__(self,
localSubrs,
globalSubrs)
for subrs in [localSubrs, globalSubrs]:
if subrs and not hasattr(subrs, "_used"):
subrs._used = set()
def op_callsubr(self, index):
self.localSubrs._used.add(self.operandStack[-1]+self.localBias)
fontTools.misc.psCharStrings.SimpleT2Decompiler.op_callsubr(self, index)
def op_callgsubr(self, index):
self.globalSubrs._used.add(self.operandStack[-1]+self.globalBias)
fontTools.misc.psCharStrings.SimpleT2Decompiler.op_callgsubr(self, index)
class _DehintingT2Decompiler(fontTools.misc.psCharStrings.SimpleT2Decompiler):
class Hints:
def __init__(self):
# Whether calling this charstring produces any hint stems
self.has_hint = False
# Index to start at to drop all hints
self.last_hint = 0
# Index up to which we know more hints are possible. Only
# relevant if status is 0 or 1.
self.last_checked = 0
# The status means:
# 0: after dropping hints, this charstring is empty
# 1: after dropping hints, there may be more hints continuing after this
# 2: no more hints possible after this charstring
self.status = 0
# Has hintmask instructions; not recursive
self.has_hintmask = False
pass
def __init__(self, css, localSubrs, globalSubrs):
self._css = css
fontTools.misc.psCharStrings.SimpleT2Decompiler.__init__(self,
localSubrs,
globalSubrs)
def execute(self, charString):
old_hints = charString._hints if hasattr(charString, '_hints') else None
charString._hints = self.Hints()
fontTools.misc.psCharStrings.SimpleT2Decompiler.execute(self, charString)
hints = charString._hints
if hints.has_hint or hints.has_hintmask:
self._css.add(charString)
if hints.status != 2:
# Check from last_check, make sure we didn't have any operators.
for i in xrange(hints.last_checked, len(charString.program) - 1):
if type(charString.program[i]) == str:
hints.status = 2
break;
else:
hints.status = 1 # There's *something* here
hints.last_checked = len(charString.program)
if old_hints:
assert hints.__dict__ == old_hints.__dict__
def op_callsubr(self, index):
subr = self.localSubrs[self.operandStack[-1]+self.localBias]
fontTools.misc.psCharStrings.SimpleT2Decompiler.op_callsubr(self, index)
self.processSubr(index, subr)
def op_callgsubr(self, index):
subr = self.globalSubrs[self.operandStack[-1]+self.globalBias]
fontTools.misc.psCharStrings.SimpleT2Decompiler.op_callgsubr(self, index)
self.processSubr(index, subr)
def op_hstem(self, index):
fontTools.misc.psCharStrings.SimpleT2Decompiler.op_hstem(self, index)
self.processHint(index)
def op_vstem(self, index):
fontTools.misc.psCharStrings.SimpleT2Decompiler.op_vstem(self, index)
self.processHint(index)
def op_hstemhm(self, index):
fontTools.misc.psCharStrings.SimpleT2Decompiler.op_hstemhm(self, index)
self.processHint(index)
def op_vstemhm(self, index):
fontTools.misc.psCharStrings.SimpleT2Decompiler.op_vstemhm(self, index)
self.processHint(index)
def op_hintmask(self, index):
fontTools.misc.psCharStrings.SimpleT2Decompiler.op_hintmask(self, index)
self.processHintmask(index)
def op_cntrmask(self, index):
fontTools.misc.psCharStrings.SimpleT2Decompiler.op_cntrmask(self, index)
self.processHintmask(index)
def processHintmask(self, index):
cs = self.callingStack[-1]
hints = cs._hints
hints.has_hintmask = True
if hints.status != 2 and hints.has_hint:
# Check from last_check, see if we may be an implicit vstem
for i in xrange(hints.last_checked, index - 1):
if type(cs.program[i]) == str:
hints.status = 2
break;
if hints.status != 2:
# We are an implicit vstem
hints.last_hint = index + 1
hints.status = 0
hints.last_checked = index + 1
def processHint(self, index):
cs = self.callingStack[-1]
hints = cs._hints
hints.has_hint = True
hints.last_hint = index
hints.last_checked = index
def processSubr(self, index, subr):
cs = self.callingStack[-1]
hints = cs._hints
subr_hints = subr._hints
if subr_hints.has_hint:
if hints.status != 2:
hints.has_hint = True
hints.last_checked = index
hints.status = subr_hints.status
# Decide where to chop off from
if subr_hints.status == 0:
hints.last_hint = index
else:
hints.last_hint = index - 2 # Leave the subr call in
else:
# In my understanding, this is a font bug. Ie. it has hint stems
# *after* path construction. I've seen this in widespread fonts.
# Best to ignore the hints I suppose...
pass
#assert 0
else:
hints.status = max(hints.status, subr_hints.status)
if hints.status != 2:
# Check from last_check, make sure we didn't have
# any operators.
for i in xrange(hints.last_checked, index - 1):
if type(cs.program[i]) == str:
hints.status = 2
break;
hints.last_checked = index
@_add_method(fontTools.ttLib.getTableClass('CFF '))
def prune_post_subset(self, options):
cff = self.cff
for fontname in cff.keys():
font = cff[fontname]
cs = font.CharStrings
#
2013-08-14 19:39:00 -04:00
# Drop unused FontDictionaries
#
if hasattr(font, "FDSelect"):
sel = font.FDSelect
indices = _uniq_sort(sel.gidArray)
sel.gidArray = [indices.index (ss) for ss in sel.gidArray]
arr = font.FDArray
2013-08-14 19:39:00 -04:00
arr.items = [arr[i] for i in indices]
arr.count = len(arr.items)
del arr.file, arr.offsets
#
# Drop hints if not needed
#
if not options.hinting:
#
# This can be tricky, but doesn't have to. What we do is:
#
# - Run all used glyph charstrings and recurse into subroutines,
# - For each charstring (including subroutines), if it has any
# of the hint stem operators, we mark it as such. Upon returning,
# for each charstring we note all the subroutine calls it makes
# that (recursively) contain a stem,
# - Dropping hinting then consists of the following two ops:
# * Drop the piece of the program in each charstring before the
# last call to a stem op or a stem-calling subroutine,
# * Drop all hintmask operations.
# - It's trickier... A hintmask right after hints and a few numbers
# will act as an implicit vstemhm. As such, we track whether
# we have seen any non-hint operators so far and do the right
# thing, recursively... Good luck understanding that :(
#
css = set()
for g in font.charset:
c,sel = cs.getItemAndSelector(g)
# Make sure it's decompiled. We want our "decompiler" to walk
# the program, not the bytecode.
c.draw(fontTools.pens.basePen.NullPen())
subrs = getattr(c.private, "Subrs", [])
decompiler = _DehintingT2Decompiler(css, subrs, c.globalSubrs)
decompiler.execute(c)
for charstring in css:
charstring.drop_hints()
#
# Renumber subroutines to remove unused ones
#
# Mark all used subroutines
for g in font.charset:
c,sel = cs.getItemAndSelector(g)
subrs = getattr(c.private, "Subrs", [])
decompiler = _MarkingT2Decompiler(subrs, c.globalSubrs)
decompiler.execute(c)
all_subrs = [font.GlobalSubrs]
if hasattr(font, 'FDSelect'):
all_subrs.extend(fd.Private.Subrs for fd in font.FDArray if hasattr(fd.Private, 'Subrs') and fd.Private.Subrs)
elif hasattr(font.Private, 'Subrs') and font.Private.Subrs:
all_subrs.append(font.Private.Subrs)
subrs = set(subrs) # Remove duplicates
# Prepare
for subrs in all_subrs:
if not hasattr(subrs, '_used'):
subrs._used = set()
subrs._used = _uniq_sort(subrs._used)
subrs._old_bias = fontTools.misc.psCharStrings.calcSubrBias(subrs)
subrs._new_bias = fontTools.misc.psCharStrings.calcSubrBias(subrs._used)
2013-08-14 19:54:13 -04:00
# Renumber glyph charstrings
for g in font.charset:
c,sel = cs.getItemAndSelector(g)
subrs = getattr(c.private, "Subrs", [])
c.subset_subroutines (subrs, font.GlobalSubrs)
# Renumber subroutines themselves
for subrs in all_subrs:
if subrs == font.GlobalSubrs:
if not hasattr(font, 'FDSelect') and hasattr(font.Private, 'Subrs'):
local_subrs = font.Private.Subrs
else:
local_subrs = []
else:
local_subrs = subrs
subrs.items = [subrs.items[i] for i in subrs._used]
subrs.count = len(subrs.items)
del subrs.file
if hasattr(subrs, 'offsets'):
del subrs.offsets
for i in xrange (subrs.count):
subrs[i].subset_subroutines (local_subrs, font.GlobalSubrs)
# Cleanup
for subrs in all_subrs:
del subrs._used, subrs._old_bias, subrs._new_bias
2013-08-13 19:50:38 -04:00
return True
2013-07-23 13:37:13 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('cmap'))
2013-08-13 19:53:30 -04:00
def closure_glyphs(self, s):
2013-08-13 19:50:38 -04:00
tables = [t for t in self.tables
if t.platformID == 3 and t.platEncID in [1, 10]]
for u in s.unicodes_requested:
found = False
for table in tables:
if u in table.cmap:
2013-08-13 19:53:30 -04:00
s.glyphs.add(table.cmap[u])
2013-08-13 19:50:38 -04:00
found = True
break
if not found:
2013-08-13 19:53:30 -04:00
s.log("No glyph for Unicode value %s; skipping." % u)
2013-07-31 19:47:37 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('cmap'))
2013-08-13 19:53:30 -04:00
def prune_pre_subset(self, options):
2013-08-13 19:50:38 -04:00
if not options.legacy_cmap:
# Drop non-Unicode / non-Symbol cmaps
self.tables = [t for t in self.tables
if t.platformID == 3 and t.platEncID in [0, 1, 10]]
if not options.symbol_cmap:
self.tables = [t for t in self.tables
if t.platformID == 3 and t.platEncID in [1, 10]]
2013-08-13 20:16:16 -04:00
# TODO(behdad) Only keep one subtable?
2013-08-13 19:50:38 -04:00
# For now, drop format=0 which can't be subset_glyphs easily?
self.tables = [t for t in self.tables if t.format != 0]
2013-09-19 19:43:09 -04:00
self.numSubTables = len(self.tables)
2013-08-13 19:53:30 -04:00
return bool(self.tables)
2013-07-23 12:58:37 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('cmap'))
2013-08-13 19:53:30 -04:00
def subset_glyphs(self, s):
2013-08-13 19:50:38 -04:00
s.glyphs = s.glyphs_cmaped
for t in self.tables:
# For reasons I don't understand I need this here
# to force decompilation of the cmap format 14.
try:
2013-08-13 19:53:30 -04:00
getattr(t, "asdf")
2013-08-13 19:50:38 -04:00
except AttributeError:
pass
if t.format == 14:
2013-08-13 20:16:16 -04:00
# TODO(behdad) XXX We drop all the default-UVS mappings(g==None).
2013-08-16 10:58:25 -04:00
t.uvsDict = dict((v,[(u,g) for u,g in l if g in s.glyphs])
for v,l in t.uvsDict.iteritems())
t.uvsDict = dict((v,l) for v,l in t.uvsDict.iteritems() if l)
2013-08-13 19:50:38 -04:00
else:
2013-08-16 10:58:25 -04:00
t.cmap = dict((u,g) for u,g in t.cmap.iteritems()
if g in s.glyphs_requested or u in s.unicodes_requested)
2013-08-13 19:50:38 -04:00
self.tables = [t for t in self.tables
2013-08-14 19:47:42 -04:00
if (t.cmap if t.format != 14 else t.uvsDict)]
2013-09-19 19:43:09 -04:00
self.numSubTables = len(self.tables)
2013-08-13 20:16:16 -04:00
# TODO(behdad) Convert formats when needed.
2013-08-13 19:50:38 -04:00
# In particular, if we have a format=12 without non-BMP
# characters, either drop format=12 one or convert it
# to format=4 if there's not one.
2013-08-13 19:53:30 -04:00
return bool(self.tables)
2013-07-23 11:03:49 -04:00
2013-08-13 20:25:37 -04:00
@_add_method(fontTools.ttLib.getTableClass('name'))
2013-08-13 19:53:30 -04:00
def prune_pre_subset(self, options):
2013-08-13 19:50:38 -04:00
if '*' not in options.name_IDs:
self.names = [n for n in self.names if n.nameID in options.name_IDs]
if not options.name_legacy:
self.names = [n for n in self.names
if n.platformID == 3 and n.platEncID == 1]
if '*' not in options.name_languages:
self.names = [n for n in self.names if n.langID in options.name_languages]
2013-08-13 20:09:28 -04:00
return True # Retain even if empty
2013-07-22 15:17:12 -04:00
2013-07-22 15:06:23 -04:00
2013-08-13 20:16:16 -04:00
# TODO(behdad) OS/2 ulUnicodeRange / ulCodePageRange?
# TODO(behdad) Drop unneeded GSUB/GPOS Script/LangSys entries.
2013-08-29 18:19:22 -04:00
# TODO(behdad) Drop empty GSUB/GPOS, and GDEF if no GSUB/GPOS left
# TODO(behdad) Drop GDEF subitems if unused by lookups
2013-08-14 19:55:24 -04:00
# TODO(behdad) Avoid recursing too much (in GSUB/GPOS and in CFF)
2013-08-13 20:16:16 -04:00
# TODO(behdad) Text direction considerations.
# TODO(behdad) Text script / language considerations.
2013-09-12 16:47:52 -04:00
# TODO(behdad) Option to drop hmtx for CFF?
2013-07-24 13:34:47 -04:00
2013-08-13 20:57:59 -04:00
class Options(object):
class UnknownOptionError(Exception):
pass
2013-08-28 17:14:53 -04:00
_drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'SVG ',
2013-08-13 20:57:59 -04:00
'PCLT', 'LTSH']
_drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill'] # Graphite
_drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL'] # Color
_no_subset_tables_default = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2',
'loca', 'name', 'cvt ', 'fpgm', 'prep']
_hinting_tables_default = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
# Based on HarfBuzz shapers
_layout_features_groups = {
# Default shaper
'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
'vertical': ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
'ltr': ['ltra', 'ltrm'],
'rtl': ['rtla', 'rtlm'],
# Complex shapers
'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3',
'cswh', 'mset'],
'hangul': ['ljmo', 'vjmo', 'tjmo'],
'tibetal': ['abvs', 'blws', 'abvm', 'blwm'],
'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half',
'abvf', 'pstf', 'cfar', 'vatu', 'cjct', 'init', 'pres',
'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
}
_layout_features_default = _uniq_sort(sum(
_layout_features_groups.itervalues(), []))
drop_tables = _drop_tables_default
no_subset_tables = _no_subset_tables_default
hinting_tables = _hinting_tables_default
layout_features = _layout_features_default
hinting = False
glyph_names = False
legacy_cmap = False
symbol_cmap = False
name_IDs = [1, 2] # Family and Style
name_legacy = False
name_languages = [0x0409] # English
notdef_glyph = True # gid0 for TrueType / .notdef for CFF
2013-08-29 18:02:48 -04:00
notdef_outline = False # No need for notdef to have an outline really
recommended_glyphs = False # gid1, gid2, gid3 for TrueType
2013-08-16 12:42:34 -04:00
recalc_bounds = False # Recalculate font bounding boxes
canonical_order = False # Order tables as recommended
flavor = None # May be 'woff'
2013-08-13 20:57:59 -04:00
def __init__(self, **kwargs):
self.set(**kwargs)
def set(self, **kwargs):
for k,v in kwargs.iteritems():
if not hasattr(self, k):
2013-09-03 18:29:58 -04:00
raise self.UnknownOptionError("Unknown option '%s'" % k)
2013-08-13 20:57:59 -04:00
setattr(self, k, v)
def parse_opts(self, argv, ignore_unknown=False):
ret = []
opts = {}
for a in argv:
orig_a = a
if not a.startswith('--'):
ret.append(a)
continue
a = a[2:]
i = a.find('=')
op = '='
2013-08-13 20:57:59 -04:00
if i == -1:
if a.startswith("no-"):
k = a[3:]
v = False
else:
k = a
v = True
else:
k = a[:i]
if k[-1] in "-+":
op = k[-1]+'=' # Ops is '-=' or '+=' now.
k = k[:-1]
2013-08-13 20:57:59 -04:00
v = a[i+1:]
k = k.replace('-', '_')
if not hasattr(self, k):
if ignore_unknown == True or k in ignore_unknown:
ret.append(orig_a)
continue
else:
raise self.UnknownOptionError("Unknown option '%s'" % a)
2013-07-31 15:59:21 -04:00
2013-08-13 20:57:59 -04:00
ov = getattr(self, k)
if isinstance(ov, bool):
v = bool(v)
elif isinstance(ov, int):
v = int(v)
elif isinstance(ov, list):
vv = v.split(',')
if vv == ['']:
vv = []
2013-08-16 14:44:09 -04:00
vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv]
if op == '=':
v = vv
elif op == '+=':
v = ov
v.extend(vv)
elif op == '-=':
v = ov
for x in vv:
if x in v:
v.remove(x)
else:
assert 0
2013-08-13 19:50:38 -04:00
2013-08-13 20:57:59 -04:00
opts[k] = v
self.set(**opts)
2013-08-13 19:50:38 -04:00
2013-08-13 20:57:59 -04:00
return ret
2013-08-13 19:50:38 -04:00
2013-08-13 20:57:59 -04:00
class Subsetter(object):
2013-08-13 19:53:30 -04:00
def __init__(self, options=None, log=None):
2013-08-13 19:50:38 -04:00
if not log:
log = Logger()
if not options:
options = Options()
self.options = options
self.log = log
2013-08-13 19:53:30 -04:00
self.unicodes_requested = set()
self.glyphs_requested = set()
self.glyphs = set()
def populate(self, glyphs=[], unicodes=[], text=""):
self.unicodes_requested.update(unicodes)
if isinstance(text, str):
text = text.decode("utf8")
2013-08-13 19:50:38 -04:00
for u in text:
2013-08-13 19:53:30 -04:00
self.unicodes_requested.add(ord(u))
self.glyphs_requested.update(glyphs)
self.glyphs.update(glyphs)
2013-08-13 19:50:38 -04:00
2013-08-13 20:48:33 -04:00
def _prune_pre_subset(self, font):
2013-08-13 19:50:38 -04:00
for tag in font.keys():
if tag == 'GlyphOrder': continue
2013-08-13 19:53:30 -04:00
if(tag in self.options.drop_tables or
(tag in self.options.hinting_tables and not self.options.hinting)):
self.log(tag, "dropped")
2013-08-13 19:50:38 -04:00
del font[tag]
continue
clazz = fontTools.ttLib.getTableClass(tag)
2013-08-13 19:53:30 -04:00
if hasattr(clazz, 'prune_pre_subset'):
2013-08-13 19:50:38 -04:00
table = font[tag]
self.log.lapse("load '%s'" % tag)
2013-08-13 19:53:30 -04:00
retain = table.prune_pre_subset(self.options)
self.log.lapse("prune '%s'" % tag)
2013-08-13 19:50:38 -04:00
if not retain:
2013-08-13 19:53:30 -04:00
self.log(tag, "pruned to empty; dropped")
2013-08-13 19:50:38 -04:00
del font[tag]
continue
else:
2013-08-13 19:53:30 -04:00
self.log(tag, "pruned")
2013-08-13 19:50:38 -04:00
2013-08-13 20:48:33 -04:00
def _closure_glyphs(self, font):
2013-08-13 19:50:38 -04:00
2013-08-13 19:53:30 -04:00
self.glyphs = self.glyphs_requested.copy()
2013-08-13 19:50:38 -04:00
if 'cmap' in font:
2013-08-13 19:53:30 -04:00
font['cmap'].closure_glyphs(self)
2013-08-13 19:50:38 -04:00
self.glyphs_cmaped = self.glyphs
if self.options.notdef_glyph:
if 'glyf' in font:
self.glyphs.add(font.getGlyphName(0))
self.log("Added gid0 to subset")
else:
self.glyphs.add('.notdef')
self.log("Added .notdef to subset")
if self.options.recommended_glyphs:
2013-08-13 19:50:38 -04:00
if 'glyf' in font:
2013-08-13 19:53:30 -04:00
for i in range(4):
self.glyphs.add(font.getGlyphName(i))
self.log("Added first four glyphs to subset")
2013-08-13 19:50:38 -04:00
if 'GSUB' in font:
2013-08-13 19:53:30 -04:00
self.log("Closing glyph list over 'GSUB': %d glyphs before" %
len(self.glyphs))
self.log.glyphs(self.glyphs, font=font)
font['GSUB'].closure_glyphs(self)
self.log("Closed glyph list over 'GSUB': %d glyphs after" %
len(self.glyphs))
self.log.glyphs(self.glyphs, font=font)
self.log.lapse("close glyph list over 'GSUB'")
self.glyphs_gsubed = self.glyphs.copy()
2013-08-13 19:50:38 -04:00
if 'glyf' in font:
2013-08-13 19:53:30 -04:00
self.log("Closing glyph list over 'glyf': %d glyphs before" %
len(self.glyphs))
self.log.glyphs(self.glyphs, font=font)
font['glyf'].closure_glyphs(self)
self.log("Closed glyph list over 'glyf': %d glyphs after" %
len(self.glyphs))
self.log.glyphs(self.glyphs, font=font)
self.log.lapse("close glyph list over 'glyf'")
self.glyphs_glyfed = self.glyphs.copy()
2013-08-13 19:50:38 -04:00
2013-08-13 19:53:30 -04:00
self.glyphs_all = self.glyphs.copy()
2013-08-13 19:50:38 -04:00
2013-08-13 19:53:30 -04:00
self.log("Retaining %d glyphs: " % len(self.glyphs_all))
2013-08-13 19:50:38 -04:00
2013-08-13 20:48:33 -04:00
def _subset_glyphs(self, font):
2013-08-13 19:50:38 -04:00
for tag in font.keys():
if tag == 'GlyphOrder': continue
clazz = fontTools.ttLib.getTableClass(tag)
if tag in self.options.no_subset_tables:
2013-08-13 19:53:30 -04:00
self.log(tag, "subsetting not needed")
elif hasattr(clazz, 'subset_glyphs'):
2013-08-13 19:50:38 -04:00
table = font[tag]
self.glyphs = self.glyphs_all
2013-08-13 19:53:30 -04:00
retain = table.subset_glyphs(self)
2013-08-13 19:50:38 -04:00
self.glyphs = self.glyphs_all
2013-08-13 19:53:30 -04:00
self.log.lapse("subset '%s'" % tag)
2013-08-13 19:50:38 -04:00
if not retain:
2013-08-13 19:53:30 -04:00
self.log(tag, "subsetted to empty; dropped")
2013-08-13 19:50:38 -04:00
del font[tag]
else:
2013-08-13 19:53:30 -04:00
self.log(tag, "subsetted")
2013-08-13 19:50:38 -04:00
else:
2013-08-13 19:53:30 -04:00
self.log(tag, "NOT subset; don't know how to subset; dropped")
2013-08-13 19:50:38 -04:00
del font[tag]
glyphOrder = font.getGlyphOrder()
glyphOrder = [g for g in glyphOrder if g in self.glyphs_all]
2013-08-13 19:53:30 -04:00
font.setGlyphOrder(glyphOrder)
font._buildReverseGlyphOrderDict()
self.log.lapse("subset GlyphOrder")
2013-08-13 19:50:38 -04:00
2013-08-13 20:48:33 -04:00
def _prune_post_subset(self, font):
2013-08-13 19:50:38 -04:00
for tag in font.keys():
if tag == 'GlyphOrder': continue
clazz = fontTools.ttLib.getTableClass(tag)
2013-08-13 19:53:30 -04:00
if hasattr(clazz, 'prune_post_subset'):
2013-08-13 19:50:38 -04:00
table = font[tag]
2013-08-13 19:53:30 -04:00
retain = table.prune_post_subset(self.options)
self.log.lapse("prune '%s'" % tag)
2013-08-13 19:50:38 -04:00
if not retain:
2013-08-13 19:53:30 -04:00
self.log(tag, "pruned to empty; dropped")
2013-08-13 19:50:38 -04:00
del font[tag]
else:
2013-08-13 19:53:30 -04:00
self.log(tag, "pruned")
2013-08-13 19:50:38 -04:00
2013-08-13 19:53:30 -04:00
def subset(self, font):
2013-08-13 19:50:38 -04:00
2013-08-13 20:48:33 -04:00
self._prune_pre_subset(font)
self._closure_glyphs(font)
self._subset_glyphs(font)
self._prune_post_subset(font)
2013-07-31 20:16:24 -04:00
2013-08-01 12:05:26 -04:00
2013-08-13 20:10:17 -04:00
class Logger(object):
2013-07-31 15:03:43 -04:00
2013-08-13 19:53:30 -04:00
def __init__(self, verbose=False, xml=False, timing=False):
2013-08-13 19:50:38 -04:00
self.verbose = verbose
self.xml = xml
self.timing = timing
2013-08-13 19:53:30 -04:00
self.last_time = self.start_time = time.time()
2013-08-13 19:50:38 -04:00
2013-08-13 19:53:30 -04:00
def parse_opts(self, argv):
2013-08-13 19:50:38 -04:00
argv = argv[:]
for v in ['verbose', 'xml', 'timing']:
if "--"+v in argv:
2013-08-13 19:53:30 -04:00
setattr(self, v, True)
argv.remove("--"+v)
2013-08-13 19:50:38 -04:00
return argv
2013-08-13 19:53:30 -04:00
def __call__(self, *things):
2013-08-13 19:50:38 -04:00
if not self.verbose:
return
2013-08-13 19:53:30 -04:00
print ' '.join(str(x) for x in things)
2013-08-13 19:50:38 -04:00
2013-08-13 19:53:30 -04:00
def lapse(self, *things):
2013-08-13 19:50:38 -04:00
if not self.timing:
return
2013-08-13 19:53:30 -04:00
new_time = time.time()
print "Took %0.3fs to %s" %(new_time - self.last_time,
' '.join(str(x) for x in things))
2013-08-13 19:50:38 -04:00
self.last_time = new_time
2013-08-14 12:55:42 -04:00
def glyphs(self, glyphs, font=None):
2013-08-13 19:53:30 -04:00
self("Names: ", sorted(glyphs))
2013-08-13 19:50:38 -04:00
if font:
2013-08-13 19:53:30 -04:00
reverseGlyphMap = font.getReverseGlyphMap()
self("Gids : ", sorted(reverseGlyphMap[g] for g in glyphs))
2013-08-13 19:50:38 -04:00
2013-08-13 19:53:30 -04:00
def font(self, font, file=sys.stdout):
2013-08-13 19:50:38 -04:00
if not self.xml:
return
2013-09-18 19:01:16 -04:00
from fontTools.misc import xmlWriter
2013-08-13 19:53:30 -04:00
writer = xmlWriter.XMLWriter(file)
2013-08-19 14:44:49 -04:00
font.disassembleInstructions = False # Work around ttLib bug
2013-08-13 19:50:38 -04:00
for tag in font.keys():
2013-08-13 19:53:30 -04:00
writer.begintag(tag)
writer.newline()
2013-08-13 19:50:38 -04:00
font[tag].toXML(writer, font)
2013-08-13 19:53:30 -04:00
writer.endtag(tag)
writer.newline()
2013-08-15 12:17:21 -04:00
def load_font(fontFile,
2013-08-15 18:29:25 -04:00
options,
2013-08-15 12:17:21 -04:00
checkChecksums=False,
dontLoadGlyphNames=False):
2013-08-19 14:44:49 -04:00
font = fontTools.ttLib.TTFont(fontFile,
checkChecksums=checkChecksums,
recalcBBoxes=options.recalc_bounds)
2013-08-13 19:50:38 -04:00
# Hack:
#
# If we don't need glyph names, change 'post' class to not try to
# load them. It avoid lots of headache with broken fonts as well
# as loading time.
#
# Ideally ttLib should provide a way to ask it to skip loading
# glyph names. But it currently doesn't provide such a thing.
#
2013-08-15 12:17:21 -04:00
if dontLoadGlyphNames:
2013-08-13 19:50:38 -04:00
post = fontTools.ttLib.getTableClass('post')
saved = post.decode_format_2_0
post.decode_format_2_0 = post.decode_format_3_0
f = font['post']
if f.formatType == 2.0:
f.formatType = 3.0
post.decode_format_2_0 = saved
2013-08-13 12:20:59 -04:00
2013-08-13 19:50:38 -04:00
return font
2013-08-13 12:20:59 -04:00
2013-08-16 12:42:34 -04:00
def save_font(font, outfile, options):
if options.flavor and not hasattr(font, 'flavor'):
raise Exception("fonttools version does not support flavors.")
font.flavor = options.flavor
2013-08-16 12:42:34 -04:00
font.save(outfile, reorderTables=options.canonical_order)
2013-08-15 12:09:55 -04:00
def main(args):
2013-08-13 12:20:59 -04:00
2013-08-13 19:53:30 -04:00
log = Logger()
args = log.parse_opts(args)
2013-08-13 19:50:38 -04:00
2013-08-14 12:55:42 -04:00
options = Options()
2013-08-13 19:53:30 -04:00
args = options.parse_opts(args, ignore_unknown=['text'])
2013-08-13 19:50:38 -04:00
2013-08-13 19:53:30 -04:00
if len(args) < 2:
print >>sys.stderr, "usage: pyftsubset font-file glyph... [--text=ABC]... [--option=value]..."
2013-08-13 19:53:30 -04:00
sys.exit(1)
2013-08-13 19:50:38 -04:00
fontfile = args[0]
args = args[1:]
2013-08-15 12:17:21 -04:00
dontLoadGlyphNames =(not options.glyph_names and
2013-08-13 19:53:30 -04:00
all(any(g.startswith(p)
2013-08-13 19:50:38 -04:00
for p in ['gid', 'glyph', 'uni', 'U+'])
for g in args))
2013-08-15 18:29:25 -04:00
font = load_font(fontfile, options, dontLoadGlyphNames=dontLoadGlyphNames)
2013-08-13 19:53:30 -04:00
subsetter = Subsetter(options=options, log=log)
log.lapse("load font")
2013-08-13 19:50:38 -04:00
names = font.getGlyphNames()
2013-08-13 19:53:30 -04:00
log.lapse("loading glyph names")
2013-08-13 19:50:38 -04:00
glyphs = []
unicodes = []
text = ""
for g in args:
if g == '*':
glyphs.extend(font.getGlyphOrder())
continue
2013-08-13 19:50:38 -04:00
if g in names:
2013-08-13 19:53:30 -04:00
glyphs.append(g)
2013-08-13 19:50:38 -04:00
continue
2013-08-13 19:53:30 -04:00
if g.startswith('--text='):
2013-08-13 19:50:38 -04:00
text += g[7:]
continue
2013-08-13 19:53:30 -04:00
if g.startswith('uni') or g.startswith('U+'):
if g.startswith('uni') and len(g) > 3:
2013-08-13 19:50:38 -04:00
g = g[3:]
2013-08-13 19:53:30 -04:00
elif g.startswith('U+') and len(g) > 2:
2013-08-13 19:50:38 -04:00
g = g[2:]
2013-08-13 19:53:30 -04:00
u = int(g, 16)
unicodes.append(u)
2013-08-13 19:50:38 -04:00
continue
2013-08-13 19:53:30 -04:00
if g.startswith('gid') or g.startswith('glyph'):
if g.startswith('gid') and len(g) > 3:
2013-08-13 19:50:38 -04:00
g = g[3:]
2013-08-13 19:53:30 -04:00
elif g.startswith('glyph') and len(g) > 5:
2013-08-13 19:50:38 -04:00
g = g[5:]
try:
2013-08-13 19:53:30 -04:00
glyphs.append(font.getGlyphName(int(g), requireReal=1))
2013-08-13 19:50:38 -04:00
except ValueError:
2013-08-13 19:53:30 -04:00
raise Exception("Invalid glyph identifier: %s" % g)
2013-08-13 19:50:38 -04:00
continue
2013-08-13 19:53:30 -04:00
raise Exception("Invalid glyph identifier: %s" % g)
log.lapse("compile glyph list")
log("Unicodes:", unicodes)
log("Glyphs:", glyphs)
2013-08-13 19:50:38 -04:00
2013-08-13 19:53:30 -04:00
subsetter.populate(glyphs=glyphs, unicodes=unicodes, text=text)
subsetter.subset(font)
2013-08-13 19:50:38 -04:00
outfile = fontfile + '.subset'
save_font (font, outfile, options)
2013-08-13 19:53:30 -04:00
log.lapse("compile and save font")
2013-08-13 19:50:38 -04:00
log.last_time = log.start_time
2013-08-13 19:53:30 -04:00
log.lapse("make one with everything(TOTAL TIME)")
2013-08-13 19:50:38 -04:00
if log.verbose:
import os
log("Input font: %d bytes" % os.path.getsize(fontfile))
log("Subset font: %d bytes" % os.path.getsize(outfile))
2013-08-13 19:53:30 -04:00
log.font(font)
2013-07-24 13:34:47 -04:00
2013-08-13 20:13:33 -04:00
font.close()
__all__ = [
'Options',
'Subsetter',
'Logger',
'load_font',
'save_font',
'main'
]
2013-07-24 13:34:47 -04:00
if __name__ == '__main__':
main(sys.argv[1:])