blob: 8b1e98028ea385fe98cc63d4a1d79f95df0f2063 [file] [log] [blame]
Behdad Esfahbod54660612013-07-21 18:16:55 -04001#!/usr/bin/python
2
3# Python OpenType Layout Subsetter
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04004#
5# Copyright 2013 Google, Inc. All Rights Reserved.
6#
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18#
19# Google Author(s): Behdad Esfahbod
20#
Behdad Esfahbod54660612013-07-21 18:16:55 -040021
Behdad Esfahbodfa3bc5e2013-07-24 14:37:58 -040022# Try running on PyPy
23try:
24 import numpypy
25except ImportError:
26 pass
27
Behdad Esfahbod54660612013-07-21 18:16:55 -040028import fontTools.ttx
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -040029import struct
Behdad Esfahbod54660612013-07-21 18:16:55 -040030
Behdad Esfahbod54660612013-07-21 18:16:55 -040031
Behdad Esfahbod02b92062013-07-21 18:40:59 -040032def add_method (*clazzes):
Behdad Esfahbod54660612013-07-21 18:16:55 -040033 def wrapper(method):
Behdad Esfahbod02b92062013-07-21 18:40:59 -040034 for clazz in clazzes:
Behdad Esfahbodc0d59592013-07-24 14:41:47 -040035 assert clazz.__name__ != 'DefaultTable', 'Oops, table class not found.'
Behdad Esfahbod02b92062013-07-21 18:40:59 -040036 setattr (clazz, method.func_name, method)
Behdad Esfahbod54660612013-07-21 18:16:55 -040037 return wrapper
38
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040039def unique_sorted (l):
Behdad Esfahbod2d9a0962013-07-31 13:33:31 -040040 return sorted (set (l))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040041
42
Behdad Esfahbod54660612013-07-21 18:16:55 -040043@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040044def intersect (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -040045 "Returns ascending list of matching coverage values."
46 return [i for (i,g) in enumerate (self.glyphs) if g in glyphs]
47
48@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040049def subset (self, glyphs):
Behdad Esfahbodd821ea02013-07-23 10:50:43 -040050 "Returns ascending list of remaining coverage values."
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040051 indices = self.intersect (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -040052 self.glyphs = [g for g in self.glyphs if g in glyphs]
53 return indices
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040054
Behdad Esfahbod54660612013-07-21 18:16:55 -040055@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040056def intersect (self, glyphs):
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040057 "Returns ascending list of matching class values."
58 return unique_sorted (v for g,v in self.classDefs.items() if g in glyphs)
59
60@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040061def intersects_class (self, glyphs, klass):
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040062 "Returns true if any of glyphs has requested class."
63 return any (g in glyphs for g,v in self.classDefs.items() if v == klass)
64
65@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040066def subset (self, glyphs, remap=False):
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -040067 "Returns ascending list of remaining classes."
Behdad Esfahbod54660612013-07-21 18:16:55 -040068 self.classDefs = {g:v for g,v in self.classDefs.items() if g in glyphs}
Behdad Esfahbodde71dca2013-07-24 12:40:54 -040069 indices = unique_sorted (self.classDefs.values ())
70 if remap:
71 self.remap (indices)
72 return indices
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -040073
74@add_method(fontTools.ttLib.tables.otTables.ClassDef)
75def remap (self, class_map):
76 "Remaps classes."
77 self.classDefs = {g:class_map.index (v) for g,v in self.classDefs.items()}
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040078
Behdad Esfahbod54660612013-07-21 18:16:55 -040079@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod610b0552013-07-23 14:52:18 -040080def closure_glyphs (self, glyphs, table):
81 if self.Format in [1, 2]:
82 return [v for g,v in self.mapping.items() if g in glyphs]
83 else:
84 assert 0, "unknown format: %s" % self.Format
85
86@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -040087def subset_glyphs (self, glyphs):
Behdad Esfahbod54660612013-07-21 18:16:55 -040088 if self.Format in [1, 2]:
89 self.mapping = {g:v for g,v in self.mapping.items() if g in glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -040090 return bool (self.mapping)
Behdad Esfahbod54660612013-07-21 18:16:55 -040091 else:
92 assert 0, "unknown format: %s" % self.Format
93
94@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod610b0552013-07-23 14:52:18 -040095def closure_glyphs (self, glyphs, table):
96 if self.Format == 1:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040097 indices = self.Coverage.intersect (glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -040098 return sum ((self.Sequence[i].Substitute for i in indices), [])
99 else:
100 assert 0, "unknown format: %s" % self.Format
101
102@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400103def subset_glyphs (self, glyphs):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400104 if self.Format == 1:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400105 indices = self.Coverage.subset (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400106 self.Sequence = [self.Sequence[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400107 self.SequenceCount = len (self.Sequence)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400108 return bool (self.SequenceCount)
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.AlternateSubst)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400113def closure_glyphs (self, glyphs, table):
114 if self.Format == 1:
115 return sum ((v for g,v in self.alternates.items() if g in glyphs), [])
116 else:
117 assert 0, "unknown format: %s" % self.Format
118
119@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400120def subset_glyphs (self, glyphs):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400121 if self.Format == 1:
122 self.alternates = {g:v for g,v in self.alternates.items() if g in glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400123 return bool (self.alternates)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400124 else:
125 assert 0, "unknown format: %s" % self.Format
126
127@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400128def closure_glyphs (self, glyphs, table):
129 if self.Format == 1:
130 return sum (([seq.LigGlyph for seq in seqs if all(c in glyphs for c in seq.Component)]
Behdad Esfahbodaf2117f2013-07-24 13:43:44 -0400131 for g,seqs in self.ligatures.items() if g in glyphs), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400132 else:
133 assert 0, "unknown format: %s" % self.Format
134
135@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400136def subset_glyphs (self, glyphs):
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400137 if self.Format == 1:
138 self.ligatures = {g:v for g,v in self.ligatures.items() if g in glyphs}
139 self.ligatures = {g:[seq for seq in seqs if all(c in glyphs for c in seq.Component)]
140 for g,seqs in self.ligatures.items()}
141 self.ligatures = {g:v for g,v in self.ligatures.items() if v}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400142 return bool (self.ligatures)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400143 else:
144 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400145
Behdad Esfahbod54660612013-07-21 18:16:55 -0400146@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400147def closure_glyphs (self, glyphs, table):
148 if self.Format == 1:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400149 indices = self.Coverage.intersect (glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400150 if not indices or \
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400151 not all (c.intersect (glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400152 return []
153 return [self.Substitute[i] for i in indices]
154 else:
155 assert 0, "unknown format: %s" % self.Format
156
157@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400158def subset_glyphs (self, glyphs):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400159 if self.Format == 1:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400160 indices = self.Coverage.subset (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400161 self.Substitute = [self.Substitute[i] for i in indices]
162 self.GlyphCount = len (self.Substitute)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400163 return bool (self.GlyphCount and all (c.subset (glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400164 else:
165 assert 0, "unknown format: %s" % self.Format
166
167@add_method(fontTools.ttLib.tables.otTables.SinglePos)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400168def subset_glyphs (self, glyphs):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400169 if self.Format == 1:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400170 return len (self.Coverage.subset (glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400171 elif self.Format == 2:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400172 indices = self.Coverage.subset (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400173 self.Value = [self.Value[i] for i in indices]
174 self.ValueCount = len (self.Value)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400175 return bool (self.ValueCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400176 else:
177 assert 0, "unknown format: %s" % self.Format
178
179@add_method(fontTools.ttLib.tables.otTables.PairPos)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400180def subset_glyphs (self, glyphs):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400181 if self.Format == 1:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400182 indices = self.Coverage.subset (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400183 self.PairSet = [self.PairSet[i] for i in indices]
184 for p in self.PairSet:
185 p.PairValueRecord = [r for r in p.PairValueRecord if r.SecondGlyph in glyphs]
186 p.PairValueCount = len (p.PairValueRecord)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400187 self.PairSet = [p for p in self.PairSet if p.PairValueCount]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400188 self.PairSetCount = len (self.PairSet)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400189 return bool (self.PairSetCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400190 elif self.Format == 2:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400191 class1_map = self.ClassDef1.subset (glyphs, remap=True)
192 class2_map = self.ClassDef2.subset (glyphs, remap=True)
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -0400193 self.Class1Record = [self.Class1Record[i] for i in class1_map]
194 for c in self.Class1Record:
195 c.Class2Record = [c.Class2Record[i] for i in class2_map]
196 self.Class1Count = len (class1_map)
197 self.Class2Count = len (class2_map)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400198 return bool (self.Class1Count and self.Class2Count and self.Coverage.subset (glyphs))
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.CursivePos)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400203def subset_glyphs (self, glyphs):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400204 if self.Format == 1:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400205 indices = self.Coverage.subset (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400206 self.EntryExitRecord = [self.EntryExitRecord[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400207 self.EntryExitCount = len (self.EntryExitRecord)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400208 return bool (self.EntryExitCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400209 else:
210 assert 0, "unknown format: %s" % self.Format
211
212@add_method(fontTools.ttLib.tables.otTables.MarkBasePos)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400213def subset_glyphs (self, glyphs):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400214 if self.Format == 1:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400215 mark_indices = self.MarkCoverage.subset (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400216 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
217 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400218 base_indices = self.BaseCoverage.subset (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400219 self.BaseArray.BaseRecord = [self.BaseArray.BaseRecord[i] for i in base_indices]
220 self.BaseArray.BaseCount = len (self.BaseArray.BaseRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400221 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400222 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400223 self.ClassCount = len (class_indices)
224 for m in self.MarkArray.MarkRecord:
225 m.Class = class_indices.index (m.Class)
226 for b in self.BaseArray.BaseRecord:
227 b.BaseAnchor = [b.BaseAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400228 return bool (self.ClassCount and self.MarkArray.MarkCount and self.BaseArray.BaseCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400229 else:
230 assert 0, "unknown format: %s" % self.Format
231
232@add_method(fontTools.ttLib.tables.otTables.MarkLigPos)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400233def subset_glyphs (self, glyphs):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400234 if self.Format == 1:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400235 mark_indices = self.MarkCoverage.subset (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400236 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
237 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400238 ligature_indices = self.LigatureCoverage.subset (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400239 self.LigatureArray.LigatureAttach = [self.LigatureArray.LigatureAttach[i] for i in ligature_indices]
240 self.LigatureArray.LigatureCount = len (self.LigatureArray.LigatureAttach)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400241 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400242 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400243 self.ClassCount = len (class_indices)
244 for m in self.MarkArray.MarkRecord:
245 m.Class = class_indices.index (m.Class)
246 for l in self.LigatureArray.LigatureAttach:
247 for c in l.ComponentRecord:
248 c.LigatureAnchor = [c.LigatureAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400249 return bool (self.ClassCount and self.MarkArray.MarkCount and self.LigatureArray.LigatureCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400250 else:
251 assert 0, "unknown format: %s" % self.Format
252
253@add_method(fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400254def subset_glyphs (self, glyphs):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400255 if self.Format == 1:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400256 mark1_indices = self.Mark1Coverage.subset (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400257 self.Mark1Array.MarkRecord = [self.Mark1Array.MarkRecord[i] for i in mark1_indices]
258 self.Mark1Array.MarkCount = len (self.Mark1Array.MarkRecord)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400259 mark2_indices = self.Mark2Coverage.subset (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400260 self.Mark2Array.Mark2Record = [self.Mark2Array.Mark2Record[i] for i in mark2_indices]
261 self.Mark2Array.MarkCount = len (self.Mark2Array.Mark2Record)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400262 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400263 class_indices = unique_sorted (v.Class for v in self.Mark1Array.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400264 self.ClassCount = len (class_indices)
265 for m in self.Mark1Array.MarkRecord:
266 m.Class = class_indices.index (m.Class)
267 for b in self.Mark2Array.Mark2Record:
268 b.Mark2Anchor = [b.Mark2Anchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400269 return bool (self.ClassCount and self.Mark1Array.MarkCount and self.Mark2Array.MarkCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400270 else:
271 assert 0, "unknown format: %s" % self.Format
272
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400273@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
274 fontTools.ttLib.tables.otTables.MultipleSubst,
275 fontTools.ttLib.tables.otTables.AlternateSubst,
276 fontTools.ttLib.tables.otTables.LigatureSubst,
277 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
278 fontTools.ttLib.tables.otTables.SinglePos,
279 fontTools.ttLib.tables.otTables.PairPos,
280 fontTools.ttLib.tables.otTables.CursivePos,
281 fontTools.ttLib.tables.otTables.MarkBasePos,
282 fontTools.ttLib.tables.otTables.MarkLigPos,
283 fontTools.ttLib.tables.otTables.MarkMarkPos)
284def subset_lookups (self, lookup_indices):
285 pass
286
287@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
288 fontTools.ttLib.tables.otTables.MultipleSubst,
289 fontTools.ttLib.tables.otTables.AlternateSubst,
290 fontTools.ttLib.tables.otTables.LigatureSubst,
291 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
292 fontTools.ttLib.tables.otTables.SinglePos,
293 fontTools.ttLib.tables.otTables.PairPos,
294 fontTools.ttLib.tables.otTables.CursivePos,
295 fontTools.ttLib.tables.otTables.MarkBasePos,
296 fontTools.ttLib.tables.otTables.MarkLigPos,
297 fontTools.ttLib.tables.otTables.MarkMarkPos)
298def collect_lookups (self):
299 return []
300
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400301@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
302 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
303def __classify_context (self):
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400304
305 class ContextHelper:
306 def __init__ (self, klass, Format):
307 if klass.__name__.endswith ('Subst'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400308 Typ = 'Sub'
309 Type = 'Subst'
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400310 else:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400311 Typ = 'Pos'
312 Type = 'Pos'
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400313 if klass.__name__.startswith ('Chain'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400314 Chain = 'Chain'
315 else:
316 Chain = ''
317 ChainTyp = Chain+Typ
318
319 self.Typ = Typ
320 self.Type = Type
321 self.Chain = Chain
322 self.ChainTyp = ChainTyp
323
324 self.LookupRecord = Type+'LookupRecord'
325
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400326 if Format == 1:
327 ContextData = None
328 ChainContextData = None
329 RuleData = lambda r: r.Input
330 ChainRuleData = lambda r: r.Backtrack + r.Input + r.LookAhead
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400331 SetRuleData = None
332 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400333 elif Format == 2:
Behdad Esfahbode3f20732013-07-24 11:26:43 -0400334 ContextData = lambda r: (r.ClassDef,)
335 ChainContextData = lambda r: (r.LookAheadClassDef, r.InputClassDef, r.BacktrackClassDef)
336 RuleData = lambda r: (r.Class,)
337 ChainRuleData = lambda r: (r.LookAhead, r.Input, r.Backtrack)
338 def SetRuleData (r, d): (r.Class,) = d
339 def ChainSetRuleData (r, d): (r.LookAhead, r.Input, r.Backtrack) = d
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400340 elif Format == 3:
341 ContextData = None
342 ChainContextData = None
343 RuleData = lambda r: r.Coverage
344 ChainRuleData = lambda r: r.LookAheadCoverage + r.InputCoverage + r.BacktrackCoverage
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400345 SetRuleData = None
346 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400347 else:
348 assert 0, "unknown format: %s" % Format
349
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400350 if Chain:
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400351 self.ContextData = ChainContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400352 self.RuleData = ChainRuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400353 self.SetRuleData = ChainSetRuleData
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400354 else:
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400355 self.ContextData = ContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400356 self.RuleData = RuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400357 self.SetRuleData = SetRuleData
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400358
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400359 if Format == 1:
360 self.Rule = ChainTyp+'Rule'
361 self.RuleCount = ChainTyp+'RuleCount'
362 self.RuleSet = ChainTyp+'RuleSet'
363 self.RuleSetCount = ChainTyp+'RuleSetCount'
364 elif Format == 2:
365 self.Rule = ChainTyp+'ClassRule'
366 self.RuleCount = ChainTyp+'ClassRuleCount'
367 self.RuleSet = ChainTyp+'ClassSet'
368 self.RuleSetCount = ChainTyp+'ClassSetCount'
Behdad Esfahbod89987002013-07-23 23:07:42 -0400369
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400370 self.ClassDef = 'InputClassDef' if Chain else 'ClassDef'
Behdad Esfahbod27108392013-07-23 16:40:47 -0400371
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400372 if self.Format not in [1, 2, 3]:
373 return None # Don't shoot the messenger; let it go
374 if not hasattr (self.__class__, "__ContextHelpers"):
375 self.__class__.__ContextHelpers = {}
376 if self.Format not in self.__class__.__ContextHelpers:
377 self.__class__.__ContextHelpers[self.Format] = ContextHelper (self.__class__, self.Format)
378 return self.__class__.__ContextHelpers[self.Format]
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400379
Behdad Esfahbodf2b6d9c2013-07-23 17:31:54 -0400380@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst)
Behdad Esfahbod00776972013-07-23 15:33:00 -0400381def closure_glyphs (self, glyphs, table):
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400382 c = self.__classify_context ()
383
Behdad Esfahbod00776972013-07-23 15:33:00 -0400384 if self.Format == 1:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400385 indices = self.Coverage.intersect (glyphs)
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400386 rss = getattr (self, c.RuleSet)
387 return sum ((table.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs (glyphs, table) \
388 for i in indices \
389 for r in getattr (rss[i], c.Rule) \
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400390 if r and all (g in glyphs for g in c.RuleData (r)) \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400391 for ll in getattr (r, c.LookupRecord) if ll \
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400392 ), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400393 elif self.Format == 2:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400394 if not self.Coverage.intersect (glyphs):
Behdad Esfahbod31084302013-07-23 22:22:38 -0400395 return []
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400396 indices = getattr (self, c.ClassDef).intersect (glyphs)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400397 rss = getattr (self, c.RuleSet)
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400398 return sum ((table.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs (glyphs, table) \
399 for i in indices \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400400 for r in getattr (rss[i], c.Rule) \
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400401 if r and all (cd.intersects_class (glyphs, k) \
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400402 for cd,k in zip (c.ContextData (self), c.RuleData (r))) \
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400403 for ll in getattr (r, c.LookupRecord) if ll \
404 ), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400405 elif self.Format == 3:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400406 if not all (x.intersect (glyphs) for x in c.RuleData (self)):
Behdad Esfahbod00776972013-07-23 15:33:00 -0400407 return []
408 return sum ((table.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs (glyphs, table) \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400409 for ll in getattr (self, c.LookupRecord) if ll), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400410 else:
411 assert 0, "unknown format: %s" % self.Format
412
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400413@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ContextPos,
414 fontTools.ttLib.tables.otTables.ChainContextSubst, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400415def subset_glyphs (self, glyphs):
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400416 c = self.__classify_context ()
417
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400418 if self.Format == 1:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400419 indices = self.Coverage.subset (glyphs)
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400420 rss = getattr (self, c.RuleSet)
421 rss = [rss[i] for i in indices]
422 for rs in rss:
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400423 if rs:
424 ss = getattr (rs, c.Rule)
425 ss = [r for r in ss \
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400426 if r and all (g in glyphs for g in c.RuleData (r))]
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400427 setattr (rs, c.Rule, ss)
428 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400429 # Prune empty subrulesets
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400430 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400431 setattr (self, c.RuleSet, rss)
432 setattr (self, c.RuleSetCount, len (rss))
433 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400434 elif self.Format == 2:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400435 if not self.Coverage.subset (glyphs):
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400436 return False
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400437 indices = getattr (self, c.ClassDef).intersect (glyphs)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400438 rss = getattr (self, c.RuleSet)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400439 rss = [rss[i] for i in indices]
440 ContextData = c.ContextData (self)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400441 klass_maps = [x.subset (glyphs, remap=True) for x in ContextData]
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400442 for rs in rss:
443 if rs:
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400444 ss = getattr (rs, c.Rule)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400445 ss = [r for r in ss \
446 if r and all (k in klass_map \
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400447 for klass_map,k in zip (klass_maps, c.RuleData (r)))]
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400448 setattr (rs, c.Rule, ss)
449 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400450
451 # Remap rule classes
452 for r in ss:
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400453 c.SetRuleData (r, (klass_map.index (k) \
454 for klassmap,k in zip (klass_maps, c.RuleData (r))))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400455 # Prune empty subrulesets
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400456 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
457 setattr (self, c.RuleSet, rss)
458 setattr (self, c.RuleSetCount, len (rss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400459 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400460 elif self.Format == 3:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400461 return all (x.subset (glyphs) for x in c.RuleData (self))
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400462 else:
463 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400464
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400465@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
466 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400467def subset_lookups (self, lookup_indices):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400468 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400469
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400470 if self.Format in [1, 2]:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400471 for rs in getattr (self, c.RuleSet):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400472 if rs:
473 for r in getattr (rs, c.Rule):
474 if r:
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400475 setattr (r, c.LookupRecord, [ll for ll in getattr (r, c.LookupRecord) if ll \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400476 if ll.LookupListIndex in lookup_indices])
477 for ll in getattr (r, c.LookupRecord):
478 if ll:
479 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400480 elif self.Format == 3:
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400481 setattr (self, c.LookupRecord, [ll for ll in getattr (self, c.LookupRecord) if ll \
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400482 if ll.LookupListIndex in lookup_indices])
483 for ll in getattr (self, c.LookupRecord):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400484 if ll:
485 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400486 else:
487 assert 0, "unknown format: %s" % self.Format
488
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400489@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
490 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400491def collect_lookups (self):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400492 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400493
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400494 if self.Format in [1, 2]:
Behdad Esfahbod27108392013-07-23 16:40:47 -0400495 return [ll.LookupListIndex \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400496 for rs in getattr (self, c.RuleSet) if rs \
497 for r in getattr (rs, c.Rule) if r \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400498 for ll in getattr (r, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400499 elif self.Format == 3:
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400500 return [ll.LookupListIndex \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400501 for ll in getattr (self, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400502 else:
503 assert 0, "unknown format: %s" % self.Format
504
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400505@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
506def closure_glyphs (self, glyphs, table):
507 if self.Format == 1:
508 return self.ExtSubTable.closure_glyphs (glyphs, table)
509 else:
510 assert 0, "unknown format: %s" % self.Format
511
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400512@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400513def subset_glyphs (self, glyphs):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400514 if self.Format == 1:
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400515 return self.ExtSubTable.subset_glyphs (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400516 else:
517 assert 0, "unknown format: %s" % self.Format
518
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400519@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
520def subset_lookups (self, lookup_indices):
521 if self.Format == 1:
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400522 return self.ExtSubTable.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400523 else:
524 assert 0, "unknown format: %s" % self.Format
525
526@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
527def collect_lookups (self):
528 if self.Format == 1:
529 return self.ExtSubTable.collect_lookups ()
530 else:
531 assert 0, "unknown format: %s" % self.Format
532
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400533@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400534def closure_glyphs (self, glyphs, table):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400535 return sum ((s.closure_glyphs (glyphs, table) for s in self.SubTable if s), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400536
537@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400538def subset_glyphs (self, glyphs):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400539 self.SubTable = [s for s in self.SubTable if s and s.subset_glyphs (glyphs)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400540 self.SubTableCount = len (self.SubTable)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400541 return bool (self.SubTableCount)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400542
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400543@add_method(fontTools.ttLib.tables.otTables.Lookup)
544def subset_lookups (self, lookup_indices):
545 for s in self.SubTable:
546 s.subset_lookups (lookup_indices)
547
548@add_method(fontTools.ttLib.tables.otTables.Lookup)
549def collect_lookups (self):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400550 return unique_sorted (sum ((s.collect_lookups () for s in self.SubTable if s), []))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400551
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400552@add_method(fontTools.ttLib.tables.otTables.LookupList)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400553def subset_glyphs (self, glyphs):
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400554 "Returns the indices of nonempty lookups."
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400555 return [i for (i,l) in enumerate (self.Lookup) if l and l.subset_glyphs (glyphs)]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400556
557@add_method(fontTools.ttLib.tables.otTables.LookupList)
558def subset_lookups (self, lookup_indices):
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400559 self.Lookup = [self.Lookup[i] for i in lookup_indices if i < self.LookupCount]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400560 self.LookupCount = len (self.Lookup)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400561 for l in self.Lookup:
562 l.subset_lookups (lookup_indices)
563
564@add_method(fontTools.ttLib.tables.otTables.LookupList)
565def closure_lookups (self, lookup_indices):
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400566 lookup_indices = unique_sorted (lookup_indices)
567 recurse = lookup_indices
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400568 while True:
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400569 recurse_lookups = sum ((self.Lookup[i].collect_lookups () for i in recurse if i < self.LookupCount), [])
570 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 -0400571 if not recurse_lookups:
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400572 return unique_sorted (lookup_indices)
573 recurse_lookups = unique_sorted (recurse_lookups)
574 lookup_indices.extend (recurse_lookups)
575 recurse = recurse_lookups
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400576
577@add_method(fontTools.ttLib.tables.otTables.Feature)
578def subset_lookups (self, lookup_indices):
579 self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices]
580 # Now map them.
581 self.LookupListIndex = [lookup_indices.index (l) for l in self.LookupListIndex]
582 self.LookupCount = len (self.LookupListIndex)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400583 return self.LookupCount
Behdad Esfahbod54660612013-07-21 18:16:55 -0400584
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400585@add_method(fontTools.ttLib.tables.otTables.Feature)
586def collect_lookups (self):
587 return self.LookupListIndex[:]
588
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400589@add_method(fontTools.ttLib.tables.otTables.FeatureList)
590def subset_lookups (self, lookup_indices):
591 "Returns the indices of nonempty features."
592 feature_indices = [i for (i,f) in enumerate (self.FeatureRecord) if f.Feature.subset_lookups (lookup_indices)]
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400593 self.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400594 return feature_indices
595
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400596@add_method(fontTools.ttLib.tables.otTables.FeatureList)
597def collect_lookups (self, feature_indices):
598 return unique_sorted (sum ((self.FeatureRecord[i].Feature.collect_lookups () for i in feature_indices
599 if i < self.FeatureCount), []))
600
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400601@add_method(fontTools.ttLib.tables.otTables.FeatureList)
602def subset_features (self, feature_indices):
603 self.FeatureRecord = [self.FeatureRecord[i] for i in feature_indices]
604 self.FeatureCount = len (self.FeatureRecord)
605 return bool (self.FeatureCount)
606
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400607@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
608def subset_features (self, feature_indices):
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400609 if self.ReqFeatureIndex in feature_indices:
610 self.ReqFeatureIndex = feature_indices.index (self.ReqFeatureIndex)
611 else:
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400612 self.ReqFeatureIndex = 65535
613 self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400614 # Now map them.
615 self.FeatureIndex = [feature_indices.index (f) for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400616 self.FeatureCount = len (self.FeatureIndex)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400617 return bool (self.FeatureCount or self.ReqFeatureIndex != 65535)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400618
619@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
620def collect_features (self):
621 feature_indices = self.FeatureIndex[:]
622 if self.ReqFeatureIndex != 65535:
623 feature_indices.append (self.ReqFeatureIndex)
624 return unique_sorted (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400625
626@add_method(fontTools.ttLib.tables.otTables.Script)
627def subset_features (self, feature_indices):
628 if self.DefaultLangSys and not self.DefaultLangSys.subset_features (feature_indices):
629 self.DefaultLangSys = None
630 self.LangSysRecord = [l for l in self.LangSysRecord if l.LangSys.subset_features (feature_indices)]
631 self.LangSysCount = len (self.LangSysRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400632 return bool (self.LangSysCount or self.DefaultLangSys)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400633
634@add_method(fontTools.ttLib.tables.otTables.Script)
635def collect_features (self):
Behdad Esfahbod2307c8b2013-07-23 11:18:13 -0400636 feature_indices = [l.LangSys.collect_features () for l in self.LangSysRecord]
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400637 if self.DefaultLangSys:
638 feature_indices.append (self.DefaultLangSys.collect_features ())
639 return unique_sorted (sum (feature_indices, []))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400640
641@add_method(fontTools.ttLib.tables.otTables.ScriptList)
642def subset_features (self, feature_indices):
643 self.ScriptRecord = [s for s in self.ScriptRecord if s.Script.subset_features (feature_indices)]
644 self.ScriptCount = len (self.ScriptRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400645 return bool (self.ScriptCount)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400646
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400647@add_method(fontTools.ttLib.tables.otTables.ScriptList)
648def collect_features (self):
649 return unique_sorted (sum ((s.Script.collect_features () for s in self.ScriptRecord), []))
650
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400651@add_method(fontTools.ttLib.getTableClass('GSUB'))
652def closure_glyphs (self, glyphs):
653 feature_indices = self.table.ScriptList.collect_features ()
654 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
655 glyphs = unique_sorted (glyphs)
656 while True:
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400657 additions = (sum ((self.table.LookupList.Lookup[i].closure_glyphs (glyphs, self) \
658 for i in lookup_indices if i < self.table.LookupList.LookupCount), []))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400659 additions = unique_sorted (g for g in additions if g not in glyphs)
660 if not additions:
661 return glyphs
662 glyphs.extend (additions)
663
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400664@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400665def subset_glyphs (self, glyphs):
666 lookup_indices = self.table.LookupList.subset_glyphs (glyphs)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400667 self.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400668 self.prune_lookups ()
669 return True
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400670
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400671@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400672def subset_lookups (self, lookup_indices):
673 "Retrains specified lookups, then removes empty features, language systems, and scripts."
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400674 self.table.LookupList.subset_lookups (lookup_indices)
675 feature_indices = self.table.FeatureList.subset_lookups (lookup_indices)
676 self.table.ScriptList.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400677
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400678@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
679def prune_lookups (self):
680 "Remove unreferenced lookups"
681 feature_indices = self.table.ScriptList.collect_features ()
682 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
683 lookup_indices = self.table.LookupList.closure_lookups (lookup_indices)
684 self.subset_lookups (lookup_indices)
685
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400686@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
687def subset_feature_tags (self, feature_tags):
688 feature_indices = [i for (i,f) in enumerate (self.table.FeatureList.FeatureRecord) if f.FeatureTag in feature_tags]
689 self.table.FeatureList.subset_features (feature_indices)
690 self.table.ScriptList.subset_features (feature_indices)
691
692@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400693def prune_pre_subset (self, options):
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400694 if options['layout-features'] and '*' not in options['layout-features']:
Behdad Esfahboded98c612013-07-23 12:37:41 -0400695 self.subset_feature_tags (options['layout-features'])
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400696 self.prune_lookups ()
697 return True
698
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400699@add_method(fontTools.ttLib.getTableClass('GDEF'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400700def subset_glyphs (self, glyphs):
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400701 table = self.table
702 if table.LigCaretList:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400703 indices = table.LigCaretList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400704 table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i] for i in indices]
705 table.LigCaretList.LigGlyphCount = len (table.LigCaretList.LigGlyph)
706 if not table.LigCaretList.LigGlyphCount:
707 table.LigCaretList = None
708 if table.MarkAttachClassDef:
709 table.MarkAttachClassDef.classDefs = {g:v for g,v in table.MarkAttachClassDef.classDefs.items() if g in glyphs}
710 if not table.MarkAttachClassDef.classDefs:
711 table.MarkAttachClassDef = None
712 if table.GlyphClassDef:
713 table.GlyphClassDef.classDefs = {g:v for g,v in table.GlyphClassDef.classDefs.items() if g in glyphs}
714 if not table.GlyphClassDef.classDefs:
715 table.GlyphClassDef = None
716 if table.AttachList:
Behdad Esfahbod327dcc32013-07-31 13:50:51 -0400717 indices = table.AttachList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400718 table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i] for i in indices]
719 table.AttachList.GlyphCount = len (table.AttachList.AttachPoint)
720 if not table.AttachList.GlyphCount:
721 table.AttachList = None
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400722 return bool (table.LigCaretList or table.MarkAttachClassDef or table.GlyphClassDef or table.AttachList)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400723
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400724@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbodd4e33a72013-07-24 18:51:05 -0400725def prune_pre_subset (self, options):
726 # Prune unknown kern table types
727 self.kernTables = [t for t in self.kernTables if hasattr (t, 'kernTable')]
728 return bool (self.kernTables)
729
730@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400731def subset_glyphs (self, glyphs):
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400732 for t in self.kernTables:
733 t.kernTable = {(a,b):v for ((a,b),v) in t.kernTable.items() if a in glyphs and b in glyphs}
734 self.kernTables = [t for t in self.kernTables if t.kernTable]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400735 return bool (self.kernTables)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400736
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400737@add_method(fontTools.ttLib.getTableClass('hmtx'), fontTools.ttLib.getTableClass('vmtx'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400738def subset_glyphs (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400739 self.metrics = {g:v for g,v in self.metrics.items() if g in glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400740 return bool (self.metrics)
Behdad Esfahbodc7160442013-07-22 14:29:08 -0400741
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400742@add_method(fontTools.ttLib.getTableClass('hdmx'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400743def subset_glyphs (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400744 self.hdmx = {s:{g:v for g,v in l.items() if g in glyphs} for (s,l) in self.hdmx.items()}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400745 return bool (self.hdmx)
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400746
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400747@add_method(fontTools.ttLib.getTableClass('VORG'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400748def subset_glyphs (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400749 self.VOriginRecords = {g:v for g,v in self.VOriginRecords.items() if g in glyphs}
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400750 self.numVertOriginYMetrics = len (self.VOriginRecords)
751 return True # Never drop; has default metrics
752
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400753@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400754def prune_pre_subset (self, options):
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400755 if not options['glyph-names']:
Behdad Esfahbod42648242013-07-23 12:56:06 -0400756 self.formatType = 3.0
757 return True
758
759@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400760def subset_glyphs (self, glyphs):
Behdad Esfahbod42648242013-07-23 12:56:06 -0400761 self.extraNames = [] # This seems to do it
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -0400762 return True
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400763
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400764# Copied from _g_l_y_f.py
765ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes
766ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points
767ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true
768WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0
769NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!)
770MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one
771WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy
772WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11
773WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow
774USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph
775OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts
776SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple)
777UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS)
778
779@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
780def getComponentNamesFast (self, glyfTable):
781 if struct.unpack(">h", self.data[:2])[0] >= 0:
782 return [] # Not composite
783 data = self.data
784 i = 10
785 components = []
786 more = 1
787 while more:
788 flags, glyphID = struct.unpack(">HH", data[i:i+4])
789 i += 4
790 flags = int(flags)
791 components.append (glyfTable.getGlyphName (int (glyphID)))
792
793 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
794 else: i += 2
795 if flags & WE_HAVE_A_SCALE: i += 2
796 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
797 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
798 more = flags & MORE_COMPONENTS
799 return components
800
801@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
802def remapComponentsFast (self, indices):
803 if struct.unpack(">h", self.data[:2])[0] >= 0:
804 return # Not composite
805 data = bytearray (self.data)
806 i = 10
807 more = 1
808 while more:
809 flags = (data[i] << 8) | data[i+1]
810 glyphID = (data[i+2] << 8) | data[i+3]
811 # Remap
812 glyphID = indices.index (glyphID)
813 data[i+2] = glyphID >> 8
814 data[i+3] = glyphID & 0xFF
815 i += 4
816 flags = int(flags)
817
818 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
819 else: i += 2
820 if flags & WE_HAVE_A_SCALE: i += 2
821 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
822 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
823 more = flags & MORE_COMPONENTS
824 self.data = str (data)
825
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400826@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
827def dropInstructionsFast (self):
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400828 numContours = struct.unpack(">h", self.data[:2])[0]
829 data = bytearray (self.data)
830 i = 10
831 if numContours >= 0:
832 i += 2 * numContours # endPtsOfContours
833 instructionLen = (data[i] << 8) | data[i+1]
834 # Zero it
835 data[i] = data [i+1] = 0
836 i += 2
Behdad Esfahbod0fb69882013-07-24 17:25:35 -0400837 if instructionLen:
838 # Splice it out
839 data = data[:i] + data[i+instructionLen:]
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400840 else:
841 more = 1
842 while more:
843 flags = (data[i] << 8) | data[i+1]
844 # Turn instruction flag off
845 flags &= ~WE_HAVE_INSTRUCTIONS
846 data[i+0] = flags >> 8
847 data[i+1] = flags & 0xFF
848 i += 4
849 flags = int(flags)
850
851 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
852 else: i += 2
853 if flags & WE_HAVE_A_SCALE: i += 2
854 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
855 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
856 more = flags & MORE_COMPONENTS
857 # Cut off
858 data = data[:i]
859 if len(data) % 4:
860 # add pad bytes
861 nPadBytes = 4 - (len(data) % 4)
862 for i in range (nPadBytes):
863 data.append (0)
864 self.data = str (data)
865
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400866@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400867def closure_glyphs (self, glyphs):
868 glyphs = unique_sorted (glyphs)
869 decompose = glyphs
870 # I don't know if component glyphs can be composite themselves.
871 # We handle them anyway.
872 while True:
873 components = []
874 for g in decompose:
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400875 if g not in self.glyphs:
Behdad Esfahbodf8c20e42013-07-23 23:13:23 -0400876 continue
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400877 gl = self.glyphs[g]
878 if hasattr (gl, "data"):
879 for c in gl.getComponentNamesFast (self):
880 if c not in glyphs:
881 components.append (c)
882 else:
883 # TTX seems to expand gid0..3 always
884 if gl.isComposite ():
885 for c in gl.components:
886 if c.glyphName not in glyphs:
887 components.append (c.glyphName)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400888 components = [c for c in components if c not in glyphs]
889 if not components:
890 return glyphs
891 decompose = unique_sorted (components)
892 glyphs.extend (components)
893
894@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400895def subset_glyphs (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400896 self.glyphs = {g:v for g,v in self.glyphs.items() if g in glyphs}
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400897 indices = [i for i,g in enumerate (self.glyphOrder) if g in glyphs]
898 for v in self.glyphs.values ():
899 if hasattr (v, "data"):
900 v.remapComponentsFast (indices)
901 else:
902 pass # No need
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400903 self.glyphOrder = [g for g in self.glyphOrder if g in glyphs]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400904 return bool (self.glyphs)
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400905
Behdad Esfahboded98c612013-07-23 12:37:41 -0400906@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400907def prune_post_subset (self, options):
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400908 if not options['hinting']:
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400909 for v in self.glyphs.values ():
910 if hasattr (v, "data"):
911 v.dropInstructionsFast ()
912 else:
913 v.program = fontTools.ttLib.tables.ttProgram.Program()
914 v.program.fromBytecode([])
Behdad Esfahboded98c612013-07-23 12:37:41 -0400915 return True
916
Behdad Esfahbod2b677c82013-07-23 13:37:13 -0400917@add_method(fontTools.ttLib.getTableClass('CFF '))
918def subset_glyphs (self, glyphs):
919 assert 0, "unimplemented"
920
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400921@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400922def prune_pre_subset (self, options):
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400923 if not options['legacy-cmap']:
924 # Drop non-Unicode / non-Symbol cmaps
925 self.tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [0, 1, 10]]
926 if not options['symbol-cmap']:
927 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 -0400928 # TODO Only keep one subtable?
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400929 # For now, drop format=0 which can't be subset_glyphs easily?
930 self.tables = [t for t in self.tables if t.format != 0]
931 return bool (self.tables)
932
933@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400934def subset_glyphs (self, glyphs):
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400935 for t in self.tables:
Behdad Esfahbod9453a362013-07-22 16:21:24 -0400936 # For reasons I don't understand I need this here
937 # to force decompilation of the cmap format 14.
938 try:
939 getattr (t, "asdf")
940 except AttributeError:
941 pass
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400942 if t.format == 14:
Behdad Esfahbod9453a362013-07-22 16:21:24 -0400943 # XXX We drop all the default-UVS mappings (g==None)
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400944 t.uvsDict = {v:[(u,g) for (u,g) in l if g in glyphs] for (v,l) in t.uvsDict.items()}
945 t.uvsDict = {v:l for (v,l) in t.uvsDict.items() if l}
946 else:
947 t.cmap = {u:g for (u,g) in t.cmap.items() if g in glyphs}
948 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 -0400949 # XXX Convert formats when needed
Behdad Esfahbod61addb42013-07-23 11:03:49 -0400950 return bool (self.tables)
951
Behdad Esfahbod61addb42013-07-23 11:03:49 -0400952@add_method(fontTools.ttLib.getTableClass('name'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400953def prune_pre_subset (self, options):
Behdad Esfahbod20faeb02013-07-23 13:19:03 -0400954 if '*' not in options['name-IDs']:
955 self.names = [n for n in self.names if n.nameID in options['name-IDs']]
956 if not options['name-legacy']:
957 self.names = [n for n in self.names if n.platformID == 3 and n.platEncID == 1]
958 if '*' not in options['name-languages']:
959 self.names = [n for n in self.names if n.langID in options['name-languages']]
960 return True # Retain even if empty
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400961
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400962
Behdad Esfahbodbc25f162013-07-23 12:56:54 -0400963drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'PCLT', 'LTSH']
Behdad Esfahbod103a12f2013-07-23 15:08:39 -0400964drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill'] # Graphite
Behdad Esfahbod38e852c2013-07-23 16:56:50 -0400965drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL'] # Color
Behdad Esfahboded98c612013-07-23 12:37:41 -0400966no_subset_tables = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2', 'loca', 'name', 'cvt ', 'fpgm', 'prep']
Behdad Esfahbodbc25f162013-07-23 12:56:54 -0400967hinting_tables = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
Behdad Esfahbod29df0462013-07-23 11:05:25 -0400968
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400969# Based on HarfBuzz shapers
970layout_features_dict = {
971 # Default shaper
972 'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
973 'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
974 'vertical': ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
975 'ltr': ['ltra', 'ltrm'],
976 'rtl': ['rtla', 'rtlm'],
977 # Complex shapers
978 'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3'],
979 'hangul': ['ljmo', 'vjmo', 'tjmo'],
980 'tibetal': ['abvs', 'blws', 'abvm', 'blwm'],
981 'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half', 'abvf', 'pstf', 'cfar', 'vatu', 'cjct',
982 'init', 'pres', 'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
983}
984layout_features_all = unique_sorted (sum (layout_features_dict.values (), []))
985
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400986options_default = {
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400987 'drop-tables': drop_tables_default,
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400988 'layout-features': layout_features_all,
989 'hinting': False,
990 'glyph-names': False,
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400991 'legacy-cmap': False,
992 'symbol-cmap': False,
Behdad Esfahbod20faeb02013-07-23 13:19:03 -0400993 'name-IDs': [1, 2], # Family and Style
994 'name-legacy': False,
995 'name-languages': [0x0409], # English
Behdad Esfahbode30ed122013-07-23 21:08:29 -0400996 'mandatory-glyphs': True, # First four for TrueType, .notdef for CFF
Behdad Esfahbod8e11c6d2013-07-24 16:17:03 -0400997 'recalc-bboxes': False, # Slows us down
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400998}
999
Behdad Esfahbod29df0462013-07-23 11:05:25 -04001000
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -04001001# TODO OS/2 ulUnicodeRange / ulCodePageRange?
Behdad Esfahbodf71267b2013-07-23 12:59:13 -04001002# TODO Drop unneeded GSUB/GPOS Script/LangSys entries
Behdad Esfahbod398d3892013-07-23 15:29:40 -04001003# TODO Avoid recursing too much
Behdad Esfahbode94aa0e2013-07-23 13:22:04 -04001004# TODO Text direction considerations
1005# TODO Text script / language considerations
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001006# TODO Drop unknown tables? Using DefaultTable.prune?
Behdad Esfahbod8c4f7cc2013-07-24 17:58:29 -04001007# TODO Drop GPOS Device records if not hinting?
Behdad Esfahbod75e7ecf2013-07-29 12:05:15 -04001008# TODO subset_unicode values in cmap
Behdad Esfahbod56ebd042013-07-22 13:02:24 -04001009
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001010
1011def main ():
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001012
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001013 import sys, time
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001014 global last_time
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001015
1016 start_time = time.time ()
1017 last_time = start_time
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001018
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001019 verbose = False
1020 if "--verbose" in sys.argv:
1021 verbose = True
1022 sys.argv.remove ("--verbose")
Behdad Esfahbod350a5272013-07-22 12:02:16 -04001023 xml = False
1024 if "--xml" in sys.argv:
1025 xml = True
1026 sys.argv.remove ("--xml")
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001027 timing = False
1028 if "--timing" in sys.argv:
1029 timing = True
1030 sys.argv.remove ("--timing")
1031
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001032 options = options_default.copy ()
1033
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001034 def lapse (what):
1035 if not timing:
1036 return
1037 global last_time
1038 new_time = time.time ()
1039 print "Took %0.3fs to %s" % (new_time - last_time, what)
1040 last_time = new_time
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001041
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001042 if len (sys.argv) < 3:
1043 print >>sys.stderr, "usage: pyotlss.py font-file glyph..."
1044 sys.exit (1)
1045
1046 fontfile = sys.argv[1]
1047 glyphs = sys.argv[2:]
1048
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001049 # TODO Option for ignoreDecompileErrors?
Behdad Esfahbodd83bb6c2013-07-24 19:20:04 -04001050 font = fontTools.ttx.TTFont (fontfile, recalcBBoxes=options['recalc-bboxes'])
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001051 lapse ("load font")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001052
Behdad Esfahbode86b7982013-07-25 18:34:22 -04001053 # If we don't need glyph names, change 'post' class to not try to
1054 # load them. It avoid lots of headache with broken fonts as well
1055 # as loading time. We already change the table format during
1056 # pruning so we are safe for the encode side.
1057 #
1058 # Ideally ttLib should provide a way to ask it to skip loading
1059 # glyph names. But it currently doesn't provide such a thing.
1060 if not options['glyph-names'] \
1061 and all (any (g.startswith (p) \
1062 for p in ['gid', 'glyph', 'uni']) \
1063 for g in glyphs):
Behdad Esfahbod3684f4b2013-07-24 19:36:39 -04001064 post = fontTools.ttLib.getTableClass('post')
1065 post.decode_format_2_0 = post.decode_format_3_0
1066 del post
1067
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001068 if options["mandatory-glyphs"]:
1069 # Always include .notdef; anything else?
1070 if 'glyf' in font:
1071 glyphs.extend (['gid0', 'gid1', 'gid2', 'gid3'])
1072 if verbose:
1073 print "Added first four glyphs to subset"
1074 else:
1075 glyphs.append ('.notdef')
1076 if verbose:
1077 print "Added .notdef glyph to subset"
1078
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001079 names = font.getGlyphNames()
Behdad Esfahbod9bd59c42013-07-23 21:19:49 -04001080 lapse ("loading glyph names")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001081 # Convert to glyph names
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001082 glyph_names = []
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001083 cmap_tables = None
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001084 for g in glyphs:
1085 if g in names:
1086 glyph_names.append (g)
1087 continue
Behdad Esfahbod7c225a62013-07-23 21:33:13 -04001088 if g.startswith ('uni') and len (g) > 3:
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001089 if not cmap_tables:
1090 cmap = font['cmap']
1091 cmap_tables = [t for t in cmap.tables if t.platformID == 3 and t.platEncID in [1, 10]]
1092 del cmap
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001093 found = False
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001094 u = int (g[3:], 16)
1095 for table in cmap_tables:
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001096 if u in table.cmap:
1097 glyph_names.append (table.cmap[u])
1098 found = True
1099 break
1100 if not found:
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001101 if verbose:
1102 print ("No glyph for Unicode value %s; skipping." % g)
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001103 continue
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001104 if g.startswith ('gid') or g.startswith ('glyph'):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -04001105 if g.startswith ('gid') and len (g) > 3:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001106 g = g[3:]
Behdad Esfahbod7c225a62013-07-23 21:33:13 -04001107 elif g.startswith ('glyph') and len (g) > 5:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001108 g = g[5:]
1109 try:
1110 glyph_names.append (font.getGlyphName (int (g), requireReal=1))
1111 except ValueError:
1112 raise Exception ("Invalid glyph identifier %s" % g)
1113 continue
1114 raise Exception ("Invalid glyph identifier %s" % g)
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001115 del cmap_tables
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001116 glyphs = unique_sorted (glyph_names)
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001117 del glyph_names
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001118 lapse ("compile glyph list")
Behdad Esfahbod240d7e72013-07-23 23:12:06 -04001119 if verbose:
1120 print "Glyphs:", glyphs
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001121
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001122
1123 for tag in font.keys():
1124 if tag == 'GlyphOrder': continue
1125
1126 if tag in options['drop-tables'] or \
Behdad Esfahbodc0d59592013-07-24 14:41:47 -04001127 (tag in hinting_tables and not options['hinting']):
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001128 if verbose:
1129 print tag, "dropped."
1130 del font[tag]
1131 continue
1132
1133 clazz = fontTools.ttLib.getTableClass(tag)
1134
1135 if hasattr (clazz, 'prune_pre_subset'):
1136 table = font[tag]
1137 retain = table.prune_pre_subset (options)
1138 lapse ("prune '%s'" % tag)
1139 if not retain:
1140 if verbose:
1141 print tag, "pruned to empty; dropped."
1142 del font[tag]
1143 continue
1144 else:
1145 if verbose:
1146 print tag, "pruned."
1147
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001148 glyphs_requested = glyphs
1149 if 'GSUB' in font:
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001150 if verbose:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001151 print "Closing glyph list over 'GSUB': %d glyphs before" % len (glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001152 glyphs = font['GSUB'].closure_glyphs (glyphs)
1153 if verbose:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001154 print "Closed glyph list over 'GSUB': %d glyphs after" % len (glyphs)
Behdad Esfahbod240d7e72013-07-23 23:12:06 -04001155 print "Glyphs:", glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001156 lapse ("close glyph list over 'GSUB'")
1157 glyphs_gsubed = glyphs
1158
Behdad Esfahbod2a784ac2013-07-22 17:00:36 -04001159 # Close over composite glyphs
1160 if 'glyf' in font:
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001161 if verbose:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001162 print "Closing glyph list over 'glyf': %d glyphs before" % len (glyphs)
Behdad Esfahbod240d7e72013-07-23 23:12:06 -04001163 print "Glyphs:", glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001164 glyphs = font['glyf'].closure_glyphs (glyphs)
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001165 if verbose:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001166 print "Closed glyph list over 'glyf': %d glyphs after" % len (glyphs)
Behdad Esfahbod240d7e72013-07-23 23:12:06 -04001167 print "Glyphs:", glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001168 lapse ("close glyph list over 'glyf'")
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001169 else:
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001170 glyphs = glyphs
1171 glyphs_glyfed = glyphs
1172 glyphs_closed = glyphs
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001173 del glyphs
1174
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -04001175 if verbose:
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001176 print "Retaining %d glyphs: " % len (glyphs_closed)
Behdad Esfahbod2a784ac2013-07-22 17:00:36 -04001177
Behdad Esfahbod8842ce22013-07-22 13:01:33 -04001178 for tag in font.keys():
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001179 if tag == 'GlyphOrder': continue
Behdad Esfahbod4e214e42013-07-22 13:13:49 -04001180
Behdad Esfahbod8842ce22013-07-22 13:01:33 -04001181 clazz = fontTools.ttLib.getTableClass(tag)
Behdad Esfahbod4e214e42013-07-22 13:13:49 -04001182
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001183 if tag in no_subset_tables:
1184 if verbose:
1185 print tag, "subsetting not needed."
Behdad Esfahbod96f47042013-07-23 12:21:34 -04001186 elif hasattr (clazz, 'subset_glyphs'):
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001187 table = font[tag]
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001188 if tag == 'cmap': # What else?
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001189 glyphs = glyphs_requested
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001190 elif tag in ['GSUB', 'GPOS', 'GDEF', 'cmap', 'kern', 'post']: # What else?
1191 glyphs = glyphs_gsubed
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001192 else:
1193 glyphs = glyphs_closed
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001194 retain = table.subset_glyphs (glyphs)
1195 lapse ("subset '%s'" % tag)
1196 if not retain:
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001197 if verbose:
1198 print tag, "subsetted to empty; dropped."
Behdad Esfahbod8b411f32013-07-23 11:24:20 -04001199 del font[tag]
1200 continue
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001201 else:
1202 if verbose:
1203 print tag, "subsetted."
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001204 del glyphs
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001205 else:
Behdad Esfahbod350a5272013-07-22 12:02:16 -04001206 if verbose:
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001207 print tag, "NOT subset; don't know how to subset."
1208 continue
1209
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -04001210 if hasattr (clazz, 'prune_post_subset'):
1211 table = font[tag]
1212 retain = table.prune_post_subset (options)
1213 lapse ("prune '%s'" % tag)
1214 if not retain:
1215 if verbose:
1216 print tag, "pruned to empty; dropped."
1217 del font[tag]
1218 continue
1219 else:
1220 if verbose:
1221 print tag, "pruned."
1222
Behdad Esfahbodc7160442013-07-22 14:29:08 -04001223 glyphOrder = font.getGlyphOrder()
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001224 glyphOrder = [g for g in glyphOrder if g in glyphs_closed]
Behdad Esfahbodc7160442013-07-22 14:29:08 -04001225 font.setGlyphOrder (glyphOrder)
1226 font._buildReverseGlyphOrderDict ()
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001227 lapse ("subset GlyphOrder")
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -04001228
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001229 font.save (fontfile + '.subset')
1230 lapse ("compile and save font")
1231
1232 last_time = start_time
1233 lapse ("make one with everything (TOTAL TIME)")
1234
Behdad Esfahbod0f86ce92013-07-22 17:30:31 -04001235 if xml:
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001236 import xmlWriter
1237 writer = xmlWriter.XMLWriter (sys.stdout)
1238
Behdad Esfahbodd83bb6c2013-07-24 19:20:04 -04001239 font.disassembleInstructions = False # Work around ttx bug
1240
Behdad Esfahbod0f86ce92013-07-22 17:30:31 -04001241 for tag in font.keys():
1242 writer.begintag (tag)
1243 writer.newline ()
1244 font[tag].toXML(writer, font)
1245 writer.endtag (tag)
1246 writer.newline ()
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001247
1248if __name__ == '__main__':
1249 main ()