subset.py revision 7e97247925dab1616971a2fdb94d8462cf3e5d84
1# Copyright 2013 Google, Inc. All Rights Reserved.
2#
3# Google Author(s): Behdad Esfahbod
4
5"""Python OpenType Layout Subsetter.
6
7Later grown into full OpenType subsetter, supporting all standard tables.
8"""
9
10import sys
11import struct
12import time
13import array
14
15from fontTools import ttLib
16from fontTools.ttLib.tables import otTables
17from fontTools.misc import psCharStrings
18from fontTools.pens import basePen
19
20
21def _add_method(*clazzes):
22  """Returns a decorator function that adds a new method to one or
23  more classes."""
24  def wrapper(method):
25    for clazz in clazzes:
26      assert clazz.__name__ != 'DefaultTable', 'Oops, table class not found.'
27      assert not hasattr(clazz, method.func_name), \
28          "Oops, class '%s' has method '%s'." % (clazz.__name__,
29                                                 method.func_name)
30      setattr(clazz, method.func_name, method)
31    return None
32  return wrapper
33
34def _uniq_sort(l):
35  return sorted(set(l))
36
37def _set_update(s, *others):
38  # Jython's set.update only takes one other argument.
39  # Emulate real set.update...
40  for other in others:
41    s.update(other)
42
43
44@_add_method(otTables.Coverage)
45def intersect(self, glyphs):
46  "Returns ascending list of matching coverage values."
47  return [i for i,g in enumerate(self.glyphs) if g in glyphs]
48
49@_add_method(otTables.Coverage)
50def intersect_glyphs(self, glyphs):
51  "Returns set of intersecting glyphs."
52  return set(g for g in self.glyphs if g in glyphs)
53
54@_add_method(otTables.Coverage)
55def subset(self, glyphs):
56  "Returns ascending list of remaining coverage values."
57  indices = self.intersect(glyphs)
58  self.glyphs = [g for g in self.glyphs if g in glyphs]
59  return indices
60
61@_add_method(otTables.Coverage)
62def remap(self, coverage_map):
63  "Remaps coverage."
64  self.glyphs = [self.glyphs[i] for i in coverage_map]
65
66@_add_method(otTables.ClassDef)
67def intersect(self, glyphs):
68  "Returns ascending list of matching class values."
69  return _uniq_sort(
70     ([0] if any(g not in self.classDefs for g in glyphs) else []) +
71      [v for g,v in self.classDefs.iteritems() if g in glyphs])
72
73@_add_method(otTables.ClassDef)
74def intersect_class(self, glyphs, klass):
75  "Returns set of glyphs matching class."
76  if klass == 0:
77    return set(g for g in glyphs if g not in self.classDefs)
78  return set(g for g,v in self.classDefs.iteritems()
79              if v == klass and g in glyphs)
80
81@_add_method(otTables.ClassDef)
82def subset(self, glyphs, remap=False):
83  "Returns ascending list of remaining classes."
84  self.classDefs = dict((g,v) for g,v in self.classDefs.iteritems() if g in glyphs)
85  # Note: while class 0 has the special meaning of "not matched",
86  # if no glyph will ever /not match/, we can optimize class 0 out too.
87  indices = _uniq_sort(
88     ([0] if any(g not in self.classDefs for g in glyphs) else []) +
89      self.classDefs.values())
90  if remap:
91    self.remap(indices)
92  return indices
93
94@_add_method(otTables.ClassDef)
95def remap(self, class_map):
96  "Remaps classes."
97  self.classDefs = dict((g,class_map.index(v))
98                         for g,v in self.classDefs.iteritems())
99
100@_add_method(otTables.SingleSubst)
101def closure_glyphs(self, s, cur_glyphs=None):
102  if cur_glyphs == None: cur_glyphs = s.glyphs
103  if self.Format in [1, 2]:
104    s.glyphs.update(v for g,v in self.mapping.iteritems() if g in cur_glyphs)
105  else:
106    assert 0, "unknown format: %s" % self.Format
107
108@_add_method(otTables.SingleSubst)
109def subset_glyphs(self, s):
110  if self.Format in [1, 2]:
111    self.mapping = dict((g,v) for g,v in self.mapping.iteritems()
112                        if g in s.glyphs and v in s.glyphs)
113    return bool(self.mapping)
114  else:
115    assert 0, "unknown format: %s" % self.Format
116
117@_add_method(otTables.MultipleSubst)
118def closure_glyphs(self, s, cur_glyphs=None):
119  if cur_glyphs == None: cur_glyphs = s.glyphs
120  if self.Format == 1:
121    indices = self.Coverage.intersect(cur_glyphs)
122    _set_update(s.glyphs, *(self.Sequence[i].Substitute for i in indices))
123  else:
124    assert 0, "unknown format: %s" % self.Format
125
126@_add_method(otTables.MultipleSubst)
127def subset_glyphs(self, s):
128  if self.Format == 1:
129    indices = self.Coverage.subset(s.glyphs)
130    self.Sequence = [self.Sequence[i] for i in indices]
131    # Now drop rules generating glyphs we don't want
132    indices = [i for i,seq in enumerate(self.Sequence)
133         if all(sub in s.glyphs for sub in seq.Substitute)]
134    self.Sequence = [self.Sequence[i] for i in indices]
135    self.Coverage.remap(indices)
136    self.SequenceCount = len(self.Sequence)
137    return bool(self.SequenceCount)
138  else:
139    assert 0, "unknown format: %s" % self.Format
140
141@_add_method(otTables.AlternateSubst)
142def closure_glyphs(self, s, cur_glyphs=None):
143  if cur_glyphs == None: cur_glyphs = s.glyphs
144  if self.Format == 1:
145    _set_update(s.glyphs, *(vlist for g,vlist in self.alternates.iteritems()
146                            if g in cur_glyphs))
147  else:
148    assert 0, "unknown format: %s" % self.Format
149
150@_add_method(otTables.AlternateSubst)
151def subset_glyphs(self, s):
152  if self.Format == 1:
153    self.alternates = dict((g,vlist)
154                           for g,vlist in self.alternates.iteritems()
155                           if g in s.glyphs and
156                              all(v in s.glyphs for v in vlist))
157    return bool(self.alternates)
158  else:
159    assert 0, "unknown format: %s" % self.Format
160
161@_add_method(otTables.LigatureSubst)
162def closure_glyphs(self, s, cur_glyphs=None):
163  if cur_glyphs == None: cur_glyphs = s.glyphs
164  if self.Format == 1:
165    _set_update(s.glyphs, *([seq.LigGlyph for seq in seqs
166                             if all(c in s.glyphs for c in seq.Component)]
167                            for g,seqs in self.ligatures.iteritems()
168                            if g in cur_glyphs))
169  else:
170    assert 0, "unknown format: %s" % self.Format
171
172@_add_method(otTables.LigatureSubst)
173def subset_glyphs(self, s):
174  if self.Format == 1:
175    self.ligatures = dict((g,v) for g,v in self.ligatures.iteritems()
176                          if g in s.glyphs)
177    self.ligatures = dict((g,[seq for seq in seqs
178                              if seq.LigGlyph in s.glyphs and
179                                 all(c in s.glyphs for c in seq.Component)])
180                           for g,seqs in self.ligatures.iteritems())
181    self.ligatures = dict((g,v) for g,v in self.ligatures.iteritems() if v)
182    return bool(self.ligatures)
183  else:
184    assert 0, "unknown format: %s" % self.Format
185
186@_add_method(otTables.ReverseChainSingleSubst)
187def closure_glyphs(self, s, cur_glyphs=None):
188  if cur_glyphs == None: cur_glyphs = s.glyphs
189  if self.Format == 1:
190    indices = self.Coverage.intersect(cur_glyphs)
191    if(not indices or
192        not all(c.intersect(s.glyphs)
193                 for c in self.LookAheadCoverage + self.BacktrackCoverage)):
194      return
195    s.glyphs.update(self.Substitute[i] for i in indices)
196  else:
197    assert 0, "unknown format: %s" % self.Format
198
199@_add_method(otTables.ReverseChainSingleSubst)
200def subset_glyphs(self, s):
201  if self.Format == 1:
202    indices = self.Coverage.subset(s.glyphs)
203    self.Substitute = [self.Substitute[i] for i in indices]
204    # Now drop rules generating glyphs we don't want
205    indices = [i for i,sub in enumerate(self.Substitute)
206         if sub in s.glyphs]
207    self.Substitute = [self.Substitute[i] for i in indices]
208    self.Coverage.remap(indices)
209    self.GlyphCount = len(self.Substitute)
210    return bool(self.GlyphCount and
211                 all(c.subset(s.glyphs)
212                      for c in self.LookAheadCoverage+self.BacktrackCoverage))
213  else:
214    assert 0, "unknown format: %s" % self.Format
215
216@_add_method(otTables.SinglePos)
217def subset_glyphs(self, s):
218  if self.Format == 1:
219    return len(self.Coverage.subset(s.glyphs))
220  elif self.Format == 2:
221    indices = self.Coverage.subset(s.glyphs)
222    self.Value = [self.Value[i] for i in indices]
223    self.ValueCount = len(self.Value)
224    return bool(self.ValueCount)
225  else:
226    assert 0, "unknown format: %s" % self.Format
227
228@_add_method(otTables.SinglePos)
229def prune_post_subset(self, options):
230  if not options.hinting:
231    # Drop device tables
232    self.ValueFormat &= ~0x00F0
233  return True
234
235@_add_method(otTables.PairPos)
236def subset_glyphs(self, s):
237  if self.Format == 1:
238    indices = self.Coverage.subset(s.glyphs)
239    self.PairSet = [self.PairSet[i] for i in indices]
240    for p in self.PairSet:
241      p.PairValueRecord = [r for r in p.PairValueRecord
242                           if r.SecondGlyph in s.glyphs]
243      p.PairValueCount = len(p.PairValueRecord)
244    self.PairSet = [p for p in self.PairSet if p.PairValueCount]
245    self.PairSetCount = len(self.PairSet)
246    return bool(self.PairSetCount)
247  elif self.Format == 2:
248    class1_map = self.ClassDef1.subset(s.glyphs, remap=True)
249    class2_map = self.ClassDef2.subset(s.glyphs, remap=True)
250    self.Class1Record = [self.Class1Record[i] for i in class1_map]
251    for c in self.Class1Record:
252      c.Class2Record = [c.Class2Record[i] for i in class2_map]
253    self.Class1Count = len(class1_map)
254    self.Class2Count = len(class2_map)
255    return bool(self.Class1Count and
256                 self.Class2Count and
257                 self.Coverage.subset(s.glyphs))
258  else:
259    assert 0, "unknown format: %s" % self.Format
260
261@_add_method(otTables.PairPos)
262def prune_post_subset(self, options):
263  if not options.hinting:
264    # Drop device tables
265    self.ValueFormat1 &= ~0x00F0
266    self.ValueFormat2 &= ~0x00F0
267  return True
268
269@_add_method(otTables.CursivePos)
270def subset_glyphs(self, s):
271  if self.Format == 1:
272    indices = self.Coverage.subset(s.glyphs)
273    self.EntryExitRecord = [self.EntryExitRecord[i] for i in indices]
274    self.EntryExitCount = len(self.EntryExitRecord)
275    return bool(self.EntryExitCount)
276  else:
277    assert 0, "unknown format: %s" % self.Format
278
279@_add_method(otTables.Anchor)
280def prune_hints(self):
281  # Drop device tables / contour anchor point
282  self.Format = 1
283
284@_add_method(otTables.CursivePos)
285def prune_post_subset(self, options):
286  if not options.hinting:
287    for rec in self.EntryExitRecord:
288      if rec.EntryAnchor: rec.EntryAnchor.prune_hints()
289      if rec.ExitAnchor: rec.ExitAnchor.prune_hints()
290  return True
291
292@_add_method(otTables.MarkBasePos)
293def subset_glyphs(self, s):
294  if self.Format == 1:
295    mark_indices = self.MarkCoverage.subset(s.glyphs)
296    self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i]
297                                 for i in mark_indices]
298    self.MarkArray.MarkCount = len(self.MarkArray.MarkRecord)
299    base_indices = self.BaseCoverage.subset(s.glyphs)
300    self.BaseArray.BaseRecord = [self.BaseArray.BaseRecord[i]
301                                 for i in base_indices]
302    self.BaseArray.BaseCount = len(self.BaseArray.BaseRecord)
303    # Prune empty classes
304    class_indices = _uniq_sort(v.Class for v in self.MarkArray.MarkRecord)
305    self.ClassCount = len(class_indices)
306    for m in self.MarkArray.MarkRecord:
307      m.Class = class_indices.index(m.Class)
308    for b in self.BaseArray.BaseRecord:
309      b.BaseAnchor = [b.BaseAnchor[i] for i in class_indices]
310    return bool(self.ClassCount and
311                 self.MarkArray.MarkCount and
312                 self.BaseArray.BaseCount)
313  else:
314    assert 0, "unknown format: %s" % self.Format
315
316@_add_method(otTables.MarkBasePos)
317def prune_post_subset(self, options):
318    if not options.hinting:
319      for m in self.MarkArray.MarkRecord:
320        if m.MarkAnchor:
321          m.MarkAnchor.prune_hints()
322      for b in self.BaseArray.BaseRecord:
323        for a in b.BaseAnchor:
324          if a:
325            a.prune_hints()
326    return True
327
328@_add_method(otTables.MarkLigPos)
329def subset_glyphs(self, s):
330  if self.Format == 1:
331    mark_indices = self.MarkCoverage.subset(s.glyphs)
332    self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i]
333                                 for i in mark_indices]
334    self.MarkArray.MarkCount = len(self.MarkArray.MarkRecord)
335    ligature_indices = self.LigatureCoverage.subset(s.glyphs)
336    self.LigatureArray.LigatureAttach = [self.LigatureArray.LigatureAttach[i]
337                                         for i in ligature_indices]
338    self.LigatureArray.LigatureCount = len(self.LigatureArray.LigatureAttach)
339    # Prune empty classes
340    class_indices = _uniq_sort(v.Class for v in self.MarkArray.MarkRecord)
341    self.ClassCount = len(class_indices)
342    for m in self.MarkArray.MarkRecord:
343      m.Class = class_indices.index(m.Class)
344    for l in self.LigatureArray.LigatureAttach:
345      for c in l.ComponentRecord:
346        c.LigatureAnchor = [c.LigatureAnchor[i] for i in class_indices]
347    return bool(self.ClassCount and
348                 self.MarkArray.MarkCount and
349                 self.LigatureArray.LigatureCount)
350  else:
351    assert 0, "unknown format: %s" % self.Format
352
353@_add_method(otTables.MarkLigPos)
354def prune_post_subset(self, options):
355    if not options.hinting:
356      for m in self.MarkArray.MarkRecord:
357        if m.MarkAnchor:
358          m.MarkAnchor.prune_hints()
359      for l in self.LigatureArray.LigatureAttach:
360        for c in l.ComponentRecord:
361          for a in c.LigatureAnchor:
362            if a:
363              a.prune_hints()
364    return True
365
366@_add_method(otTables.MarkMarkPos)
367def subset_glyphs(self, s):
368  if self.Format == 1:
369    mark1_indices = self.Mark1Coverage.subset(s.glyphs)
370    self.Mark1Array.MarkRecord = [self.Mark1Array.MarkRecord[i]
371                                  for i in mark1_indices]
372    self.Mark1Array.MarkCount = len(self.Mark1Array.MarkRecord)
373    mark2_indices = self.Mark2Coverage.subset(s.glyphs)
374    self.Mark2Array.Mark2Record = [self.Mark2Array.Mark2Record[i]
375                                   for i in mark2_indices]
376    self.Mark2Array.MarkCount = len(self.Mark2Array.Mark2Record)
377    # Prune empty classes
378    class_indices = _uniq_sort(v.Class for v in self.Mark1Array.MarkRecord)
379    self.ClassCount = len(class_indices)
380    for m in self.Mark1Array.MarkRecord:
381      m.Class = class_indices.index(m.Class)
382    for b in self.Mark2Array.Mark2Record:
383      b.Mark2Anchor = [b.Mark2Anchor[i] for i in class_indices]
384    return bool(self.ClassCount and
385                 self.Mark1Array.MarkCount and
386                 self.Mark2Array.MarkCount)
387  else:
388    assert 0, "unknown format: %s" % self.Format
389
390@_add_method(otTables.MarkMarkPos)
391def prune_post_subset(self, options):
392    if not options.hinting:
393      # Drop device tables or contour anchor point
394      for m in self.Mark1Array.MarkRecord:
395        if m.MarkAnchor:
396          m.MarkAnchor.prune_hints()
397      for b in self.Mark2Array.Mark2Record:
398        for m in b.Mark2Anchor:
399          if m:
400            m.prune_hints()
401    return True
402
403@_add_method(otTables.SingleSubst,
404             otTables.MultipleSubst,
405             otTables.AlternateSubst,
406             otTables.LigatureSubst,
407             otTables.ReverseChainSingleSubst,
408             otTables.SinglePos,
409             otTables.PairPos,
410             otTables.CursivePos,
411             otTables.MarkBasePos,
412             otTables.MarkLigPos,
413             otTables.MarkMarkPos)
414def subset_lookups(self, lookup_indices):
415  pass
416
417@_add_method(otTables.SingleSubst,
418             otTables.MultipleSubst,
419             otTables.AlternateSubst,
420             otTables.LigatureSubst,
421             otTables.ReverseChainSingleSubst,
422             otTables.SinglePos,
423             otTables.PairPos,
424             otTables.CursivePos,
425             otTables.MarkBasePos,
426             otTables.MarkLigPos,
427             otTables.MarkMarkPos)
428def collect_lookups(self):
429  return []
430
431@_add_method(otTables.SingleSubst,
432             otTables.MultipleSubst,
433             otTables.AlternateSubst,
434             otTables.LigatureSubst,
435             otTables.ContextSubst,
436             otTables.ChainContextSubst,
437             otTables.ReverseChainSingleSubst,
438             otTables.SinglePos,
439             otTables.PairPos,
440             otTables.CursivePos,
441             otTables.MarkBasePos,
442             otTables.MarkLigPos,
443             otTables.MarkMarkPos,
444             otTables.ContextPos,
445             otTables.ChainContextPos)
446def prune_pre_subset(self, options):
447  return True
448
449@_add_method(otTables.SingleSubst,
450             otTables.MultipleSubst,
451             otTables.AlternateSubst,
452             otTables.LigatureSubst,
453             otTables.ReverseChainSingleSubst,
454             otTables.ContextSubst,
455             otTables.ChainContextSubst,
456             otTables.ContextPos,
457             otTables.ChainContextPos)
458def prune_post_subset(self, options):
459  return True
460
461@_add_method(otTables.SingleSubst,
462             otTables.AlternateSubst,
463             otTables.ReverseChainSingleSubst)
464def may_have_non_1to1(self):
465  return False
466
467@_add_method(otTables.MultipleSubst,
468             otTables.LigatureSubst,
469             otTables.ContextSubst,
470             otTables.ChainContextSubst)
471def may_have_non_1to1(self):
472  return True
473
474@_add_method(otTables.ContextSubst,
475             otTables.ChainContextSubst,
476             otTables.ContextPos,
477             otTables.ChainContextPos)
478def __classify_context(self):
479
480  class ContextHelper(object):
481    def __init__(self, klass, Format):
482      if klass.__name__.endswith('Subst'):
483        Typ = 'Sub'
484        Type = 'Subst'
485      else:
486        Typ = 'Pos'
487        Type = 'Pos'
488      if klass.__name__.startswith('Chain'):
489        Chain = 'Chain'
490      else:
491        Chain = ''
492      ChainTyp = Chain+Typ
493
494      self.Typ = Typ
495      self.Type = Type
496      self.Chain = Chain
497      self.ChainTyp = ChainTyp
498
499      self.LookupRecord = Type+'LookupRecord'
500
501      if Format == 1:
502        Coverage = lambda r: r.Coverage
503        ChainCoverage = lambda r: r.Coverage
504        ContextData = lambda r:(None,)
505        ChainContextData = lambda r:(None, None, None)
506        RuleData = lambda r:(r.Input,)
507        ChainRuleData = lambda r:(r.Backtrack, r.Input, r.LookAhead)
508        SetRuleData = None
509        ChainSetRuleData = None
510      elif Format == 2:
511        Coverage = lambda r: r.Coverage
512        ChainCoverage = lambda r: r.Coverage
513        ContextData = lambda r:(r.ClassDef,)
514        ChainContextData = lambda r:(r.LookAheadClassDef,
515                                      r.InputClassDef,
516                                      r.BacktrackClassDef)
517        RuleData = lambda r:(r.Class,)
518        ChainRuleData = lambda r:(r.LookAhead, r.Input, r.Backtrack)
519        def SetRuleData(r, d):(r.Class,) = d
520        def ChainSetRuleData(r, d):(r.LookAhead, r.Input, r.Backtrack) = d
521      elif Format == 3:
522        Coverage = lambda r: r.Coverage[0]
523        ChainCoverage = lambda r: r.InputCoverage[0]
524        ContextData = None
525        ChainContextData = None
526        RuleData = lambda r: r.Coverage
527        ChainRuleData = lambda r:(r.LookAheadCoverage +
528                                   r.InputCoverage +
529                                   r.BacktrackCoverage)
530        SetRuleData = None
531        ChainSetRuleData = None
532      else:
533        assert 0, "unknown format: %s" % Format
534
535      if Chain:
536        self.Coverage = ChainCoverage
537        self.ContextData = ChainContextData
538        self.RuleData = ChainRuleData
539        self.SetRuleData = ChainSetRuleData
540      else:
541        self.Coverage = Coverage
542        self.ContextData = ContextData
543        self.RuleData = RuleData
544        self.SetRuleData = SetRuleData
545
546      if Format == 1:
547        self.Rule = ChainTyp+'Rule'
548        self.RuleCount = ChainTyp+'RuleCount'
549        self.RuleSet = ChainTyp+'RuleSet'
550        self.RuleSetCount = ChainTyp+'RuleSetCount'
551        self.Intersect = lambda glyphs, c, r: [r] if r in glyphs else []
552      elif Format == 2:
553        self.Rule = ChainTyp+'ClassRule'
554        self.RuleCount = ChainTyp+'ClassRuleCount'
555        self.RuleSet = ChainTyp+'ClassSet'
556        self.RuleSetCount = ChainTyp+'ClassSetCount'
557        self.Intersect = lambda glyphs, c, r: c.intersect_class(glyphs, r)
558
559        self.ClassDef = 'InputClassDef' if Chain else 'ClassDef'
560        self.ClassDefIndex = 1 if Chain else 0
561        self.Input = 'Input' if Chain else 'Class'
562
563  if self.Format not in [1, 2, 3]:
564    return None  # Don't shoot the messenger; let it go
565  if not hasattr(self.__class__, "__ContextHelpers"):
566    self.__class__.__ContextHelpers = {}
567  if self.Format not in self.__class__.__ContextHelpers:
568    helper = ContextHelper(self.__class__, self.Format)
569    self.__class__.__ContextHelpers[self.Format] = helper
570  return self.__class__.__ContextHelpers[self.Format]
571
572@_add_method(otTables.ContextSubst,
573             otTables.ChainContextSubst)
574def closure_glyphs(self, s, cur_glyphs=None):
575  if cur_glyphs == None: cur_glyphs = s.glyphs
576  c = self.__classify_context()
577
578  indices = c.Coverage(self).intersect(s.glyphs)
579  if not indices:
580    return []
581  cur_glyphs = c.Coverage(self).intersect_glyphs(s.glyphs);
582
583  if self.Format == 1:
584    ContextData = c.ContextData(self)
585    rss = getattr(self, c.RuleSet)
586    for i in indices:
587      if not rss[i]: continue
588      for r in getattr(rss[i], c.Rule):
589        if not r: continue
590        if all(all(c.Intersect(s.glyphs, cd, k) for k in klist)
591          for cd,klist in zip(ContextData, c.RuleData(r))):
592          chaos = False
593          for ll in getattr(r, c.LookupRecord):
594            if not ll: continue
595            seqi = ll.SequenceIndex
596            if chaos:
597              pos_glyphs = s.glyphs
598            else:
599              if seqi == 0:
600                pos_glyphs = set([c.Coverage(self).glyphs[i]])
601              else:
602                pos_glyphs = set([r.Input[seqi - 1]])
603            lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
604            chaos = chaos or lookup.may_have_non_1to1()
605            lookup.closure_glyphs(s, cur_glyphs=pos_glyphs)
606  elif self.Format == 2:
607    ClassDef = getattr(self, c.ClassDef)
608    indices = ClassDef.intersect(cur_glyphs)
609    ContextData = c.ContextData(self)
610    rss = getattr(self, c.RuleSet)
611    for i in indices:
612      if not rss[i]: continue
613      for r in getattr(rss[i], c.Rule):
614        if not r: continue
615        if all(all(c.Intersect(s.glyphs, cd, k) for k in klist)
616          for cd,klist in zip(ContextData, c.RuleData(r))):
617          chaos = False
618          for ll in getattr(r, c.LookupRecord):
619            if not ll: continue
620            seqi = ll.SequenceIndex
621            if chaos:
622              pos_glyphs = s.glyphs
623            else:
624              if seqi == 0:
625                pos_glyphs = ClassDef.intersect_class(cur_glyphs, i)
626              else:
627                pos_glyphs = ClassDef.intersect_class(s.glyphs,
628                                                      getattr(r, c.Input)[seqi - 1])
629            lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
630            chaos = chaos or lookup.may_have_non_1to1()
631            lookup.closure_glyphs(s, cur_glyphs=pos_glyphs)
632  elif self.Format == 3:
633    if not all(x.intersect(s.glyphs) for x in c.RuleData(self)):
634      return []
635    r = self
636    chaos = False
637    for ll in getattr(r, c.LookupRecord):
638      if not ll: continue
639      seqi = ll.SequenceIndex
640      if chaos:
641        pos_glyphs = s.glyphs
642      else:
643        if seqi == 0:
644          pos_glyphs = cur_glyphs
645        else:
646          pos_glyphs = r.InputCoverage[seqi].intersect_glyphs(s.glyphs)
647      lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
648      chaos = chaos or lookup.may_have_non_1to1()
649      lookup.closure_glyphs(s, cur_glyphs=pos_glyphs)
650  else:
651    assert 0, "unknown format: %s" % self.Format
652
653@_add_method(otTables.ContextSubst,
654             otTables.ContextPos,
655             otTables.ChainContextSubst,
656             otTables.ChainContextPos)
657def subset_glyphs(self, s):
658  c = self.__classify_context()
659
660  if self.Format == 1:
661    indices = self.Coverage.subset(s.glyphs)
662    rss = getattr(self, c.RuleSet)
663    rss = [rss[i] for i in indices]
664    for rs in rss:
665      if not rs: continue
666      ss = getattr(rs, c.Rule)
667      ss = [r for r in ss
668            if r and all(all(g in s.glyphs for g in glist)
669              for glist in c.RuleData(r))]
670      setattr(rs, c.Rule, ss)
671      setattr(rs, c.RuleCount, len(ss))
672    # Prune empty subrulesets
673    rss = [rs for rs in rss if rs and getattr(rs, c.Rule)]
674    setattr(self, c.RuleSet, rss)
675    setattr(self, c.RuleSetCount, len(rss))
676    return bool(rss)
677  elif self.Format == 2:
678    if not self.Coverage.subset(s.glyphs):
679      return False
680    ContextData = c.ContextData(self)
681    klass_maps = [x.subset(s.glyphs, remap=True) for x in ContextData]
682
683    # Keep rulesets for class numbers that survived.
684    indices = klass_maps[c.ClassDefIndex]
685    rss = getattr(self, c.RuleSet)
686    rssCount = getattr(self, c.RuleSetCount)
687    rss = [rss[i] for i in indices if i < rssCount]
688    del rssCount
689    # Delete, but not renumber, unreachable rulesets.
690    indices = getattr(self, c.ClassDef).intersect(self.Coverage.glyphs)
691    rss = [rss if i in indices else None for i,rss in enumerate(rss)]
692    while rss and rss[-1] == None:
693      del rss[-1]
694
695    for rs in rss:
696      if not rs: continue
697      ss = getattr(rs, c.Rule)
698      ss = [r for r in ss
699            if r and all(all(k in klass_map for k in klist)
700              for klass_map,klist in zip(klass_maps, c.RuleData(r)))]
701      setattr(rs, c.Rule, ss)
702      setattr(rs, c.RuleCount, len(ss))
703
704      # Remap rule classes
705      for r in ss:
706        c.SetRuleData(r, [[klass_map.index(k) for k in klist]
707               for klass_map,klist in zip(klass_maps, c.RuleData(r))])
708    return bool(rss)
709  elif self.Format == 3:
710    return all(x.subset(s.glyphs) for x in c.RuleData(self))
711  else:
712    assert 0, "unknown format: %s" % self.Format
713
714@_add_method(otTables.ContextSubst,
715             otTables.ChainContextSubst,
716             otTables.ContextPos,
717             otTables.ChainContextPos)
718def subset_lookups(self, lookup_indices):
719  c = self.__classify_context()
720
721  if self.Format in [1, 2]:
722    for rs in getattr(self, c.RuleSet):
723      if not rs: continue
724      for r in getattr(rs, c.Rule):
725        if not r: continue
726        setattr(r, c.LookupRecord,
727                 [ll for ll in getattr(r, c.LookupRecord)
728                  if ll and ll.LookupListIndex in lookup_indices])
729        for ll in getattr(r, c.LookupRecord):
730          if not ll: continue
731          ll.LookupListIndex = lookup_indices.index(ll.LookupListIndex)
732  elif self.Format == 3:
733    setattr(self, c.LookupRecord,
734             [ll for ll in getattr(self, c.LookupRecord)
735              if ll and ll.LookupListIndex in lookup_indices])
736    for ll in getattr(self, c.LookupRecord):
737      if not ll: continue
738      ll.LookupListIndex = lookup_indices.index(ll.LookupListIndex)
739  else:
740    assert 0, "unknown format: %s" % self.Format
741
742@_add_method(otTables.ContextSubst,
743             otTables.ChainContextSubst,
744             otTables.ContextPos,
745             otTables.ChainContextPos)
746def collect_lookups(self):
747  c = self.__classify_context()
748
749  if self.Format in [1, 2]:
750    return [ll.LookupListIndex
751      for rs in getattr(self, c.RuleSet) if rs
752      for r in getattr(rs, c.Rule) if r
753      for ll in getattr(r, c.LookupRecord) if ll]
754  elif self.Format == 3:
755    return [ll.LookupListIndex
756      for ll in getattr(self, c.LookupRecord) if ll]
757  else:
758    assert 0, "unknown format: %s" % self.Format
759
760@_add_method(otTables.ExtensionSubst)
761def closure_glyphs(self, s, cur_glyphs=None):
762  if self.Format == 1:
763    self.ExtSubTable.closure_glyphs(s, cur_glyphs)
764  else:
765    assert 0, "unknown format: %s" % self.Format
766
767@_add_method(otTables.ExtensionSubst)
768def may_have_non_1to1(self):
769  if self.Format == 1:
770    return self.ExtSubTable.may_have_non_1to1()
771  else:
772    assert 0, "unknown format: %s" % self.Format
773
774@_add_method(otTables.ExtensionSubst,
775             otTables.ExtensionPos)
776def prune_pre_subset(self, options):
777  if self.Format == 1:
778    return self.ExtSubTable.prune_pre_subset(options)
779  else:
780    assert 0, "unknown format: %s" % self.Format
781
782@_add_method(otTables.ExtensionSubst,
783             otTables.ExtensionPos)
784def subset_glyphs(self, s):
785  if self.Format == 1:
786    return self.ExtSubTable.subset_glyphs(s)
787  else:
788    assert 0, "unknown format: %s" % self.Format
789
790@_add_method(otTables.ExtensionSubst,
791             otTables.ExtensionPos)
792def prune_post_subset(self, options):
793  if self.Format == 1:
794    return self.ExtSubTable.prune_post_subset(options)
795  else:
796    assert 0, "unknown format: %s" % self.Format
797
798@_add_method(otTables.ExtensionSubst,
799             otTables.ExtensionPos)
800def subset_lookups(self, lookup_indices):
801  if self.Format == 1:
802    return self.ExtSubTable.subset_lookups(lookup_indices)
803  else:
804    assert 0, "unknown format: %s" % self.Format
805
806@_add_method(otTables.ExtensionSubst,
807             otTables.ExtensionPos)
808def collect_lookups(self):
809  if self.Format == 1:
810    return self.ExtSubTable.collect_lookups()
811  else:
812    assert 0, "unknown format: %s" % self.Format
813
814@_add_method(otTables.Lookup)
815def closure_glyphs(self, s, cur_glyphs=None):
816  for st in self.SubTable:
817    if not st: continue
818    st.closure_glyphs(s, cur_glyphs)
819
820@_add_method(otTables.Lookup)
821def prune_pre_subset(self, options):
822  ret = False
823  for st in self.SubTable:
824    if not st: continue
825    if st.prune_pre_subset(options): ret = True
826  return ret
827
828@_add_method(otTables.Lookup)
829def subset_glyphs(self, s):
830  self.SubTable = [st for st in self.SubTable if st and st.subset_glyphs(s)]
831  self.SubTableCount = len(self.SubTable)
832  return bool(self.SubTableCount)
833
834@_add_method(otTables.Lookup)
835def prune_post_subset(self, options):
836  ret = False
837  for st in self.SubTable:
838    if not st: continue
839    if st.prune_post_subset(options): ret = True
840  return ret
841
842@_add_method(otTables.Lookup)
843def subset_lookups(self, lookup_indices):
844  for s in self.SubTable:
845    s.subset_lookups(lookup_indices)
846
847@_add_method(otTables.Lookup)
848def collect_lookups(self):
849  return _uniq_sort(sum((st.collect_lookups() for st in self.SubTable
850                         if st), []))
851
852@_add_method(otTables.Lookup)
853def may_have_non_1to1(self):
854  return any(st.may_have_non_1to1() for st in self.SubTable if st)
855
856@_add_method(otTables.LookupList)
857def prune_pre_subset(self, options):
858  ret = False
859  for l in self.Lookup:
860    if not l: continue
861    if l.prune_pre_subset(options): ret = True
862  return ret
863
864@_add_method(otTables.LookupList)
865def subset_glyphs(self, s):
866  "Returns the indices of nonempty lookups."
867  return [i for i,l in enumerate(self.Lookup) if l and l.subset_glyphs(s)]
868
869@_add_method(otTables.LookupList)
870def prune_post_subset(self, options):
871  ret = False
872  for l in self.Lookup:
873    if not l: continue
874    if l.prune_post_subset(options): ret = True
875  return ret
876
877@_add_method(otTables.LookupList)
878def subset_lookups(self, lookup_indices):
879  self.Lookup = [self.Lookup[i] for i in lookup_indices
880                 if i < self.LookupCount]
881  self.LookupCount = len(self.Lookup)
882  for l in self.Lookup:
883    l.subset_lookups(lookup_indices)
884
885@_add_method(otTables.LookupList)
886def closure_lookups(self, lookup_indices):
887  lookup_indices = _uniq_sort(lookup_indices)
888  recurse = lookup_indices
889  while True:
890    recurse_lookups = sum((self.Lookup[i].collect_lookups()
891                            for i in recurse if i < self.LookupCount), [])
892    recurse_lookups = [l for l in recurse_lookups
893                       if l not in lookup_indices and l < self.LookupCount]
894    if not recurse_lookups:
895      return _uniq_sort(lookup_indices)
896    recurse_lookups = _uniq_sort(recurse_lookups)
897    lookup_indices.extend(recurse_lookups)
898    recurse = recurse_lookups
899
900@_add_method(otTables.Feature)
901def subset_lookups(self, lookup_indices):
902  self.LookupListIndex = [l for l in self.LookupListIndex
903                          if l in lookup_indices]
904  # Now map them.
905  self.LookupListIndex = [lookup_indices.index(l)
906                          for l in self.LookupListIndex]
907  self.LookupCount = len(self.LookupListIndex)
908  return self.LookupCount
909
910@_add_method(otTables.Feature)
911def collect_lookups(self):
912  return self.LookupListIndex[:]
913
914@_add_method(otTables.FeatureList)
915def subset_lookups(self, lookup_indices):
916  "Returns the indices of nonempty features."
917  feature_indices = [i for i,f in enumerate(self.FeatureRecord)
918                     if f.Feature.subset_lookups(lookup_indices)]
919  self.subset_features(feature_indices)
920  return feature_indices
921
922@_add_method(otTables.FeatureList)
923def collect_lookups(self, feature_indices):
924  return _uniq_sort(sum((self.FeatureRecord[i].Feature.collect_lookups()
925                         for i in feature_indices
926                          if i < self.FeatureCount), []))
927
928@_add_method(otTables.FeatureList)
929def subset_features(self, feature_indices):
930  self.FeatureRecord = [self.FeatureRecord[i] for i in feature_indices]
931  self.FeatureCount = len(self.FeatureRecord)
932  return bool(self.FeatureCount)
933
934@_add_method(otTables.DefaultLangSys,
935             otTables.LangSys)
936def subset_features(self, feature_indices):
937  if self.ReqFeatureIndex in feature_indices:
938    self.ReqFeatureIndex = feature_indices.index(self.ReqFeatureIndex)
939  else:
940    self.ReqFeatureIndex = 65535
941  self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
942  # Now map them.
943  self.FeatureIndex = [feature_indices.index(f) for f in self.FeatureIndex
944                       if f in feature_indices]
945  self.FeatureCount = len(self.FeatureIndex)
946  return bool(self.FeatureCount or self.ReqFeatureIndex != 65535)
947
948@_add_method(otTables.DefaultLangSys,
949             otTables.LangSys)
950def collect_features(self):
951  feature_indices = self.FeatureIndex[:]
952  if self.ReqFeatureIndex != 65535:
953    feature_indices.append(self.ReqFeatureIndex)
954  return _uniq_sort(feature_indices)
955
956@_add_method(otTables.Script)
957def subset_features(self, feature_indices):
958  if(self.DefaultLangSys and
959      not self.DefaultLangSys.subset_features(feature_indices)):
960    self.DefaultLangSys = None
961  self.LangSysRecord = [l for l in self.LangSysRecord
962                        if l.LangSys.subset_features(feature_indices)]
963  self.LangSysCount = len(self.LangSysRecord)
964  return bool(self.LangSysCount or self.DefaultLangSys)
965
966@_add_method(otTables.Script)
967def collect_features(self):
968  feature_indices = [l.LangSys.collect_features() for l in self.LangSysRecord]
969  if self.DefaultLangSys:
970    feature_indices.append(self.DefaultLangSys.collect_features())
971  return _uniq_sort(sum(feature_indices, []))
972
973@_add_method(otTables.ScriptList)
974def subset_features(self, feature_indices):
975  self.ScriptRecord = [s for s in self.ScriptRecord
976                       if s.Script.subset_features(feature_indices)]
977  self.ScriptCount = len(self.ScriptRecord)
978  return bool(self.ScriptCount)
979
980@_add_method(otTables.ScriptList)
981def collect_features(self):
982  return _uniq_sort(sum((s.Script.collect_features()
983                         for s in self.ScriptRecord), []))
984
985@_add_method(ttLib.getTableClass('GSUB'))
986def closure_glyphs(self, s):
987  s.table = self.table
988  feature_indices = self.table.ScriptList.collect_features()
989  if self.table.FeatureList:
990    lookup_indices = self.table.FeatureList.collect_lookups(feature_indices)
991  else:
992    lookup_indices = []
993  if self.table.LookupList:
994    while True:
995      orig_glyphs = s.glyphs.copy()
996      for i in lookup_indices:
997        if i >= self.table.LookupList.LookupCount: continue
998        if not self.table.LookupList.Lookup[i]: continue
999        self.table.LookupList.Lookup[i].closure_glyphs(s)
1000      if orig_glyphs == s.glyphs:
1001        break
1002  del s.table
1003
1004@_add_method(ttLib.getTableClass('GSUB'),
1005             ttLib.getTableClass('GPOS'))
1006def subset_glyphs(self, s):
1007  s.glyphs = s.glyphs_gsubed
1008  if self.table.LookupList:
1009    lookup_indices = self.table.LookupList.subset_glyphs(s)
1010  else:
1011    lookup_indices = []
1012  self.subset_lookups(lookup_indices)
1013  self.prune_lookups()
1014  return True
1015
1016@_add_method(ttLib.getTableClass('GSUB'),
1017             ttLib.getTableClass('GPOS'))
1018def subset_lookups(self, lookup_indices):
1019  """Retrains specified lookups, then removes empty features, language
1020     systems, and scripts."""
1021  if self.table.LookupList:
1022    self.table.LookupList.subset_lookups(lookup_indices)
1023  if self.table.FeatureList:
1024    feature_indices = self.table.FeatureList.subset_lookups(lookup_indices)
1025  else:
1026    feature_indices = []
1027  self.table.ScriptList.subset_features(feature_indices)
1028
1029@_add_method(ttLib.getTableClass('GSUB'),
1030             ttLib.getTableClass('GPOS'))
1031def prune_lookups(self):
1032  "Remove unreferenced lookups"
1033  feature_indices = self.table.ScriptList.collect_features()
1034  if self.table.FeatureList:
1035    lookup_indices = self.table.FeatureList.collect_lookups(feature_indices)
1036  else:
1037    lookup_indices = []
1038  if self.table.LookupList:
1039    lookup_indices = self.table.LookupList.closure_lookups(lookup_indices)
1040  else:
1041    lookup_indices = []
1042  self.subset_lookups(lookup_indices)
1043
1044@_add_method(ttLib.getTableClass('GSUB'),
1045             ttLib.getTableClass('GPOS'))
1046def subset_feature_tags(self, feature_tags):
1047  if self.table.FeatureList:
1048    feature_indices = [i for i,f in
1049                       enumerate(self.table.FeatureList.FeatureRecord)
1050                       if f.FeatureTag in feature_tags]
1051    self.table.FeatureList.subset_features(feature_indices)
1052  else:
1053    feature_indices = []
1054  self.table.ScriptList.subset_features(feature_indices)
1055
1056@_add_method(ttLib.getTableClass('GSUB'),
1057             ttLib.getTableClass('GPOS'))
1058def prune_pre_subset(self, options):
1059  if '*' not in options.layout_features:
1060    self.subset_feature_tags(options.layout_features)
1061  self.prune_lookups()
1062  if self.table.LookupList:
1063    self.table.LookupList.prune_pre_subset(options);
1064  return True
1065
1066@_add_method(ttLib.getTableClass('GSUB'),
1067             ttLib.getTableClass('GPOS'))
1068def prune_post_subset(self, options):
1069  if self.table.LookupList:
1070    self.table.LookupList.prune_post_subset(options);
1071  return True
1072
1073@_add_method(ttLib.getTableClass('GDEF'))
1074def subset_glyphs(self, s):
1075  glyphs = s.glyphs_gsubed
1076  table = self.table
1077  if table.LigCaretList:
1078    indices = table.LigCaretList.Coverage.subset(glyphs)
1079    table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i]
1080                                   for i in indices]
1081    table.LigCaretList.LigGlyphCount = len(table.LigCaretList.LigGlyph)
1082    if not table.LigCaretList.LigGlyphCount:
1083      table.LigCaretList = None
1084  if table.MarkAttachClassDef:
1085    table.MarkAttachClassDef.classDefs = dict((g,v) for g,v in
1086                                              table.MarkAttachClassDef.
1087                                                classDefs.iteritems()
1088                                              if g in glyphs)
1089    if not table.MarkAttachClassDef.classDefs:
1090      table.MarkAttachClassDef = None
1091  if table.GlyphClassDef:
1092    table.GlyphClassDef.classDefs = dict((g,v) for g,v in
1093                                         table.GlyphClassDef.
1094                                           classDefs.iteritems()
1095                                         if g in glyphs)
1096    if not table.GlyphClassDef.classDefs:
1097      table.GlyphClassDef = None
1098  if table.AttachList:
1099    indices = table.AttachList.Coverage.subset(glyphs)
1100    table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i]
1101                                    for i in indices]
1102    table.AttachList.GlyphCount = len(table.AttachList.AttachPoint)
1103    if not table.AttachList.GlyphCount:
1104      table.AttachList = None
1105  return bool(table.LigCaretList or
1106               table.MarkAttachClassDef or
1107               table.GlyphClassDef or
1108               table.AttachList)
1109
1110@_add_method(ttLib.getTableClass('kern'))
1111def prune_pre_subset(self, options):
1112  # Prune unknown kern table types
1113  self.kernTables = [t for t in self.kernTables if hasattr(t, 'kernTable')]
1114  return bool(self.kernTables)
1115
1116@_add_method(ttLib.getTableClass('kern'))
1117def subset_glyphs(self, s):
1118  glyphs = s.glyphs_gsubed
1119  for t in self.kernTables:
1120    t.kernTable = dict(((a,b),v) for (a,b),v in t.kernTable.iteritems()
1121                       if a in glyphs and b in glyphs)
1122  self.kernTables = [t for t in self.kernTables if t.kernTable]
1123  return bool(self.kernTables)
1124
1125@_add_method(ttLib.getTableClass('vmtx'))
1126def subset_glyphs(self, s):
1127  self.metrics = dict((g,v) for g,v in self.metrics.iteritems() if g in s.glyphs)
1128  return bool(self.metrics)
1129
1130@_add_method(ttLib.getTableClass('hmtx'))
1131def subset_glyphs(self, s):
1132  self.metrics = dict((g,v) for g,v in self.metrics.iteritems() if g in s.glyphs)
1133  return True # Required table
1134
1135@_add_method(ttLib.getTableClass('hdmx'))
1136def subset_glyphs(self, s):
1137  self.hdmx = dict((sz,dict((g,v) for g,v in l.iteritems() if g in s.glyphs))
1138                   for sz,l in self.hdmx.iteritems())
1139  return bool(self.hdmx)
1140
1141@_add_method(ttLib.getTableClass('VORG'))
1142def subset_glyphs(self, s):
1143  self.VOriginRecords = dict((g,v) for g,v in self.VOriginRecords.iteritems()
1144                             if g in s.glyphs)
1145  self.numVertOriginYMetrics = len(self.VOriginRecords)
1146  return True  # Never drop; has default metrics
1147
1148@_add_method(ttLib.getTableClass('post'))
1149def prune_pre_subset(self, options):
1150  if not options.glyph_names:
1151    self.formatType = 3.0
1152  return True # Required table
1153
1154@_add_method(ttLib.getTableClass('post'))
1155def subset_glyphs(self, s):
1156  self.extraNames = []  # This seems to do it
1157  return True # Required table
1158
1159@_add_method(ttLib.getTableModule('glyf').Glyph)
1160def remapComponentsFast(self, indices):
1161  if not self.data or struct.unpack(">h", self.data[:2])[0] >= 0:
1162    return  # Not composite
1163  data = array.array("B", self.data)
1164  i = 10
1165  more = 1
1166  while more:
1167    flags =(data[i] << 8) | data[i+1]
1168    glyphID =(data[i+2] << 8) | data[i+3]
1169    # Remap
1170    glyphID = indices.index(glyphID)
1171    data[i+2] = glyphID >> 8
1172    data[i+3] = glyphID & 0xFF
1173    i += 4
1174    flags = int(flags)
1175
1176    if flags & 0x0001: i += 4  # ARG_1_AND_2_ARE_WORDS
1177    else: i += 2
1178    if flags & 0x0008: i += 2  # WE_HAVE_A_SCALE
1179    elif flags & 0x0040: i += 4  # WE_HAVE_AN_X_AND_Y_SCALE
1180    elif flags & 0x0080: i += 8  # WE_HAVE_A_TWO_BY_TWO
1181    more = flags & 0x0020  # MORE_COMPONENTS
1182
1183  self.data = data.tostring()
1184
1185@_add_method(ttLib.getTableClass('glyf'))
1186def closure_glyphs(self, s):
1187  decompose = s.glyphs
1188  while True:
1189    components = set()
1190    for g in decompose:
1191      if g not in self.glyphs:
1192        continue
1193      gl = self.glyphs[g]
1194      for c in gl.getComponentNames(self):
1195        if c not in s.glyphs:
1196          components.add(c)
1197    components = set(c for c in components if c not in s.glyphs)
1198    if not components:
1199      break
1200    decompose = components
1201    s.glyphs.update(components)
1202
1203@_add_method(ttLib.getTableClass('glyf'))
1204def prune_pre_subset(self, options):
1205  if options.notdef_glyph and not options.notdef_outline:
1206    g = self[self.glyphOrder[0]]
1207    # Yay, easy!
1208    g.__dict__.clear()
1209    g.data = ""
1210  return True
1211
1212@_add_method(ttLib.getTableClass('glyf'))
1213def subset_glyphs(self, s):
1214  self.glyphs = dict((g,v) for g,v in self.glyphs.iteritems() if g in s.glyphs)
1215  indices = [i for i,g in enumerate(self.glyphOrder) if g in s.glyphs]
1216  for v in self.glyphs.itervalues():
1217    if hasattr(v, "data"):
1218      v.remapComponentsFast(indices)
1219    else:
1220      pass  # No need
1221  self.glyphOrder = [g for g in self.glyphOrder if g in s.glyphs]
1222  # Don't drop empty 'glyf' tables, otherwise 'loca' doesn't get subset.
1223  return True
1224
1225@_add_method(ttLib.getTableClass('glyf'))
1226def prune_post_subset(self, options):
1227  if not options.hinting:
1228    for v in self.glyphs.itervalues():
1229      v.removeHinting()
1230  return True
1231
1232@_add_method(ttLib.getTableClass('CFF '))
1233def prune_pre_subset(self, options):
1234  cff = self.cff
1235  # CFF table must have one font only
1236  cff.fontNames = cff.fontNames[:1]
1237
1238  if options.notdef_glyph and not options.notdef_outline:
1239    for fontname in cff.keys():
1240      font = cff[fontname]
1241      c,_ = font.CharStrings.getItemAndSelector('.notdef')
1242      # XXX we should preserve the glyph width
1243      c.bytecode = '\x0e' # endchar
1244      c.program = None
1245
1246  return True # bool(cff.fontNames)
1247
1248@_add_method(ttLib.getTableClass('CFF '))
1249def subset_glyphs(self, s):
1250  cff = self.cff
1251  for fontname in cff.keys():
1252    font = cff[fontname]
1253    cs = font.CharStrings
1254
1255    # Load all glyphs
1256    for g in font.charset:
1257      if g not in s.glyphs: continue
1258      c,sel = cs.getItemAndSelector(g)
1259
1260    if cs.charStringsAreIndexed:
1261      indices = [i for i,g in enumerate(font.charset) if g in s.glyphs]
1262      csi = cs.charStringsIndex
1263      csi.items = [csi.items[i] for i in indices]
1264      csi.count = len(csi.items)
1265      del csi.file, csi.offsets
1266      if hasattr(font, "FDSelect"):
1267        sel = font.FDSelect
1268        sel.format = None
1269        sel.gidArray = [sel.gidArray[i] for i in indices]
1270      cs.charStrings = dict((g,indices.index(v))
1271                            for g,v in cs.charStrings.iteritems()
1272                            if g in s.glyphs)
1273    else:
1274      cs.charStrings = dict((g,v)
1275                            for g,v in cs.charStrings.iteritems()
1276                            if g in s.glyphs)
1277    font.charset = [g for g in font.charset if g in s.glyphs]
1278    font.numGlyphs = len(font.charset)
1279
1280  return True # any(cff[fontname].numGlyphs for fontname in cff.keys())
1281
1282@_add_method(psCharStrings.T2CharString)
1283def subset_subroutines(self, subrs, gsubrs):
1284  p = self.program
1285  assert len(p)
1286  for i in xrange(1, len(p)):
1287    if p[i] == 'callsubr':
1288      assert type(p[i-1]) is int
1289      p[i-1] = subrs._used.index(p[i-1] + subrs._old_bias) - subrs._new_bias
1290    elif p[i] == 'callgsubr':
1291      assert type(p[i-1]) is int
1292      p[i-1] = gsubrs._used.index(p[i-1] + gsubrs._old_bias) - gsubrs._new_bias
1293
1294@_add_method(psCharStrings.T2CharString)
1295def drop_hints(self):
1296  hints = self._hints
1297
1298  if hints.has_hint:
1299    self.program = self.program[hints.last_hint:]
1300    if hasattr(self, 'width'):
1301      # Insert width back if needed
1302      if self.width != self.private.defaultWidthX:
1303        self.program.insert(0, self.width - self.private.nominalWidthX)
1304
1305  if hints.has_hintmask:
1306    i = 0
1307    p = self.program
1308    while i < len(p):
1309      if p[i] in ['hintmask', 'cntrmask']:
1310        assert i + 1 <= len(p)
1311        del p[i:i+2]
1312        continue
1313      i += 1
1314
1315  # TODO: we currently don't drop calls to "empty" subroutines.
1316
1317  assert len(self.program)
1318
1319  del self._hints
1320
1321class _MarkingT2Decompiler(psCharStrings.SimpleT2Decompiler):
1322
1323  def __init__(self, localSubrs, globalSubrs):
1324    psCharStrings.SimpleT2Decompiler.__init__(self,
1325                                              localSubrs,
1326                                              globalSubrs)
1327    for subrs in [localSubrs, globalSubrs]:
1328      if subrs and not hasattr(subrs, "_used"):
1329        subrs._used = set()
1330
1331  def op_callsubr(self, index):
1332    self.localSubrs._used.add(self.operandStack[-1]+self.localBias)
1333    psCharStrings.SimpleT2Decompiler.op_callsubr(self, index)
1334
1335  def op_callgsubr(self, index):
1336    self.globalSubrs._used.add(self.operandStack[-1]+self.globalBias)
1337    psCharStrings.SimpleT2Decompiler.op_callgsubr(self, index)
1338
1339class _DehintingT2Decompiler(psCharStrings.SimpleT2Decompiler):
1340
1341  class Hints:
1342    def __init__(self):
1343      # Whether calling this charstring produces any hint stems
1344      self.has_hint = False
1345      # Index to start at to drop all hints
1346      self.last_hint = 0
1347      # Index up to which we know more hints are possible.  Only
1348      # relevant if status is 0 or 1.
1349      self.last_checked = 0
1350      # The status means:
1351      # 0: after dropping hints, this charstring is empty
1352      # 1: after dropping hints, there may be more hints continuing after this
1353      # 2: no more hints possible after this charstring
1354      self.status = 0
1355      # Has hintmask instructions; not recursive
1356      self.has_hintmask = False
1357    pass
1358
1359  def __init__(self, css, localSubrs, globalSubrs):
1360    self._css = css
1361    psCharStrings.SimpleT2Decompiler.__init__(self,
1362                                              localSubrs,
1363                                              globalSubrs)
1364
1365  def execute(self, charString):
1366    old_hints = charString._hints if hasattr(charString, '_hints') else None
1367    charString._hints = self.Hints()
1368
1369    psCharStrings.SimpleT2Decompiler.execute(self, charString)
1370
1371    hints = charString._hints
1372
1373    if hints.has_hint or hints.has_hintmask:
1374      self._css.add(charString)
1375
1376    if hints.status != 2:
1377      # Check from last_check, make sure we didn't have any operators.
1378      for i in xrange(hints.last_checked, len(charString.program) - 1):
1379        if type(charString.program[i]) == str:
1380          hints.status = 2
1381          break;
1382        else:
1383          hints.status = 1 # There's *something* here
1384      hints.last_checked = len(charString.program)
1385
1386    if old_hints:
1387      assert hints.__dict__ == old_hints.__dict__
1388
1389  def op_callsubr(self, index):
1390    subr = self.localSubrs[self.operandStack[-1]+self.localBias]
1391    psCharStrings.SimpleT2Decompiler.op_callsubr(self, index)
1392    self.processSubr(index, subr)
1393
1394  def op_callgsubr(self, index):
1395    subr = self.globalSubrs[self.operandStack[-1]+self.globalBias]
1396    psCharStrings.SimpleT2Decompiler.op_callgsubr(self, index)
1397    self.processSubr(index, subr)
1398
1399  def op_hstem(self, index):
1400    psCharStrings.SimpleT2Decompiler.op_hstem(self, index)
1401    self.processHint(index)
1402  def op_vstem(self, index):
1403    psCharStrings.SimpleT2Decompiler.op_vstem(self, index)
1404    self.processHint(index)
1405  def op_hstemhm(self, index):
1406    psCharStrings.SimpleT2Decompiler.op_hstemhm(self, index)
1407    self.processHint(index)
1408  def op_vstemhm(self, index):
1409    psCharStrings.SimpleT2Decompiler.op_vstemhm(self, index)
1410    self.processHint(index)
1411  def op_hintmask(self, index):
1412    psCharStrings.SimpleT2Decompiler.op_hintmask(self, index)
1413    self.processHintmask(index)
1414  def op_cntrmask(self, index):
1415    psCharStrings.SimpleT2Decompiler.op_cntrmask(self, index)
1416    self.processHintmask(index)
1417
1418  def processHintmask(self, index):
1419    cs = self.callingStack[-1]
1420    hints = cs._hints
1421    hints.has_hintmask = True
1422    if hints.status != 2 and hints.has_hint:
1423      # Check from last_check, see if we may be an implicit vstem
1424      for i in xrange(hints.last_checked, index - 1):
1425        if type(cs.program[i]) == str:
1426          hints.status = 2
1427          break;
1428      if hints.status != 2:
1429        # We are an implicit vstem
1430        hints.last_hint = index + 1
1431        hints.status = 0
1432    hints.last_checked = index + 1
1433
1434  def processHint(self, index):
1435    cs = self.callingStack[-1]
1436    hints = cs._hints
1437    hints.has_hint = True
1438    hints.last_hint = index
1439    hints.last_checked = index
1440
1441  def processSubr(self, index, subr):
1442    cs = self.callingStack[-1]
1443    hints = cs._hints
1444    subr_hints = subr._hints
1445
1446    if subr_hints.has_hint:
1447      if hints.status != 2:
1448        hints.has_hint = True
1449        hints.last_checked = index
1450        hints.status = subr_hints.status
1451        # Decide where to chop off from
1452        if subr_hints.status == 0:
1453          hints.last_hint = index
1454        else:
1455          hints.last_hint = index - 2 # Leave the subr call in
1456      else:
1457        # In my understanding, this is a font bug.  Ie. it has hint stems
1458        # *after* path construction.  I've seen this in widespread fonts.
1459        # Best to ignore the hints I suppose...
1460        pass
1461        #assert 0
1462    else:
1463      hints.status = max(hints.status, subr_hints.status)
1464      if hints.status != 2:
1465        # Check from last_check, make sure we didn't have
1466        # any operators.
1467        for i in xrange(hints.last_checked, index - 1):
1468          if type(cs.program[i]) == str:
1469            hints.status = 2
1470            break;
1471        hints.last_checked = index
1472      if hints.status != 2:
1473        # Decide where to chop off from
1474        if subr_hints.status == 0:
1475          hints.last_hint = index
1476        else:
1477          hints.last_hint = index - 2 # Leave the subr call in
1478
1479@_add_method(ttLib.getTableClass('CFF '))
1480def prune_post_subset(self, options):
1481  cff = self.cff
1482  for fontname in cff.keys():
1483    font = cff[fontname]
1484    cs = font.CharStrings
1485
1486
1487    #
1488    # Drop unused FontDictionaries
1489    #
1490    if hasattr(font, "FDSelect"):
1491      sel = font.FDSelect
1492      indices = _uniq_sort(sel.gidArray)
1493      sel.gidArray = [indices.index (ss) for ss in sel.gidArray]
1494      arr = font.FDArray
1495      arr.items = [arr[i] for i in indices]
1496      arr.count = len(arr.items)
1497      del arr.file, arr.offsets
1498
1499
1500    #
1501    # Drop hints if not needed
1502    #
1503    if not options.hinting:
1504
1505      #
1506      # This can be tricky, but doesn't have to.  What we do is:
1507      #
1508      # - Run all used glyph charstrings and recurse into subroutines,
1509      # - For each charstring (including subroutines), if it has any
1510      #   of the hint stem operators, we mark it as such.  Upon returning,
1511      #   for each charstring we note all the subroutine calls it makes
1512      #   that (recursively) contain a stem,
1513      # - Dropping hinting then consists of the following two ops:
1514      #   * Drop the piece of the program in each charstring before the
1515      #     last call to a stem op or a stem-calling subroutine,
1516      #   * Drop all hintmask operations.
1517      # - It's trickier... A hintmask right after hints and a few numbers
1518      #   will act as an implicit vstemhm.  As such, we track whether
1519      #   we have seen any non-hint operators so far and do the right
1520      #   thing, recursively...  Good luck understanding that :(
1521      #
1522      css = set()
1523      for g in font.charset:
1524        c,sel = cs.getItemAndSelector(g)
1525        # Make sure it's decompiled.  We want our "decompiler" to walk
1526        # the program, not the bytecode.
1527        c.draw(basePen.NullPen())
1528        subrs = getattr(c.private, "Subrs", [])
1529        decompiler = _DehintingT2Decompiler(css, subrs, c.globalSubrs)
1530        decompiler.execute(c)
1531      for charstring in css:
1532        charstring.drop_hints()
1533
1534      # Drop font-wide hinting values
1535      all_privs = []
1536      if hasattr(font, 'FDSelect'):
1537        all_privs.extend(fd.Private for fd in font.FDArray)
1538      else:
1539        all_privs.append(font.Private)
1540      for priv in all_privs:
1541        for k in ['BlueValues', 'OtherBlues', 'FamilyBlues', 'FamilyOtherBlues',
1542                  'BlueScale', 'BlueShift', 'BlueFuzz',
1543                  'StemSnapH', 'StemSnapV', 'StdHW', 'StdVW']:
1544          if hasattr(priv, k):
1545            setattr(priv, k, None)
1546
1547
1548    #
1549    # Renumber subroutines to remove unused ones
1550    #
1551
1552    # Mark all used subroutines
1553    for g in font.charset:
1554      c,sel = cs.getItemAndSelector(g)
1555      subrs = getattr(c.private, "Subrs", [])
1556      decompiler = _MarkingT2Decompiler(subrs, c.globalSubrs)
1557      decompiler.execute(c)
1558
1559    all_subrs = [font.GlobalSubrs]
1560    if hasattr(font, 'FDSelect'):
1561      all_subrs.extend(fd.Private.Subrs for fd in font.FDArray if hasattr(fd.Private, 'Subrs') and fd.Private.Subrs)
1562    elif hasattr(font.Private, 'Subrs') and font.Private.Subrs:
1563      all_subrs.append(font.Private.Subrs)
1564
1565    subrs = set(subrs) # Remove duplicates
1566
1567    # Prepare
1568    for subrs in all_subrs:
1569      if not hasattr(subrs, '_used'):
1570        subrs._used = set()
1571      subrs._used = _uniq_sort(subrs._used)
1572      subrs._old_bias = psCharStrings.calcSubrBias(subrs)
1573      subrs._new_bias = psCharStrings.calcSubrBias(subrs._used)
1574
1575    # Renumber glyph charstrings
1576    for g in font.charset:
1577      c,sel = cs.getItemAndSelector(g)
1578      subrs = getattr(c.private, "Subrs", [])
1579      c.subset_subroutines (subrs, font.GlobalSubrs)
1580
1581    # Renumber subroutines themselves
1582    for subrs in all_subrs:
1583
1584      if subrs == font.GlobalSubrs:
1585        if not hasattr(font, 'FDSelect') and hasattr(font.Private, 'Subrs'):
1586          local_subrs = font.Private.Subrs
1587        else:
1588          local_subrs = []
1589      else:
1590        local_subrs = subrs
1591
1592      subrs.items = [subrs.items[i] for i in subrs._used]
1593      subrs.count = len(subrs.items)
1594      del subrs.file
1595      if hasattr(subrs, 'offsets'):
1596        del subrs.offsets
1597
1598      for i in xrange (subrs.count):
1599        subrs[i].subset_subroutines (local_subrs, font.GlobalSubrs)
1600
1601    # Cleanup
1602    for subrs in all_subrs:
1603      del subrs._used, subrs._old_bias, subrs._new_bias
1604
1605  return True
1606
1607@_add_method(ttLib.getTableClass('cmap'))
1608def closure_glyphs(self, s):
1609  tables = [t for t in self.tables
1610            if t.platformID == 3 and t.platEncID in [1, 10]]
1611  for u in s.unicodes_requested:
1612    found = False
1613    for table in tables:
1614      if u in table.cmap:
1615        s.glyphs.add(table.cmap[u])
1616        found = True
1617        break
1618    if not found:
1619      s.log("No glyph for Unicode value %s; skipping." % u)
1620
1621@_add_method(ttLib.getTableClass('cmap'))
1622def prune_pre_subset(self, options):
1623  if not options.legacy_cmap:
1624    # Drop non-Unicode / non-Symbol cmaps
1625    self.tables = [t for t in self.tables
1626                   if t.platformID == 3 and t.platEncID in [0, 1, 10]]
1627  if not options.symbol_cmap:
1628    self.tables = [t for t in self.tables
1629                   if t.platformID == 3 and t.platEncID in [1, 10]]
1630  # TODO(behdad) Only keep one subtable?
1631  # For now, drop format=0 which can't be subset_glyphs easily?
1632  self.tables = [t for t in self.tables if t.format != 0]
1633  self.numSubTables = len(self.tables)
1634  return True # Required table
1635
1636@_add_method(ttLib.getTableClass('cmap'))
1637def subset_glyphs(self, s):
1638  s.glyphs = s.glyphs_cmaped
1639  for t in self.tables:
1640    # For reasons I don't understand I need this here
1641    # to force decompilation of the cmap format 14.
1642    try:
1643      getattr(t, "asdf")
1644    except AttributeError:
1645      pass
1646    if t.format == 14:
1647      # TODO(behdad) XXX We drop all the default-UVS mappings(g==None).
1648      t.uvsDict = dict((v,[(u,g) for u,g in l if g in s.glyphs])
1649                       for v,l in t.uvsDict.iteritems())
1650      t.uvsDict = dict((v,l) for v,l in t.uvsDict.iteritems() if l)
1651    else:
1652      t.cmap = dict((u,g) for u,g in t.cmap.iteritems()
1653                    if g in s.glyphs_requested or u in s.unicodes_requested)
1654  self.tables = [t for t in self.tables
1655                 if (t.cmap if t.format != 14 else t.uvsDict)]
1656  self.numSubTables = len(self.tables)
1657  # TODO(behdad) Convert formats when needed.
1658  # In particular, if we have a format=12 without non-BMP
1659  # characters, either drop format=12 one or convert it
1660  # to format=4 if there's not one.
1661  return True # Required table
1662
1663@_add_method(ttLib.getTableClass('name'))
1664def prune_pre_subset(self, options):
1665  if '*' not in options.name_IDs:
1666    self.names = [n for n in self.names if n.nameID in options.name_IDs]
1667  if not options.name_legacy:
1668    self.names = [n for n in self.names
1669                  if n.platformID == 3 and n.platEncID == 1]
1670  if '*' not in options.name_languages:
1671    self.names = [n for n in self.names if n.langID in options.name_languages]
1672  return True  # Required table
1673
1674
1675# TODO(behdad) OS/2 ulUnicodeRange / ulCodePageRange?
1676# TODO(behdad) Drop AAT tables.
1677# TODO(behdad) Drop unneeded GSUB/GPOS Script/LangSys entries.
1678# TODO(behdad) Drop empty GSUB/GPOS, and GDEF if no GSUB/GPOS left
1679# TODO(behdad) Drop GDEF subitems if unused by lookups
1680# TODO(behdad) Avoid recursing too much (in GSUB/GPOS and in CFF)
1681# TODO(behdad) Text direction considerations.
1682# TODO(behdad) Text script / language considerations.
1683
1684class Options(object):
1685
1686  class UnknownOptionError(Exception):
1687    pass
1688
1689  _drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'SVG ',
1690                          'PCLT', 'LTSH']
1691  _drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill']  # Graphite
1692  _drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL']  # Color
1693  _no_subset_tables_default = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2',
1694                               'loca', 'name', 'cvt ', 'fpgm', 'prep']
1695  _hinting_tables_default = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
1696
1697  # Based on HarfBuzz shapers
1698  _layout_features_groups = {
1699    # Default shaper
1700    'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
1701    'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
1702    'vertical':  ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
1703    'ltr': ['ltra', 'ltrm'],
1704    'rtl': ['rtla', 'rtlm'],
1705    # Complex shapers
1706    'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3',
1707               'cswh', 'mset'],
1708    'hangul': ['ljmo', 'vjmo', 'tjmo'],
1709    'tibetan': ['abvs', 'blws', 'abvm', 'blwm'],
1710    'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half',
1711              'abvf', 'pstf', 'cfar', 'vatu', 'cjct', 'init', 'pres',
1712              'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
1713  }
1714  _layout_features_default = _uniq_sort(sum(
1715      _layout_features_groups.itervalues(), []))
1716
1717  drop_tables = _drop_tables_default
1718  no_subset_tables = _no_subset_tables_default
1719  hinting_tables = _hinting_tables_default
1720  layout_features = _layout_features_default
1721  hinting = True
1722  glyph_names = False
1723  legacy_cmap = False
1724  symbol_cmap = False
1725  name_IDs = [1, 2]  # Family and Style
1726  name_legacy = False
1727  name_languages = [0x0409]  # English
1728  notdef_glyph = True # gid0 for TrueType / .notdef for CFF
1729  notdef_outline = False # No need for notdef to have an outline really
1730  recommended_glyphs = False  # gid1, gid2, gid3 for TrueType
1731  recalc_bounds = False # Recalculate font bounding boxes
1732  canonical_order = False # Order tables as recommended
1733  flavor = None # May be 'woff'
1734
1735  def __init__(self, **kwargs):
1736
1737    self.set(**kwargs)
1738
1739  def set(self, **kwargs):
1740    for k,v in kwargs.iteritems():
1741      if not hasattr(self, k):
1742        raise self.UnknownOptionError("Unknown option '%s'" % k)
1743      setattr(self, k, v)
1744
1745  def parse_opts(self, argv, ignore_unknown=False):
1746    ret = []
1747    opts = {}
1748    for a in argv:
1749      orig_a = a
1750      if not a.startswith('--'):
1751        ret.append(a)
1752        continue
1753      a = a[2:]
1754      i = a.find('=')
1755      op = '='
1756      if i == -1:
1757        if a.startswith("no-"):
1758          k = a[3:]
1759          v = False
1760        else:
1761          k = a
1762          v = True
1763      else:
1764        k = a[:i]
1765        if k[-1] in "-+":
1766          op = k[-1]+'='  # Ops is '-=' or '+=' now.
1767          k = k[:-1]
1768        v = a[i+1:]
1769      k = k.replace('-', '_')
1770      if not hasattr(self, k):
1771        if ignore_unknown == True or k in ignore_unknown:
1772          ret.append(orig_a)
1773          continue
1774        else:
1775          raise self.UnknownOptionError("Unknown option '%s'" % a)
1776
1777      ov = getattr(self, k)
1778      if isinstance(ov, bool):
1779        v = bool(v)
1780      elif isinstance(ov, int):
1781        v = int(v)
1782      elif isinstance(ov, list):
1783        vv = v.split(',')
1784        if vv == ['']:
1785          vv = []
1786        vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv]
1787        if op == '=':
1788          v = vv
1789        elif op == '+=':
1790          v = ov
1791          v.extend(vv)
1792        elif op == '-=':
1793          v = ov
1794          for x in vv:
1795            if x in v:
1796              v.remove(x)
1797        else:
1798          assert 0
1799
1800      opts[k] = v
1801    self.set(**opts)
1802
1803    return ret
1804
1805
1806class Subsetter(object):
1807
1808  def __init__(self, options=None, log=None):
1809
1810    if not log:
1811      log = Logger()
1812    if not options:
1813      options = Options()
1814
1815    self.options = options
1816    self.log = log
1817    self.unicodes_requested = set()
1818    self.glyphs_requested = set()
1819    self.glyphs = set()
1820
1821  def populate(self, glyphs=[], unicodes=[], text=""):
1822    self.unicodes_requested.update(unicodes)
1823    if isinstance(text, str):
1824      text = text.decode("utf8")
1825    for u in text:
1826      self.unicodes_requested.add(ord(u))
1827    self.glyphs_requested.update(glyphs)
1828    self.glyphs.update(glyphs)
1829
1830  def _prune_pre_subset(self, font):
1831
1832    for tag in font.keys():
1833      if tag == 'GlyphOrder': continue
1834
1835      if(tag in self.options.drop_tables or
1836         (tag in self.options.hinting_tables and not self.options.hinting)):
1837        self.log(tag, "dropped")
1838        del font[tag]
1839        continue
1840
1841      clazz = ttLib.getTableClass(tag)
1842
1843      if hasattr(clazz, 'prune_pre_subset'):
1844        table = font[tag]
1845        self.log.lapse("load '%s'" % tag)
1846        retain = table.prune_pre_subset(self.options)
1847        self.log.lapse("prune  '%s'" % tag)
1848        if not retain:
1849          self.log(tag, "pruned to empty; dropped")
1850          del font[tag]
1851          continue
1852        else:
1853          self.log(tag, "pruned")
1854
1855  def _closure_glyphs(self, font):
1856
1857    self.glyphs = self.glyphs_requested.copy()
1858
1859    if 'cmap' in font:
1860      font['cmap'].closure_glyphs(self)
1861    self.glyphs_cmaped = self.glyphs
1862
1863    if self.options.notdef_glyph:
1864      if 'glyf' in font:
1865        self.glyphs.add(font.getGlyphName(0))
1866        self.log("Added gid0 to subset")
1867      else:
1868        self.glyphs.add('.notdef')
1869        self.log("Added .notdef to subset")
1870    if self.options.recommended_glyphs:
1871      if 'glyf' in font:
1872        for i in range(4):
1873          self.glyphs.add(font.getGlyphName(i))
1874        self.log("Added first four glyphs to subset")
1875
1876    if 'GSUB' in font:
1877      self.log("Closing glyph list over 'GSUB': %d glyphs before" %
1878                len(self.glyphs))
1879      self.log.glyphs(self.glyphs, font=font)
1880      font['GSUB'].closure_glyphs(self)
1881      self.log("Closed  glyph list over 'GSUB': %d glyphs after" %
1882                len(self.glyphs))
1883      self.log.glyphs(self.glyphs, font=font)
1884      self.log.lapse("close glyph list over 'GSUB'")
1885    self.glyphs_gsubed = self.glyphs.copy()
1886
1887    if 'glyf' in font:
1888      self.log("Closing glyph list over 'glyf': %d glyphs before" %
1889                len(self.glyphs))
1890      self.log.glyphs(self.glyphs, font=font)
1891      font['glyf'].closure_glyphs(self)
1892      self.log("Closed  glyph list over 'glyf': %d glyphs after" %
1893                len(self.glyphs))
1894      self.log.glyphs(self.glyphs, font=font)
1895      self.log.lapse("close glyph list over 'glyf'")
1896    self.glyphs_glyfed = self.glyphs.copy()
1897
1898    self.glyphs_all = self.glyphs.copy()
1899
1900    self.log("Retaining %d glyphs: " % len(self.glyphs_all))
1901
1902  def _subset_glyphs(self, font):
1903    for tag in font.keys():
1904      if tag == 'GlyphOrder': continue
1905      clazz = ttLib.getTableClass(tag)
1906
1907      if tag in self.options.no_subset_tables:
1908        self.log(tag, "subsetting not needed")
1909      elif hasattr(clazz, 'subset_glyphs'):
1910        table = font[tag]
1911        self.glyphs = self.glyphs_all
1912        retain = table.subset_glyphs(self)
1913        self.glyphs = self.glyphs_all
1914        self.log.lapse("subset '%s'" % tag)
1915        if not retain:
1916          self.log(tag, "subsetted to empty; dropped")
1917          del font[tag]
1918        else:
1919          self.log(tag, "subsetted")
1920      else:
1921        self.log(tag, "NOT subset; don't know how to subset; dropped")
1922        del font[tag]
1923
1924    glyphOrder = font.getGlyphOrder()
1925    glyphOrder = [g for g in glyphOrder if g in self.glyphs_all]
1926    font.setGlyphOrder(glyphOrder)
1927    font._buildReverseGlyphOrderDict()
1928    self.log.lapse("subset GlyphOrder")
1929
1930  def _prune_post_subset(self, font):
1931    for tag in font.keys():
1932      if tag == 'GlyphOrder': continue
1933      clazz = ttLib.getTableClass(tag)
1934      if hasattr(clazz, 'prune_post_subset'):
1935        table = font[tag]
1936        retain = table.prune_post_subset(self.options)
1937        self.log.lapse("prune  '%s'" % tag)
1938        if not retain:
1939          self.log(tag, "pruned to empty; dropped")
1940          del font[tag]
1941        else:
1942          self.log(tag, "pruned")
1943
1944  def subset(self, font):
1945
1946    self._prune_pre_subset(font)
1947    self._closure_glyphs(font)
1948    self._subset_glyphs(font)
1949    self._prune_post_subset(font)
1950
1951
1952class Logger(object):
1953
1954  def __init__(self, verbose=False, xml=False, timing=False):
1955    self.verbose = verbose
1956    self.xml = xml
1957    self.timing = timing
1958    self.last_time = self.start_time = time.time()
1959
1960  def parse_opts(self, argv):
1961    argv = argv[:]
1962    for v in ['verbose', 'xml', 'timing']:
1963      if "--"+v in argv:
1964        setattr(self, v, True)
1965        argv.remove("--"+v)
1966    return argv
1967
1968  def __call__(self, *things):
1969    if not self.verbose:
1970      return
1971    print ' '.join(str(x) for x in things)
1972
1973  def lapse(self, *things):
1974    if not self.timing:
1975      return
1976    new_time = time.time()
1977    print "Took %0.3fs to %s" %(new_time - self.last_time,
1978                                 ' '.join(str(x) for x in things))
1979    self.last_time = new_time
1980
1981  def glyphs(self, glyphs, font=None):
1982    self("Names: ", sorted(glyphs))
1983    if font:
1984      reverseGlyphMap = font.getReverseGlyphMap()
1985      self("Gids : ", sorted(reverseGlyphMap[g] for g in glyphs))
1986
1987  def font(self, font, file=sys.stdout):
1988    if not self.xml:
1989      return
1990    from fontTools.misc import xmlWriter
1991    writer = xmlWriter.XMLWriter(file)
1992    font.disassembleInstructions = False  # Work around ttLib bug
1993    for tag in font.keys():
1994      writer.begintag(tag)
1995      writer.newline()
1996      font[tag].toXML(writer, font)
1997      writer.endtag(tag)
1998      writer.newline()
1999
2000
2001def load_font(fontFile,
2002              options,
2003              checkChecksums=False,
2004              dontLoadGlyphNames=False):
2005
2006  font = ttLib.TTFont(fontFile,
2007                                checkChecksums=checkChecksums,
2008                                recalcBBoxes=options.recalc_bounds)
2009
2010  # Hack:
2011  #
2012  # If we don't need glyph names, change 'post' class to not try to
2013  # load them.  It avoid lots of headache with broken fonts as well
2014  # as loading time.
2015  #
2016  # Ideally ttLib should provide a way to ask it to skip loading
2017  # glyph names.  But it currently doesn't provide such a thing.
2018  #
2019  if dontLoadGlyphNames:
2020    post = ttLib.getTableClass('post')
2021    saved = post.decode_format_2_0
2022    post.decode_format_2_0 = post.decode_format_3_0
2023    f = font['post']
2024    if f.formatType == 2.0:
2025      f.formatType = 3.0
2026    post.decode_format_2_0 = saved
2027
2028  return font
2029
2030def save_font(font, outfile, options):
2031  if options.flavor and not hasattr(font, 'flavor'):
2032    raise Exception("fonttools version does not support flavors.")
2033  font.flavor = options.flavor
2034  font.save(outfile, reorderTables=options.canonical_order)
2035
2036def main(args):
2037
2038  log = Logger()
2039  args = log.parse_opts(args)
2040
2041  options = Options()
2042  args = options.parse_opts(args, ignore_unknown=['text'])
2043
2044  if len(args) < 2:
2045    print >>sys.stderr, "usage: pyftsubset font-file glyph... [--text=ABC]... [--option=value]..."
2046    sys.exit(1)
2047
2048  fontfile = args[0]
2049  args = args[1:]
2050
2051  dontLoadGlyphNames =(not options.glyph_names and
2052         all(any(g.startswith(p)
2053             for p in ['gid', 'glyph', 'uni', 'U+'])
2054              for g in args))
2055
2056  font = load_font(fontfile, options, dontLoadGlyphNames=dontLoadGlyphNames)
2057  subsetter = Subsetter(options=options, log=log)
2058  log.lapse("load font")
2059
2060  names = font.getGlyphNames()
2061  log.lapse("loading glyph names")
2062
2063  glyphs = []
2064  unicodes = []
2065  text = ""
2066  for g in args:
2067    if g == '*':
2068      glyphs.extend(font.getGlyphOrder())
2069      continue
2070    if g in names:
2071      glyphs.append(g)
2072      continue
2073    if g.startswith('--text='):
2074      text += g[7:]
2075      continue
2076    if g.startswith('uni') or g.startswith('U+'):
2077      if g.startswith('uni') and len(g) > 3:
2078        g = g[3:]
2079      elif g.startswith('U+') and len(g) > 2:
2080        g = g[2:]
2081      u = int(g, 16)
2082      unicodes.append(u)
2083      continue
2084    if g.startswith('gid') or g.startswith('glyph'):
2085      if g.startswith('gid') and len(g) > 3:
2086        g = g[3:]
2087      elif g.startswith('glyph') and len(g) > 5:
2088        g = g[5:]
2089      try:
2090        glyphs.append(font.getGlyphName(int(g), requireReal=1))
2091      except ValueError:
2092        raise Exception("Invalid glyph identifier: %s" % g)
2093      continue
2094    raise Exception("Invalid glyph identifier: %s" % g)
2095  log.lapse("compile glyph list")
2096  log("Unicodes:", unicodes)
2097  log("Glyphs:", glyphs)
2098
2099  subsetter.populate(glyphs=glyphs, unicodes=unicodes, text=text)
2100  subsetter.subset(font)
2101
2102  outfile = fontfile + '.subset'
2103
2104  save_font (font, outfile, options)
2105  log.lapse("compile and save font")
2106
2107  log.last_time = log.start_time
2108  log.lapse("make one with everything(TOTAL TIME)")
2109
2110  if log.verbose:
2111    import os
2112    log("Input  font: %d bytes" % os.path.getsize(fontfile))
2113    log("Subset font: %d bytes" % os.path.getsize(outfile))
2114
2115  log.font(font)
2116
2117  font.close()
2118
2119
2120__all__ = [
2121  'Options',
2122  'Subsetter',
2123  'Logger',
2124  'load_font',
2125  'save_font',
2126  'main'
2127]
2128
2129if __name__ == '__main__':
2130  main(sys.argv[1:])
2131