blob: b6966ed4c3bc99b3cf5174000524f8e1a01527a8 [file] [log] [blame]
Behdad Esfahbod54660612013-07-21 18:16:55 -04001#!/usr/bin/python
Behdad Esfahboddb6d2e92013-08-13 12:42:12 -04002#
Behdad Esfahbod54660612013-07-21 18:16:55 -04003# Python OpenType Layout Subsetter
Behdad Esfahboddb6d2e92013-08-13 12:42:12 -04004# Later grown into a full OpenType subsetter...
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04005#
6# Copyright 2013 Google, Inc. All Rights Reserved.
7#
8# Licensed under the Apache License, Version 2.0 (the "License");
9# you may not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS,
16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19#
20# Google Author(s): Behdad Esfahbod
21#
Behdad Esfahbod54660612013-07-21 18:16:55 -040022
Behdad Esfahbodfa3bc5e2013-07-24 14:37:58 -040023# Try running on PyPy
24try:
25 import numpypy
26except ImportError:
27 pass
28
Behdad Esfahbod54660612013-07-21 18:16:55 -040029import fontTools.ttx
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -040030import struct
Behdad Esfahbod54660612013-07-21 18:16:55 -040031
Behdad Esfahbod54660612013-07-21 18:16:55 -040032
Behdad Esfahbod02b92062013-07-21 18:40:59 -040033def add_method (*clazzes):
Behdad Esfahbod54660612013-07-21 18:16:55 -040034 def wrapper(method):
Behdad Esfahbod02b92062013-07-21 18:40:59 -040035 for clazz in clazzes:
Behdad Esfahbodc0d59592013-07-24 14:41:47 -040036 assert clazz.__name__ != 'DefaultTable', 'Oops, table class not found.'
Behdad Esfahbod02b92062013-07-21 18:40:59 -040037 setattr (clazz, method.func_name, method)
Behdad Esfahbod54660612013-07-21 18:16:55 -040038 return wrapper
39
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040040def unique_sorted (l):
Behdad Esfahbod2d9a0962013-07-31 13:33:31 -040041 return sorted (set (l))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040042
43
Behdad Esfahbod54660612013-07-21 18:16:55 -040044@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040045def intersect (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -040046 "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(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -040050def 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(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040055def subset (self, glyphs):
Behdad Esfahbodd821ea02013-07-23 10:50:43 -040056 "Returns ascending list of remaining coverage values."
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040057 indices = self.intersect (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -040058 self.glyphs = [g for g in self.glyphs if g in glyphs]
59 return indices
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040060
Behdad Esfahbod14374262013-08-08 22:26:49 -040061@add_method(fontTools.ttLib.tables.otTables.Coverage)
62def remap (self, coverage_map):
63 "Remaps coverage."
64 self.glyphs = [self.glyphs[i] for i in coverage_map]
65
Behdad Esfahbod54660612013-07-21 18:16:55 -040066@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040067def intersect (self, glyphs):
Behdad Esfahbode10803e2013-08-08 21:09:27 -040068 "Returns ascending list of matching class values."
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040069 return unique_sorted (([0] if any (g not in self.classDefs for g in glyphs) else []) + \
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040070 [v for g,v in self.classDefs.iteritems() if g in glyphs])
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040071
72@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -040073def intersect_class (self, glyphs, klass):
74 "Returns set of glyphs matching class."
Behdad Esfahbod0befd6b2013-08-05 22:47:14 -040075 if klass == 0:
Behdad Esfahbod849d25c2013-08-12 19:24:24 -040076 return set (g for g in glyphs if g not in self.classDefs)
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040077 return set (g for g,v in self.classDefs.iteritems() if v == klass and g in glyphs)
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040078
79@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040080def subset (self, glyphs, remap=False):
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040081 "Returns ascending list of remaining classes."
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040082 self.classDefs = {g:v for g,v in self.classDefs.iteritems() if g in glyphs}
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040083 # Note: while class 0 has the special meaning of "not matched", if no glyph will
84 # ever /not match/, we can optimize class 0 out too.
85 indices = unique_sorted (([0] if any (g not in self.classDefs for g in glyphs) else []) + \
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040086 self.classDefs.itervalues())
Behdad Esfahbodde71dca2013-07-24 12:40:54 -040087 if remap:
88 self.remap (indices)
89 return indices
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -040090
91@add_method(fontTools.ttLib.tables.otTables.ClassDef)
92def remap (self, class_map):
93 "Remaps classes."
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040094 self.classDefs = {g:class_map.index (v) for g,v in self.classDefs.iteritems()}
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040095
Behdad Esfahbod54660612013-07-21 18:16:55 -040096@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -040097def closure_glyphs (self, s, cur_glyphs=None):
98 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -040099 if self.Format in [1, 2]:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400100 s.glyphs.update (v for g,v in self.mapping.iteritems() if g in cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400101 else:
102 assert 0, "unknown format: %s" % self.Format
103
104@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400105def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400106 if self.Format in [1, 2]:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400107 self.mapping = {g:v for g,v in self.mapping.iteritems() if g in s.glyphs and v in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400108 return bool (self.mapping)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400109 else:
110 assert 0, "unknown format: %s" % self.Format
111
112@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400113def closure_glyphs (self, s, cur_glyphs=None):
114 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400115 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400116 indices = self.Coverage.intersect (cur_glyphs)
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400117 s.glyphs.update (*(self.Sequence[i].Substitute for i in indices))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400118 else:
119 assert 0, "unknown format: %s" % self.Format
120
121@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400122def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400123 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400124 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400125 self.Sequence = [self.Sequence[i] for i in indices]
Behdad Esfahbod14374262013-08-08 22:26:49 -0400126 # Now drop rules generating glyphs we don't want
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400127 indices = [i for i,seq in enumerate (self.Sequence)
Behdad Esfahbod14374262013-08-08 22:26:49 -0400128 if all (sub in s.glyphs for sub in seq.Substitute)]
129 self.Sequence = [self.Sequence[i] for i in indices]
130 self.Coverage.remap (indices)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400131 self.SequenceCount = len (self.Sequence)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400132 return bool (self.SequenceCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400133 else:
134 assert 0, "unknown format: %s" % self.Format
135
136@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400137def closure_glyphs (self, s, cur_glyphs=None):
138 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400139 if self.Format == 1:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400140 s.glyphs.update (*(vlist for g,vlist in self.alternates.iteritems() if g in cur_glyphs))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400141 else:
142 assert 0, "unknown format: %s" % self.Format
143
144@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400145def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400146 if self.Format == 1:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400147 self.alternates = {g:vlist for g,vlist in self.alternates.iteritems()
Behdad Esfahbod14374262013-08-08 22:26:49 -0400148 if g in s.glyphs and all (v in s.glyphs for v in vlist)}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400149 return bool (self.alternates)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400150 else:
151 assert 0, "unknown format: %s" % self.Format
152
153@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400154def closure_glyphs (self, s, cur_glyphs=None):
155 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400156 if self.Format == 1:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400157 s.glyphs.update (*([seq.LigGlyph for seq in seqs if all(c in s.glyphs for c in seq.Component)]
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400158 for g,seqs in self.ligatures.iteritems() if g in cur_glyphs))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400159 else:
160 assert 0, "unknown format: %s" % self.Format
161
162@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400163def subset_glyphs (self, s):
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400164 if self.Format == 1:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400165 self.ligatures = {g:v for g,v in self.ligatures.iteritems() if g in s.glyphs}
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400166 self.ligatures = {g:[seq for seq in seqs
167 if seq.LigGlyph in s.glyphs and
168 all (c in s.glyphs for c in seq.Component)]
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400169 for g,seqs in self.ligatures.iteritems()}
170 self.ligatures = {g:v for g,v in self.ligatures.iteritems() if v}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400171 return bool (self.ligatures)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400172 else:
173 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400174
Behdad Esfahbod54660612013-07-21 18:16:55 -0400175@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400176def closure_glyphs (self, s, cur_glyphs=None):
177 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400178 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400179 indices = self.Coverage.intersect (cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400180 if not indices or \
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400181 not all (c.intersect (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage):
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400182 return
183 s.glyphs.update (self.Substitute[i] for i in indices)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400184 else:
185 assert 0, "unknown format: %s" % self.Format
186
187@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400188def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400189 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400190 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400191 self.Substitute = [self.Substitute[i] for i in indices]
Behdad Esfahbod14374262013-08-08 22:26:49 -0400192 # Now drop rules generating glyphs we don't want
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400193 indices = [i for i,sub in enumerate (self.Substitute)
Behdad Esfahbod14374262013-08-08 22:26:49 -0400194 if sub in s.glyphs]
195 self.Substitute = [self.Substitute[i] for i in indices]
196 self.Coverage.remap (indices)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400197 self.GlyphCount = len (self.Substitute)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400198 return bool (self.GlyphCount and all (c.subset (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400199 else:
200 assert 0, "unknown format: %s" % self.Format
201
202@add_method(fontTools.ttLib.tables.otTables.SinglePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400203def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400204 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400205 return len (self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400206 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400207 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400208 self.Value = [self.Value[i] for i in indices]
209 self.ValueCount = len (self.Value)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400210 return bool (self.ValueCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400211 else:
212 assert 0, "unknown format: %s" % self.Format
213
214@add_method(fontTools.ttLib.tables.otTables.PairPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400215def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400216 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400217 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400218 self.PairSet = [self.PairSet[i] for i in indices]
219 for p in self.PairSet:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400220 p.PairValueRecord = [r for r in p.PairValueRecord if r.SecondGlyph in s.glyphs]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400221 p.PairValueCount = len (p.PairValueRecord)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400222 self.PairSet = [p for p in self.PairSet if p.PairValueCount]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400223 self.PairSetCount = len (self.PairSet)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400224 return bool (self.PairSetCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400225 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400226 class1_map = self.ClassDef1.subset (s.glyphs, remap=True)
227 class2_map = self.ClassDef2.subset (s.glyphs, remap=True)
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -0400228 self.Class1Record = [self.Class1Record[i] for i in class1_map]
229 for c in self.Class1Record:
230 c.Class2Record = [c.Class2Record[i] for i in class2_map]
231 self.Class1Count = len (class1_map)
232 self.Class2Count = len (class2_map)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400233 return bool (self.Class1Count and self.Class2Count and self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400234 else:
235 assert 0, "unknown format: %s" % self.Format
236
237@add_method(fontTools.ttLib.tables.otTables.CursivePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400238def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400239 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400240 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400241 self.EntryExitRecord = [self.EntryExitRecord[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400242 self.EntryExitCount = len (self.EntryExitRecord)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400243 return bool (self.EntryExitCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400244 else:
245 assert 0, "unknown format: %s" % self.Format
246
247@add_method(fontTools.ttLib.tables.otTables.MarkBasePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400248def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400249 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400250 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400251 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
252 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400253 base_indices = self.BaseCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400254 self.BaseArray.BaseRecord = [self.BaseArray.BaseRecord[i] for i in base_indices]
255 self.BaseArray.BaseCount = len (self.BaseArray.BaseRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400256 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400257 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400258 self.ClassCount = len (class_indices)
259 for m in self.MarkArray.MarkRecord:
260 m.Class = class_indices.index (m.Class)
261 for b in self.BaseArray.BaseRecord:
262 b.BaseAnchor = [b.BaseAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400263 return bool (self.ClassCount and self.MarkArray.MarkCount and self.BaseArray.BaseCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400264 else:
265 assert 0, "unknown format: %s" % self.Format
266
267@add_method(fontTools.ttLib.tables.otTables.MarkLigPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400268def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400269 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400270 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400271 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
272 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400273 ligature_indices = self.LigatureCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400274 self.LigatureArray.LigatureAttach = [self.LigatureArray.LigatureAttach[i] for i in ligature_indices]
275 self.LigatureArray.LigatureCount = len (self.LigatureArray.LigatureAttach)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400276 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400277 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400278 self.ClassCount = len (class_indices)
279 for m in self.MarkArray.MarkRecord:
280 m.Class = class_indices.index (m.Class)
281 for l in self.LigatureArray.LigatureAttach:
282 for c in l.ComponentRecord:
283 c.LigatureAnchor = [c.LigatureAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400284 return bool (self.ClassCount and self.MarkArray.MarkCount and self.LigatureArray.LigatureCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400285 else:
286 assert 0, "unknown format: %s" % self.Format
287
288@add_method(fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400289def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400290 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400291 mark1_indices = self.Mark1Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400292 self.Mark1Array.MarkRecord = [self.Mark1Array.MarkRecord[i] for i in mark1_indices]
293 self.Mark1Array.MarkCount = len (self.Mark1Array.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400294 mark2_indices = self.Mark2Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400295 self.Mark2Array.Mark2Record = [self.Mark2Array.Mark2Record[i] for i in mark2_indices]
296 self.Mark2Array.MarkCount = len (self.Mark2Array.Mark2Record)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400297 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400298 class_indices = unique_sorted (v.Class for v in self.Mark1Array.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400299 self.ClassCount = len (class_indices)
300 for m in self.Mark1Array.MarkRecord:
301 m.Class = class_indices.index (m.Class)
302 for b in self.Mark2Array.Mark2Record:
303 b.Mark2Anchor = [b.Mark2Anchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400304 return bool (self.ClassCount and self.Mark1Array.MarkCount and self.Mark2Array.MarkCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400305 else:
306 assert 0, "unknown format: %s" % self.Format
307
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400308@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400309 fontTools.ttLib.tables.otTables.MultipleSubst,
310 fontTools.ttLib.tables.otTables.AlternateSubst,
311 fontTools.ttLib.tables.otTables.LigatureSubst,
312 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
313 fontTools.ttLib.tables.otTables.SinglePos,
314 fontTools.ttLib.tables.otTables.PairPos,
315 fontTools.ttLib.tables.otTables.CursivePos,
316 fontTools.ttLib.tables.otTables.MarkBasePos,
317 fontTools.ttLib.tables.otTables.MarkLigPos,
318 fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400319def subset_lookups (self, lookup_indices):
320 pass
321
322@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400323 fontTools.ttLib.tables.otTables.MultipleSubst,
324 fontTools.ttLib.tables.otTables.AlternateSubst,
325 fontTools.ttLib.tables.otTables.LigatureSubst,
326 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
327 fontTools.ttLib.tables.otTables.SinglePos,
328 fontTools.ttLib.tables.otTables.PairPos,
329 fontTools.ttLib.tables.otTables.CursivePos,
330 fontTools.ttLib.tables.otTables.MarkBasePos,
331 fontTools.ttLib.tables.otTables.MarkLigPos,
332 fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400333def collect_lookups (self):
334 return []
335
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400336@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
337 fontTools.ttLib.tables.otTables.AlternateSubst,
338 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
339def may_have_non_1to1 (self):
340 return False
341
342@add_method(fontTools.ttLib.tables.otTables.MultipleSubst,
343 fontTools.ttLib.tables.otTables.LigatureSubst,
344 fontTools.ttLib.tables.otTables.ContextSubst,
345 fontTools.ttLib.tables.otTables.ChainContextSubst)
346def may_have_non_1to1 (self):
347 return True
348
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400349@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
350 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
351def __classify_context (self):
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400352
353 class ContextHelper:
354 def __init__ (self, klass, Format):
355 if klass.__name__.endswith ('Subst'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400356 Typ = 'Sub'
357 Type = 'Subst'
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400358 else:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400359 Typ = 'Pos'
360 Type = 'Pos'
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400361 if klass.__name__.startswith ('Chain'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400362 Chain = 'Chain'
363 else:
364 Chain = ''
365 ChainTyp = Chain+Typ
366
367 self.Typ = Typ
368 self.Type = Type
369 self.Chain = Chain
370 self.ChainTyp = ChainTyp
371
372 self.LookupRecord = Type+'LookupRecord'
373
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400374 if Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400375 Coverage = lambda r: r.Coverage
376 ChainCoverage = lambda r: r.Coverage
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400377 ContextData = lambda r: (None,)
378 ChainContextData = lambda r: (None, None, None)
379 RuleData = lambda r: (r.Input,)
380 ChainRuleData = lambda r: (r.Backtrack, r.Input, r.LookAhead)
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400381 SetRuleData = None
382 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400383 elif Format == 2:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400384 Coverage = lambda r: r.Coverage
385 ChainCoverage = lambda r: r.Coverage
Behdad Esfahbode3f20732013-07-24 11:26:43 -0400386 ContextData = lambda r: (r.ClassDef,)
387 ChainContextData = lambda r: (r.LookAheadClassDef, r.InputClassDef, r.BacktrackClassDef)
388 RuleData = lambda r: (r.Class,)
389 ChainRuleData = lambda r: (r.LookAhead, r.Input, r.Backtrack)
390 def SetRuleData (r, d): (r.Class,) = d
391 def ChainSetRuleData (r, d): (r.LookAhead, r.Input, r.Backtrack) = d
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400392 elif Format == 3:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400393 Coverage = lambda r: r.Coverage[0]
394 ChainCoverage = lambda r: r.InputCoverage[0]
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400395 ContextData = None
396 ChainContextData = None
397 RuleData = lambda r: r.Coverage
398 ChainRuleData = lambda r: r.LookAheadCoverage + r.InputCoverage + r.BacktrackCoverage
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400399 SetRuleData = None
400 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400401 else:
402 assert 0, "unknown format: %s" % Format
403
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400404 if Chain:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400405 self.Coverage = ChainCoverage
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400406 self.ContextData = ChainContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400407 self.RuleData = ChainRuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400408 self.SetRuleData = ChainSetRuleData
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400409 else:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400410 self.Coverage = Coverage
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400411 self.ContextData = ContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400412 self.RuleData = RuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400413 self.SetRuleData = SetRuleData
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400414
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400415 if Format == 1:
416 self.Rule = ChainTyp+'Rule'
417 self.RuleCount = ChainTyp+'RuleCount'
418 self.RuleSet = ChainTyp+'RuleSet'
419 self.RuleSetCount = ChainTyp+'RuleSetCount'
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400420 self.Intersect = lambda glyphs, ContextData, RuleData: [RuleData] if RuleData in glyphs else []
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400421 elif Format == 2:
422 self.Rule = ChainTyp+'ClassRule'
423 self.RuleCount = ChainTyp+'ClassRuleCount'
424 self.RuleSet = ChainTyp+'ClassSet'
425 self.RuleSetCount = ChainTyp+'ClassSetCount'
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400426 self.Intersect = lambda glyphs, ContextData, RuleData: ContextData.intersect_class (glyphs, RuleData)
Behdad Esfahbod89987002013-07-23 23:07:42 -0400427
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400428 self.ClassDef = 'InputClassDef' if Chain else 'ClassDef'
Behdad Esfahbod27108392013-07-23 16:40:47 -0400429
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400430 if self.Format not in [1, 2, 3]:
431 return None # Don't shoot the messenger; let it go
432 if not hasattr (self.__class__, "__ContextHelpers"):
433 self.__class__.__ContextHelpers = {}
434 if self.Format not in self.__class__.__ContextHelpers:
435 self.__class__.__ContextHelpers[self.Format] = ContextHelper (self.__class__, self.Format)
436 return self.__class__.__ContextHelpers[self.Format]
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400437
Behdad Esfahbodf2b6d9c2013-07-23 17:31:54 -0400438@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400439def closure_glyphs (self, s, cur_glyphs=None):
440 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400441 c = self.__classify_context ()
442
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400443 indices = c.Coverage (self).intersect (s.glyphs)
444 if not indices:
445 return []
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400446 cur_glyphs = c.Coverage (self).intersect_glyphs (s.glyphs);
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400447
Behdad Esfahbod00776972013-07-23 15:33:00 -0400448 if self.Format == 1:
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400449 ContextData = c.ContextData (self)
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400450 rss = getattr (self, c.RuleSet)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400451 for i in indices:
452 if not rss[i]: continue
453 for r in getattr (rss[i], c.Rule):
454 if not r: continue
455 if all (all (c.Intersect (s.glyphs, cd, k) for k in klist)
456 for cd,klist in zip (ContextData, c.RuleData (r))):
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400457 chaos = False
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400458 for ll in getattr (r, c.LookupRecord):
459 if not ll: continue
460 seqi = ll.SequenceIndex
461 if seqi == 0:
462 pos_glyphs = set (c.Coverage (self).glyphs[i])
463 else:
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400464 if chaos:
465 pos_glyphs = s.glyphs
466 else:
467 pos_glyphs = set (r.Input[seqi - 1])
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400468 lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400469 chaos = chaos or lookup.may_have_non_1to1 ()
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400470 lookup.closure_glyphs (s, cur_glyphs=pos_glyphs)
Behdad Esfahbod00776972013-07-23 15:33:00 -0400471 elif self.Format == 2:
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400472 ClassDef = getattr (self, c.ClassDef)
473 indices = ClassDef.intersect (cur_glyphs)
474 ContextData = c.ContextData (self)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400475 rss = getattr (self, c.RuleSet)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400476 for i in indices:
477 if not rss[i]: continue
478 for r in getattr (rss[i], c.Rule):
479 if not r: continue
480 if all (all (c.Intersect (s.glyphs, cd, k) for k in klist)
481 for cd,klist in zip (ContextData, c.RuleData (r))):
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400482 chaos = False
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400483 for ll in getattr (r, c.LookupRecord):
484 if not ll: continue
485 seqi = ll.SequenceIndex
486 if seqi == 0:
487 pos_glyphs = ClassDef.intersect_class (cur_glyphs, i)
488 else:
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400489 if chaos:
490 pos_glyphs = s.glyphs
491 else:
492 pos_glyphs = ClassDef.intersect_class (s.glyphs, r.Input[seqi - 1])
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400493 lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400494 chaos = chaos or lookup.may_have_non_1to1 ()
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400495 lookup.closure_glyphs (s, cur_glyphs=pos_glyphs)
Behdad Esfahbod00776972013-07-23 15:33:00 -0400496 elif self.Format == 3:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400497 if not all (x.intersect (s.glyphs) for x in c.RuleData (self)):
Behdad Esfahbod00776972013-07-23 15:33:00 -0400498 return []
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400499 r = self
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400500 chaos = False
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400501 for ll in getattr (r, c.LookupRecord):
502 if not ll: continue
503 seqi = ll.SequenceIndex
504 if seqi == 0:
505 pos_glyphs = cur_glyphs
506 else:
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400507 if chaos:
508 pos_glyphs = s.glyphs
509 else:
510 pos_glyphs = r.InputCoverage[seqi].intersect_glyphs (s.glyphs)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400511 lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400512 chaos = chaos or lookup.may_have_non_1to1 ()
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400513 lookup.closure_glyphs (s, cur_glyphs=pos_glyphs)
Behdad Esfahbod00776972013-07-23 15:33:00 -0400514 else:
515 assert 0, "unknown format: %s" % self.Format
516
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400517@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ContextPos,
518 fontTools.ttLib.tables.otTables.ChainContextSubst, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400519def subset_glyphs (self, s):
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400520 c = self.__classify_context ()
521
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400522 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400523 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400524 rss = getattr (self, c.RuleSet)
525 rss = [rss[i] for i in indices]
526 for rs in rss:
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400527 if not rs: continue
528 ss = getattr (rs, c.Rule)
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400529 ss = [r for r in ss
530 if r and all (all (g in s.glyphs for g in glist)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400531 for glist in c.RuleData (r))]
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400532 setattr (rs, c.Rule, ss)
533 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400534 # Prune empty subrulesets
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400535 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400536 setattr (self, c.RuleSet, rss)
537 setattr (self, c.RuleSetCount, len (rss))
538 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400539 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400540 if not self.Coverage.subset (s.glyphs):
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400541 return False
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400542 indices = getattr (self, c.ClassDef).subset (self.Coverage.glyphs, remap=False)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400543 rss = getattr (self, c.RuleSet)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400544 rss = [rss[i] for i in indices]
545 ContextData = c.ContextData (self)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400546 klass_maps = [x.subset (s.glyphs, remap=True) for x in ContextData]
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400547 for rs in rss:
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400548 if not rs: continue
549 ss = getattr (rs, c.Rule)
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400550 ss = [r for r in ss
551 if r and all (all (k in klass_map for k in klist)
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400552 for klass_map,klist in zip (klass_maps, c.RuleData (r)))]
553 setattr (rs, c.Rule, ss)
554 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400555
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400556 # Remap rule classes
557 for r in ss:
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400558 c.SetRuleData (r, [[klass_map.index (k) for k in klist]
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400559 for klass_map,klist in zip (klass_maps, c.RuleData (r))])
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400560 # Prune empty subrulesets
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400561 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
562 setattr (self, c.RuleSet, rss)
563 setattr (self, c.RuleSetCount, len (rss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400564 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400565 elif self.Format == 3:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400566 return all (x.subset (s.glyphs) for x in c.RuleData (self))
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400567 else:
568 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400569
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400570@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
571 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400572def subset_lookups (self, lookup_indices):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400573 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400574
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400575 if self.Format in [1, 2]:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400576 for rs in getattr (self, c.RuleSet):
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400577 if not rs: continue
578 for r in getattr (rs, c.Rule):
579 if not r: continue
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400580 setattr (r, c.LookupRecord, [ll for ll in getattr (r, c.LookupRecord) if ll
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400581 if ll.LookupListIndex in lookup_indices])
582 for ll in getattr (r, c.LookupRecord):
583 if not ll: continue
584 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400585 elif self.Format == 3:
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400586 setattr (self, c.LookupRecord, [ll for ll in getattr (self, c.LookupRecord) if ll
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400587 if ll.LookupListIndex in lookup_indices])
588 for ll in getattr (self, c.LookupRecord):
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400589 if not ll: continue
590 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400591 else:
592 assert 0, "unknown format: %s" % self.Format
593
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400594@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
595 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400596def collect_lookups (self):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400597 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400598
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400599 if self.Format in [1, 2]:
Behdad Esfahbod27108392013-07-23 16:40:47 -0400600 return [ll.LookupListIndex \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400601 for rs in getattr (self, c.RuleSet) if rs \
602 for r in getattr (rs, c.Rule) if r \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400603 for ll in getattr (r, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400604 elif self.Format == 3:
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400605 return [ll.LookupListIndex \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400606 for ll in getattr (self, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400607 else:
608 assert 0, "unknown format: %s" % self.Format
609
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400610@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400611def closure_glyphs (self, s, cur_glyphs=None):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400612 if self.Format == 1:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400613 self.ExtSubTable.closure_glyphs (s, cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400614 else:
615 assert 0, "unknown format: %s" % self.Format
616
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400617@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
618def may_have_non_1to1 (self):
619 if self.Format == 1:
620 return self.ExtSubTable.may_have_non_1to1 ()
621 else:
622 assert 0, "unknown format: %s" % self.Format
623
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400624@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400625def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400626 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400627 return self.ExtSubTable.subset_glyphs (s)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400628 else:
629 assert 0, "unknown format: %s" % self.Format
630
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400631@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
632def subset_lookups (self, lookup_indices):
633 if self.Format == 1:
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400634 return self.ExtSubTable.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400635 else:
636 assert 0, "unknown format: %s" % self.Format
637
638@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
639def collect_lookups (self):
640 if self.Format == 1:
641 return self.ExtSubTable.collect_lookups ()
642 else:
643 assert 0, "unknown format: %s" % self.Format
644
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400645@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400646def closure_glyphs (self, s, cur_glyphs=None):
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400647 for st in self.SubTable:
648 if not st: continue
649 st.closure_glyphs (s, cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400650
651@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400652def subset_glyphs (self, s):
653 self.SubTable = [st for st in self.SubTable if st and st.subset_glyphs (s)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400654 self.SubTableCount = len (self.SubTable)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400655 return bool (self.SubTableCount)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400656
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400657@add_method(fontTools.ttLib.tables.otTables.Lookup)
658def subset_lookups (self, lookup_indices):
659 for s in self.SubTable:
660 s.subset_lookups (lookup_indices)
661
662@add_method(fontTools.ttLib.tables.otTables.Lookup)
663def collect_lookups (self):
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400664 return unique_sorted (sum ((st.collect_lookups () for st in self.SubTable if st), []))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400665
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400666@add_method(fontTools.ttLib.tables.otTables.Lookup)
667def may_have_non_1to1 (self):
668 return any (st.may_have_non_1to1 () for st in self.SubTable if st)
669
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400670@add_method(fontTools.ttLib.tables.otTables.LookupList)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400671def subset_glyphs (self, s):
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400672 "Returns the indices of nonempty lookups."
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400673 return [i for (i,l) in enumerate (self.Lookup) if l and l.subset_glyphs (s)]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400674
675@add_method(fontTools.ttLib.tables.otTables.LookupList)
676def subset_lookups (self, lookup_indices):
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400677 self.Lookup = [self.Lookup[i] for i in lookup_indices if i < self.LookupCount]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400678 self.LookupCount = len (self.Lookup)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400679 for l in self.Lookup:
680 l.subset_lookups (lookup_indices)
681
682@add_method(fontTools.ttLib.tables.otTables.LookupList)
683def closure_lookups (self, lookup_indices):
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400684 lookup_indices = unique_sorted (lookup_indices)
685 recurse = lookup_indices
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400686 while True:
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400687 recurse_lookups = sum ((self.Lookup[i].collect_lookups () for i in recurse if i < self.LookupCount), [])
688 recurse_lookups = [l for l in recurse_lookups if l not in lookup_indices and l < self.LookupCount]
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400689 if not recurse_lookups:
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400690 return unique_sorted (lookup_indices)
691 recurse_lookups = unique_sorted (recurse_lookups)
692 lookup_indices.extend (recurse_lookups)
693 recurse = recurse_lookups
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400694
695@add_method(fontTools.ttLib.tables.otTables.Feature)
696def subset_lookups (self, lookup_indices):
697 self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices]
698 # Now map them.
699 self.LookupListIndex = [lookup_indices.index (l) for l in self.LookupListIndex]
700 self.LookupCount = len (self.LookupListIndex)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400701 return self.LookupCount
Behdad Esfahbod54660612013-07-21 18:16:55 -0400702
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400703@add_method(fontTools.ttLib.tables.otTables.Feature)
704def collect_lookups (self):
705 return self.LookupListIndex[:]
706
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400707@add_method(fontTools.ttLib.tables.otTables.FeatureList)
708def subset_lookups (self, lookup_indices):
709 "Returns the indices of nonempty features."
710 feature_indices = [i for (i,f) in enumerate (self.FeatureRecord) if f.Feature.subset_lookups (lookup_indices)]
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400711 self.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400712 return feature_indices
713
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400714@add_method(fontTools.ttLib.tables.otTables.FeatureList)
715def collect_lookups (self, feature_indices):
716 return unique_sorted (sum ((self.FeatureRecord[i].Feature.collect_lookups () for i in feature_indices
717 if i < self.FeatureCount), []))
718
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400719@add_method(fontTools.ttLib.tables.otTables.FeatureList)
720def subset_features (self, feature_indices):
721 self.FeatureRecord = [self.FeatureRecord[i] for i in feature_indices]
722 self.FeatureCount = len (self.FeatureRecord)
723 return bool (self.FeatureCount)
724
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400725@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
726def subset_features (self, feature_indices):
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400727 if self.ReqFeatureIndex in feature_indices:
728 self.ReqFeatureIndex = feature_indices.index (self.ReqFeatureIndex)
729 else:
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400730 self.ReqFeatureIndex = 65535
731 self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400732 # Now map them.
733 self.FeatureIndex = [feature_indices.index (f) for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400734 self.FeatureCount = len (self.FeatureIndex)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400735 return bool (self.FeatureCount or self.ReqFeatureIndex != 65535)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400736
737@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
738def collect_features (self):
739 feature_indices = self.FeatureIndex[:]
740 if self.ReqFeatureIndex != 65535:
741 feature_indices.append (self.ReqFeatureIndex)
742 return unique_sorted (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400743
744@add_method(fontTools.ttLib.tables.otTables.Script)
745def subset_features (self, feature_indices):
746 if self.DefaultLangSys and not self.DefaultLangSys.subset_features (feature_indices):
747 self.DefaultLangSys = None
748 self.LangSysRecord = [l for l in self.LangSysRecord if l.LangSys.subset_features (feature_indices)]
749 self.LangSysCount = len (self.LangSysRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400750 return bool (self.LangSysCount or self.DefaultLangSys)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400751
752@add_method(fontTools.ttLib.tables.otTables.Script)
753def collect_features (self):
Behdad Esfahbod2307c8b2013-07-23 11:18:13 -0400754 feature_indices = [l.LangSys.collect_features () for l in self.LangSysRecord]
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400755 if self.DefaultLangSys:
756 feature_indices.append (self.DefaultLangSys.collect_features ())
757 return unique_sorted (sum (feature_indices, []))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400758
759@add_method(fontTools.ttLib.tables.otTables.ScriptList)
760def subset_features (self, feature_indices):
761 self.ScriptRecord = [s for s in self.ScriptRecord if s.Script.subset_features (feature_indices)]
762 self.ScriptCount = len (self.ScriptRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400763 return bool (self.ScriptCount)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400764
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400765@add_method(fontTools.ttLib.tables.otTables.ScriptList)
766def collect_features (self):
767 return unique_sorted (sum ((s.Script.collect_features () for s in self.ScriptRecord), []))
768
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400769@add_method(fontTools.ttLib.getTableClass('GSUB'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400770def closure_glyphs (self, s):
771 s.table = self.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400772 feature_indices = self.table.ScriptList.collect_features ()
773 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400774 while True:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400775 orig_glyphs = s.glyphs.copy ()
776 for i in lookup_indices:
777 if i >= self.table.LookupList.LookupCount: continue
778 if not self.table.LookupList.Lookup[i]: continue
779 self.table.LookupList.Lookup[i].closure_glyphs (s)
780 if orig_glyphs == s.glyphs:
781 break
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400782 del s.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400783
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400784@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400785def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400786 s.glyphs = s.glyphs_gsubed
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400787 lookup_indices = self.table.LookupList.subset_glyphs (s)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400788 self.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400789 self.prune_lookups ()
790 return True
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400791
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400792@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400793def subset_lookups (self, lookup_indices):
794 "Retrains specified lookups, then removes empty features, language systems, and scripts."
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400795 self.table.LookupList.subset_lookups (lookup_indices)
796 feature_indices = self.table.FeatureList.subset_lookups (lookup_indices)
797 self.table.ScriptList.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400798
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400799@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
800def prune_lookups (self):
801 "Remove unreferenced lookups"
802 feature_indices = self.table.ScriptList.collect_features ()
803 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
804 lookup_indices = self.table.LookupList.closure_lookups (lookup_indices)
805 self.subset_lookups (lookup_indices)
806
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400807@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
808def subset_feature_tags (self, feature_tags):
809 feature_indices = [i for (i,f) in enumerate (self.table.FeatureList.FeatureRecord) if f.FeatureTag in feature_tags]
810 self.table.FeatureList.subset_features (feature_indices)
811 self.table.ScriptList.subset_features (feature_indices)
812
813@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400814def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400815 if options.layout_features and '*' not in options.layout_features:
816 self.subset_feature_tags (options.layout_features)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400817 self.prune_lookups ()
818 return True
819
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400820@add_method(fontTools.ttLib.getTableClass('GDEF'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400821def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400822 glyphs = s.glyphs_gsubed
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400823 table = self.table
824 if table.LigCaretList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400825 indices = table.LigCaretList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400826 table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i] for i in indices]
827 table.LigCaretList.LigGlyphCount = len (table.LigCaretList.LigGlyph)
828 if not table.LigCaretList.LigGlyphCount:
829 table.LigCaretList = None
830 if table.MarkAttachClassDef:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400831 table.MarkAttachClassDef.classDefs = {g:v for g,v in table.MarkAttachClassDef.classDefs.iteritems() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400832 if not table.MarkAttachClassDef.classDefs:
833 table.MarkAttachClassDef = None
834 if table.GlyphClassDef:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400835 table.GlyphClassDef.classDefs = {g:v for g,v in table.GlyphClassDef.classDefs.iteritems() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400836 if not table.GlyphClassDef.classDefs:
837 table.GlyphClassDef = None
838 if table.AttachList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400839 indices = table.AttachList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400840 table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i] for i in indices]
841 table.AttachList.GlyphCount = len (table.AttachList.AttachPoint)
842 if not table.AttachList.GlyphCount:
843 table.AttachList = None
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400844 return bool (table.LigCaretList or table.MarkAttachClassDef or table.GlyphClassDef or table.AttachList)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400845
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400846@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbodd4e33a72013-07-24 18:51:05 -0400847def prune_pre_subset (self, options):
848 # Prune unknown kern table types
849 self.kernTables = [t for t in self.kernTables if hasattr (t, 'kernTable')]
850 return bool (self.kernTables)
851
852@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400853def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400854 glyphs = s.glyphs_gsubed
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400855 for t in self.kernTables:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400856 t.kernTable = {(a,b):v for ((a,b),v) in t.kernTable.iteritems() if a in glyphs and b in glyphs}
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400857 self.kernTables = [t for t in self.kernTables if t.kernTable]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400858 return bool (self.kernTables)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400859
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400860@add_method(fontTools.ttLib.getTableClass('hmtx'), fontTools.ttLib.getTableClass('vmtx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400861def subset_glyphs (self, s):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400862 self.metrics = {g:v for g,v in self.metrics.iteritems() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400863 return bool (self.metrics)
Behdad Esfahbodc7160442013-07-22 14:29:08 -0400864
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400865@add_method(fontTools.ttLib.getTableClass('hdmx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400866def subset_glyphs (self, s):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400867 self.hdmx = {sz:{g:v for g,v in l.iteritems() if g in s.glyphs} for (sz,l) in self.hdmx.iteritems()}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400868 return bool (self.hdmx)
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400869
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400870@add_method(fontTools.ttLib.getTableClass('VORG'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400871def subset_glyphs (self, s):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400872 self.VOriginRecords = {g:v for g,v in self.VOriginRecords.iteritems() if g in s.glyphs}
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400873 self.numVertOriginYMetrics = len (self.VOriginRecords)
874 return True # Never drop; has default metrics
875
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400876@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400877def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400878 if not options.glyph_names:
Behdad Esfahbod42648242013-07-23 12:56:06 -0400879 self.formatType = 3.0
880 return True
881
882@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400883def subset_glyphs (self, s):
Behdad Esfahbod42648242013-07-23 12:56:06 -0400884 self.extraNames = [] # This seems to do it
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -0400885 return True
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400886
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400887# Copied from _g_l_y_f.py
888ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes
889ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points
890ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true
891WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0
892NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!)
893MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one
894WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy
895WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11
896WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow
897USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph
898OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts
899SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple)
900UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS)
901
902@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
903def getComponentNamesFast (self, glyfTable):
904 if struct.unpack(">h", self.data[:2])[0] >= 0:
905 return [] # Not composite
906 data = self.data
907 i = 10
908 components = []
909 more = 1
910 while more:
911 flags, glyphID = struct.unpack(">HH", data[i:i+4])
912 i += 4
913 flags = int(flags)
914 components.append (glyfTable.getGlyphName (int (glyphID)))
915
916 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
917 else: i += 2
918 if flags & WE_HAVE_A_SCALE: i += 2
919 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
920 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
921 more = flags & MORE_COMPONENTS
922 return components
923
924@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
925def remapComponentsFast (self, indices):
926 if struct.unpack(">h", self.data[:2])[0] >= 0:
927 return # Not composite
928 data = bytearray (self.data)
929 i = 10
930 more = 1
931 while more:
932 flags = (data[i] << 8) | data[i+1]
933 glyphID = (data[i+2] << 8) | data[i+3]
934 # Remap
935 glyphID = indices.index (glyphID)
936 data[i+2] = glyphID >> 8
937 data[i+3] = glyphID & 0xFF
938 i += 4
939 flags = int(flags)
940
941 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
942 else: i += 2
943 if flags & WE_HAVE_A_SCALE: i += 2
944 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
945 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
946 more = flags & MORE_COMPONENTS
947 self.data = str (data)
948
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400949@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
950def dropInstructionsFast (self):
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400951 numContours = struct.unpack(">h", self.data[:2])[0]
952 data = bytearray (self.data)
953 i = 10
954 if numContours >= 0:
955 i += 2 * numContours # endPtsOfContours
956 instructionLen = (data[i] << 8) | data[i+1]
957 # Zero it
958 data[i] = data [i+1] = 0
959 i += 2
Behdad Esfahbod0fb69882013-07-24 17:25:35 -0400960 if instructionLen:
961 # Splice it out
962 data = data[:i] + data[i+instructionLen:]
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400963 else:
964 more = 1
965 while more:
966 flags = (data[i] << 8) | data[i+1]
967 # Turn instruction flag off
968 flags &= ~WE_HAVE_INSTRUCTIONS
969 data[i+0] = flags >> 8
970 data[i+1] = flags & 0xFF
971 i += 4
972 flags = int(flags)
973
974 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
975 else: i += 2
976 if flags & WE_HAVE_A_SCALE: i += 2
977 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
978 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
979 more = flags & MORE_COMPONENTS
980 # Cut off
981 data = data[:i]
982 if len(data) % 4:
983 # add pad bytes
984 nPadBytes = 4 - (len(data) % 4)
985 for i in range (nPadBytes):
986 data.append (0)
987 self.data = str (data)
988
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400989@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400990def closure_glyphs (self, s):
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400991 decompose = s.glyphs
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400992 # I don't know if component glyphs can be composite themselves.
993 # We handle them anyway.
994 while True:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400995 components = set ()
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400996 for g in decompose:
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400997 if g not in self.glyphs:
Behdad Esfahbodf8c20e42013-07-23 23:13:23 -0400998 continue
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400999 gl = self.glyphs[g]
1000 if hasattr (gl, "data"):
1001 for c in gl.getComponentNamesFast (self):
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001002 if c not in s.glyphs:
1003 components.add (c)
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001004 else:
1005 # TTX seems to expand gid0..3 always
1006 if gl.isComposite ():
1007 for c in gl.components:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001008 if c.glyphName not in s.glyphs:
1009 components.add (c.glyphName)
1010 components = set (c for c in components if c not in s.glyphs)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001011 if not components:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001012 break
1013 decompose = components
1014 s.glyphs.update (components)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001015
1016@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001017def subset_glyphs (self, s):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001018 self.glyphs = {g:v for g,v in self.glyphs.iteritems() if g in s.glyphs}
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001019 indices = [i for i,g in enumerate (self.glyphOrder) if g in s.glyphs]
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001020 for v in self.glyphs.itervalues():
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001021 if hasattr (v, "data"):
1022 v.remapComponentsFast (indices)
1023 else:
1024 pass # No need
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001025 self.glyphOrder = [g for g in self.glyphOrder if g in s.glyphs]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -04001026 return bool (self.glyphs)
Behdad Esfahbod861d9152013-07-22 16:47:24 -04001027
Behdad Esfahboded98c612013-07-23 12:37:41 -04001028@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -04001029def prune_post_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001030 if not options.hinting:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001031 for v in self.glyphs.itervalues():
Behdad Esfahbod6ec88542013-07-24 16:52:47 -04001032 if hasattr (v, "data"):
1033 v.dropInstructionsFast ()
1034 else:
1035 v.program = fontTools.ttLib.tables.ttProgram.Program()
1036 v.program.fromBytecode([])
Behdad Esfahboded98c612013-07-23 12:37:41 -04001037 return True
1038
Behdad Esfahbod2b677c82013-07-23 13:37:13 -04001039@add_method(fontTools.ttLib.getTableClass('CFF '))
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001040def prune_pre_subset (self, s):
Behdad Esfahbod4e721862013-08-13 16:24:45 -04001041 cff = self.cff
1042 # CFF table should have one font only
1043 cff.fontNames = cff.fontNames[:1]
1044 return bool (cff.fontNames)
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001045
1046@add_method(fontTools.ttLib.getTableClass('CFF '))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001047def subset_glyphs (self, s):
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001048 cff = self.cff
1049 for fontname in cff.keys():
1050 font = cff[fontname]
1051 cs = font.CharStrings
1052 if cs.charStringsAreIndexed:
1053 indices = [i for i,g in enumerate (font.charset) if g in s.glyphs]
1054 # Load all glyphs
1055 for g in font.charset:
1056 if g not in s.glyphs: continue
1057 cs.getItemAndSelector (g)
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001058 csi = cs.charStringsIndex
1059 csi.items = [csi.items[i] for i in indices]
1060 csi.offsets = [] # Don't need it; loaded all glyphs
Behdad Esfahbod31ebebe2013-08-13 16:02:33 -04001061 if hasattr (font, "FDSelect"):
Behdad Esfahbod8e3b8862013-08-13 16:02:18 -04001062 sel = font.FDSelect
1063 sel.format = None
1064 sel.gidArray = [font.FDSelect.gidArray[i] for i in indices]
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001065 cs.charStrings = {g:indices.index (v) for g,v in cs.charStrings.iteritems() if g in s.glyphs}
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001066 else:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001067 cs.charStrings = {g:v for g,v in cs.charStrings.iteritems() if g in s.glyphs}
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001068 font.charset = [g for g in font.charset if g in s.glyphs]
1069 font.numGlyphs = len (font.charset)
Behdad Esfahbod409286a2013-08-13 15:57:33 -04001070 return any (cff[fontname].numGlyphs for fontname in cff.keys())
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001071
1072@add_method(fontTools.ttLib.getTableClass('glyf'))
1073def prune_post_subset (self, options):
1074 if not options.hinting:
1075 pass # Drop hints
1076 return True
Behdad Esfahbod2b677c82013-07-23 13:37:13 -04001077
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001078@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001079def closure_glyphs (self, s):
1080 tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [1, 10]]
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001081 for u in s.unicodes_requested:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001082 found = False
1083 for table in tables:
1084 if u in table.cmap:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001085 s.glyphs.add (table.cmap[u])
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001086 found = True
1087 break
1088 if not found:
1089 s.log ("No glyph for Unicode value %s; skipping." % u)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001090
1091@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001092def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001093 if not options.legacy_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -04001094 # Drop non-Unicode / non-Symbol cmaps
1095 self.tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [0, 1, 10]]
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001096 if not options.symbol_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -04001097 self.tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [1, 10]]
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001098 # TODO Only keep one subtable?
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001099 # For now, drop format=0 which can't be subset_glyphs easily?
1100 self.tables = [t for t in self.tables if t.format != 0]
1101 return bool (self.tables)
1102
1103@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001104def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -04001105 s.glyphs = s.glyphs_cmaped
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001106 for t in self.tables:
Behdad Esfahbod9453a362013-07-22 16:21:24 -04001107 # For reasons I don't understand I need this here
1108 # to force decompilation of the cmap format 14.
1109 try:
1110 getattr (t, "asdf")
1111 except AttributeError:
1112 pass
Behdad Esfahbodb13d7902013-07-22 16:01:15 -04001113 if t.format == 14:
Behdad Esfahbod9453a362013-07-22 16:21:24 -04001114 # XXX We drop all the default-UVS mappings (g==None)
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001115 t.uvsDict = {v:[(u,g) for (u,g) in l if g in s.glyphs] for (v,l) in t.uvsDict.iteritems()}
1116 t.uvsDict = {v:l for (v,l) in t.uvsDict.iteritems() if l}
Behdad Esfahbodb13d7902013-07-22 16:01:15 -04001117 else:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001118 t.cmap = {u:g for (u,g) in t.cmap.iteritems() if g in s.glyphs_requested or u in s.unicodes_requested}
Behdad Esfahbodb13d7902013-07-22 16:01:15 -04001119 self.tables = [t for t in self.tables if (t.cmap if t.format != 14 else t.uvsDict)]
Behdad Esfahbod7e4bfc32013-07-22 18:47:32 -04001120 # XXX Convert formats when needed
Behdad Esfahbod2ac36302013-08-08 23:49:00 -04001121 # In particular, if we have a format=12 without non-BMP
1122 # characters, either drop format=12 one or convert it
1123 # to format=4 if there's not one.
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001124 return bool (self.tables)
1125
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001126@add_method(fontTools.ttLib.getTableClass('name'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -04001127def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001128 if '*' not in options.name_IDs:
1129 self.names = [n for n in self.names if n.nameID in options.name_IDs]
1130 if not options.name_legacy:
Behdad Esfahbod20faeb02013-07-23 13:19:03 -04001131 self.names = [n for n in self.names if n.platformID == 3 and n.platEncID == 1]
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001132 if '*' not in options.name_languages:
1133 self.names = [n for n in self.names if n.langID in options.name_languages]
Behdad Esfahbod20faeb02013-07-23 13:19:03 -04001134 return True # Retain even if empty
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001135
Behdad Esfahbod8c646f62013-07-22 15:06:23 -04001136
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -04001137# TODO OS/2 ulUnicodeRange / ulCodePageRange?
Behdad Esfahbodf71267b2013-07-23 12:59:13 -04001138# TODO Drop unneeded GSUB/GPOS Script/LangSys entries
Behdad Esfahbod398d3892013-07-23 15:29:40 -04001139# TODO Avoid recursing too much
Behdad Esfahbode94aa0e2013-07-23 13:22:04 -04001140# TODO Text direction considerations
1141# TODO Text script / language considerations
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001142# TODO Drop unknown tables? Using DefaultTable.prune?
Behdad Esfahbod8c4f7cc2013-07-24 17:58:29 -04001143# TODO Drop GPOS Device records if not hinting?
Behdad Esfahbod93e26362013-08-09 14:22:48 -04001144# TODO Move font name loading hack to Subsetter?
Behdad Esfahbod56ebd042013-07-22 13:02:24 -04001145
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001146
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001147class Subsetter:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001148
1149 class Options:
Behdad Esfahbod26d9ee72013-08-13 16:55:01 -04001150
1151 class UnknownOptionError (Exception):
1152 pass
1153
Behdad Esfahbod9eeeb4e2013-08-13 16:58:50 -04001154 drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'PCLT', 'LTSH']
1155 drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill'] # Graphite
1156 drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL'] # Color
1157 no_subset_tables_default = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2', 'loca', 'name', 'cvt ', 'fpgm', 'prep']
1158 hinting_tables_default = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
1159
1160 # Based on HarfBuzz shapers
1161 layout_features_groups = {
1162 # Default shaper
1163 'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
1164 'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
1165 'vertical': ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
1166 'ltr': ['ltra', 'ltrm'],
1167 'rtl': ['rtla', 'rtlm'],
1168 # Complex shapers
1169 'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3', 'cswh', 'mset'],
1170 'hangul': ['ljmo', 'vjmo', 'tjmo'],
1171 'tibetal': ['abvs', 'blws', 'abvm', 'blwm'],
1172 'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half', 'abvf', 'pstf', 'cfar', 'vatu', 'cjct',
1173 'init', 'pres', 'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
1174 }
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001175 layout_features_default = unique_sorted (sum (layout_features_groups.itervalues(), []))
Behdad Esfahbod9eeeb4e2013-08-13 16:58:50 -04001176
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001177 drop_tables = drop_tables_default
Behdad Esfahbode6fc8ca2013-08-13 12:25:31 -04001178 no_subset_tables = no_subset_tables_default
1179 hinting_tables = hinting_tables_default
Behdad Esfahbod9eeeb4e2013-08-13 16:58:50 -04001180 layout_features = layout_features_default
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001181 hinting = False
1182 glyph_names = False
1183 legacy_cmap = False
1184 symbol_cmap = False
1185 name_IDs = [1, 2] # Family and Style
1186 name_legacy = False
1187 name_languages = [0x0409] # English
1188 mandatory_glyphs = True # First four for TrueType, .notdef for CFF
1189 recalc_bboxes = False # Slows us down
1190
1191 def __init__ (self, **kwargs):
1192
1193 self.set (**kwargs)
1194
1195 def set (self, **kwargs):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001196 for k,v in kwargs.iteritems():
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001197 if not hasattr (self, k):
Behdad Esfahbod26d9ee72013-08-13 16:55:01 -04001198 raise self.UnknownOptionError ("Unknown option '%s'" % k)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001199 setattr (self, k, v)
1200
1201 def parse_opts (self, argv, ignore_unknown=False):
1202 ret = []
1203 opts = {}
1204 for a in argv:
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001205 orig_a = a
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001206 if not a.startswith ('--'):
1207 ret.append (a)
1208 continue
1209 a = a[2:]
1210 i = a.find ('=')
1211 if i == -1:
1212 if a.startswith ("no-"):
1213 k = a[3:]
1214 v = False
1215 else:
1216 k = a
1217 v = True
1218 else:
1219 k = a[:i]
1220 v = a[i+1:]
1221 k = k.replace ('-', '_')
1222 if not hasattr (self, k):
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001223 if ignore_unknown == True or k in ignore_unknown:
1224 ret.append (orig_a)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001225 continue
1226 else:
Behdad Esfahbod26d9ee72013-08-13 16:55:01 -04001227 raise self.UnknownOptionError ("Unknown option '%s'" % a)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001228
1229 ov = getattr (self, k)
1230 if isinstance (ov, bool):
1231 v = bool (v)
1232 elif isinstance (ov, int):
1233 v = int (v)
1234 elif isinstance (ov, list):
1235 v = v.split (',')
1236 v = [int (x, 0) if x[0] in range (10) else x for x in v]
1237
1238 opts[k] = v
1239 self.set (**opts)
1240
1241 return ret
1242
1243
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001244 def __init__ (self, options=None, log=None):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001245
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001246 if not log:
1247 log = Logger()
1248 if not options:
1249 options = Options()
1250
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001251 self.options = options
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001252 self.log = log
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001253 self.unicodes_requested = set ()
1254 self.glyphs_requested = set ()
Behdad Esfahboda7d22432013-08-13 12:47:48 -04001255 self.glyphs = set ()
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001256
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001257 def populate (self, glyphs=[], unicodes=[], text=""):
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001258 self.unicodes_requested.update (unicodes)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001259 if isinstance (text, str):
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001260 text = text.decode ("utf8")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001261 for u in text:
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001262 self.unicodes_requested.add (ord (u))
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001263 self.glyphs_requested.update (glyphs)
Behdad Esfahboda7d22432013-08-13 12:47:48 -04001264 self.glyphs.update (glyphs)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001265
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001266 def pre_prune (self, font):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001267
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001268 for tag in font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001269 if tag == 'GlyphOrder': continue
1270
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001271 if tag in self.options.drop_tables or \
Behdad Esfahbode6fc8ca2013-08-13 12:25:31 -04001272 (tag in self.options.hinting_tables and not self.options.hinting):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001273 self.log (tag, "dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001274 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001275 continue
1276
1277 clazz = fontTools.ttLib.getTableClass(tag)
1278
1279 if hasattr (clazz, 'prune_pre_subset'):
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001280 table = font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001281 retain = table.prune_pre_subset (self.options)
1282 self.log.lapse ("prune '%s'" % tag)
1283 if not retain:
1284 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001285 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001286 continue
1287 else:
1288 self.log (tag, "pruned")
1289
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001290 def closure_glyphs (self, font):
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001291
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001292 self.glyphs = self.glyphs_requested.copy ()
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001293
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001294 if 'cmap' in font:
1295 font['cmap'].closure_glyphs (self)
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001296 self.glyphs_cmaped = self.glyphs
1297
1298 if self.options.mandatory_glyphs:
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001299 if 'glyf' in font:
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001300 for i in range (4):
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001301 self.glyphs.add (font.getGlyphName (i))
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001302 self.log ("Added first four glyphs to subset")
1303 else:
1304 self.glyphs.add ('.notdef')
1305 self.log ("Added .notdef glyph to subset")
1306
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001307 if 'GSUB' in font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001308 self.log ("Closing glyph list over 'GSUB': %d glyphs before" % len (self.glyphs))
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001309 self.log.glyphs (self.glyphs, font=font)
1310 font['GSUB'].closure_glyphs (self)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001311 self.log ("Closed glyph list over 'GSUB': %d glyphs after" % len (self.glyphs))
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001312 self.log.glyphs (self.glyphs, font=font)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001313 self.log.lapse ("close glyph list over 'GSUB'")
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001314 self.glyphs_gsubed = self.glyphs.copy ()
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001315
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001316 if 'glyf' in font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001317 self.log ("Closing glyph list over 'glyf': %d glyphs before" % len (self.glyphs))
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001318 self.log.glyphs (self.glyphs, font=font)
1319 font['glyf'].closure_glyphs (self)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001320 self.log ("Closed glyph list over 'glyf': %d glyphs after" % len (self.glyphs))
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001321 self.log.glyphs (self.glyphs, font=font)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001322 self.log.lapse ("close glyph list over 'glyf'")
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001323 self.glyphs_glyfed = self.glyphs.copy ()
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001324
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001325 self.glyphs_all = self.glyphs.copy ()
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001326
1327 self.log ("Retaining %d glyphs: " % len (self.glyphs_all))
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001328
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001329 def subset_glyphs (self, font):
1330 for tag in font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001331 if tag == 'GlyphOrder': continue
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001332 clazz = fontTools.ttLib.getTableClass(tag)
1333
Behdad Esfahbode6fc8ca2013-08-13 12:25:31 -04001334 if tag in self.options.no_subset_tables:
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001335 self.log (tag, "subsetting not needed")
1336 elif hasattr (clazz, 'subset_glyphs'):
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001337 table = font[tag]
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -04001338 self.glyphs = self.glyphs_all
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001339 retain = table.subset_glyphs (self)
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001340 self.glyphs = self.glyphs_all
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001341 self.log.lapse ("subset '%s'" % tag)
1342 if not retain:
1343 self.log (tag, "subsetted to empty; dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001344 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001345 else:
1346 self.log (tag, "subsetted")
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001347 else:
Behdad Esfahbode6fc8ca2013-08-13 12:25:31 -04001348 self.log (tag, "NOT subset; don't know how to subset; dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001349 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001350
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001351 glyphOrder = font.getGlyphOrder()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001352 glyphOrder = [g for g in glyphOrder if g in self.glyphs_all]
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001353 font.setGlyphOrder (glyphOrder)
1354 font._buildReverseGlyphOrderDict ()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001355 self.log.lapse ("subset GlyphOrder")
1356
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001357 def post_prune (self, font):
1358 for tag in font.keys():
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001359 if tag == 'GlyphOrder': continue
1360 clazz = fontTools.ttLib.getTableClass(tag)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001361 if hasattr (clazz, 'prune_post_subset'):
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001362 table = font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001363 retain = table.prune_post_subset (self.options)
1364 self.log.lapse ("prune '%s'" % tag)
1365 if not retain:
1366 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001367 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001368 else:
1369 self.log (tag, "pruned")
1370
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001371 def subset (self, font):
Behdad Esfahbod756af492013-08-01 12:05:26 -04001372
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001373 font.recalcBBoxes = self.options.recalc_bboxes
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001374
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001375 self.pre_prune (font)
1376 self.closure_glyphs (font)
1377 self.subset_glyphs (font)
1378 self.post_prune (font)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001379
Behdad Esfahbod756af492013-08-01 12:05:26 -04001380
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001381import sys, time
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001382
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001383class Logger:
1384
1385 def __init__ (self, verbose=False, xml=False, timing=False):
1386 self.verbose = verbose
1387 self.xml = xml
1388 self.timing = timing
1389 self.last_time = self.start_time = time.time ()
1390
1391 def parse_opts (self, argv):
1392 argv = argv[:]
1393 for v in ['verbose', 'xml', 'timing']:
1394 if "--"+v in argv:
1395 setattr (self, v, True)
1396 argv.remove ("--"+v)
1397 return argv
1398
1399 def __call__ (self, *things):
1400 if not self.verbose:
1401 return
1402 print ' '.join (str (x) for x in things)
1403
1404 def lapse (self, *things):
1405 if not self.timing:
1406 return
1407 new_time = time.time ()
1408 print "Took %0.3fs to %s" % (new_time - self.last_time, ' '.join (str (x) for x in things))
1409 self.last_time = new_time
1410
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001411 def glyphs (self, glyphs, glyph_names=True, font=None):
1412 self ("Names: ", sorted (glyphs))
1413 if font:
Behdad Esfahboddb6d2e92013-08-13 12:42:12 -04001414 reverseGlyphMap = font.getReverseGlyphMap ()
1415 self ("Gids : ", sorted (reverseGlyphMap[g] for g in glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001416
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001417 def font (self, font, file=sys.stdout):
1418 if not self.xml:
1419 return
Behdad Esfahbod9a49ead2013-08-13 16:51:59 -04001420 import xmlWriter
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001421 writer = xmlWriter.XMLWriter (file)
1422 font.disassembleInstructions = False # Work around ttx bug
1423 for tag in font.keys():
1424 writer.begintag (tag)
1425 writer.newline ()
1426 font[tag].toXML(writer, font)
1427 writer.endtag (tag)
1428 writer.newline ()
1429
Behdad Esfahbodf6b668e2013-08-13 12:20:59 -04001430
1431def load_font (fontfile, dont_load_glyph_names=False):
1432
1433 # TODO Option for ignoreDecompileErrors?
1434
1435 font = fontTools.ttx.TTFont (fontfile)
1436
1437 # Hack:
1438 #
1439 # If we don't need glyph names, change 'post' class to not try to
1440 # load them. It avoid lots of headache with broken fonts as well
1441 # as loading time.
1442 #
1443 # Ideally ttLib should provide a way to ask it to skip loading
1444 # glyph names. But it currently doesn't provide such a thing.
1445 #
1446 if dont_load_glyph_names:
1447 post = fontTools.ttLib.getTableClass('post')
1448 saved = post.decode_format_2_0
1449 post.decode_format_2_0 = post.decode_format_3_0
1450 f = font['post']
1451 if f.formatType == 2.0:
1452 f.formatType = 3.0
1453 post.decode_format_2_0 = saved
1454
1455 return font
1456
1457
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001458def main (args):
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001459
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001460 log = Logger ()
1461 args = log.parse_opts (args)
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001462
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001463 options = Subsetter.Options ()
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001464 args = options.parse_opts (args, ignore_unknown=['text'])
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001465
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001466 if len (args) < 2:
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001467 print >>sys.stderr, "usage: pyotlss.py font-file glyph..."
1468 sys.exit (1)
1469
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001470 fontfile = args[0]
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001471 args = args[1:]
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001472
Behdad Esfahbodf6b668e2013-08-13 12:20:59 -04001473 dont_load_glyph_names = not options.glyph_names and \
1474 all (any (g.startswith (p) \
1475 for p in ['gid', 'glyph', 'uni', 'U+']) \
1476 for g in args)
1477
1478 font = load_font (fontfile, dont_load_glyph_names=dont_load_glyph_names)
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001479 subsetter = Subsetter (options=options, log=log)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001480 log.lapse ("load font")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001481
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001482 names = font.getGlyphNames()
1483 log.lapse ("loading glyph names")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001484
1485 glyphs = []
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001486 unicodes = []
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001487 text = ""
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001488 for g in args:
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001489 if g in names:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001490 glyphs.append (g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001491 continue
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001492 if g.startswith ('--text='):
1493 text += g[7:]
1494 continue
Behdad Esfahbod9ae5d282013-08-08 21:18:17 -04001495 if g.startswith ('uni') or g.startswith ('U+'):
1496 if g.startswith ('uni') and len (g) > 3:
1497 g = g[3:]
1498 elif g.startswith ('U+') and len (g) > 2:
1499 g = g[2:]
1500 u = int (g, 16)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001501 unicodes.append (u)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001502 continue
1503 if g.startswith ('gid') or g.startswith ('glyph'):
1504 if g.startswith ('gid') and len (g) > 3:
1505 g = g[3:]
1506 elif g.startswith ('glyph') and len (g) > 5:
1507 g = g[5:]
1508 try:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001509 glyphs.append (font.getGlyphName (int (g), requireReal=1))
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001510 except ValueError:
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001511 raise Exception ("Invalid glyph identifier: %s" % g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001512 continue
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001513 raise Exception ("Invalid glyph identifier: %s" % g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001514 log.lapse ("compile glyph list")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001515 log ("Unicodes:", unicodes)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001516 log ("Glyphs:", glyphs)
1517
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001518 subsetter.populate (glyphs=glyphs, unicodes=unicodes, text=text)
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001519 subsetter.subset (font)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -04001520
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001521 font.save (fontfile + '.subset')
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001522 log.lapse ("compile and save font")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001523
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001524 log.last_time = log.start_time
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001525 log.lapse ("make one with everything (TOTAL TIME)")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001526
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001527 log.font (font)
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001528
1529if __name__ == '__main__':
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001530 main (sys.argv[1:])