blob: 96f455c2832a14a1cf30aa70dc068d5a523f5496 [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 Esfahbod610b0552013-07-23 14:52:18 -040044def intersect_glyphs (self, glyphs):
45 "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 Esfahbod0716eb42013-07-23 10:47:03 -040049def subset_glyphs (self, glyphs):
Behdad Esfahbodd821ea02013-07-23 10:50:43 -040050 "Returns ascending list of remaining coverage values."
Behdad Esfahbod610b0552013-07-23 14:52:18 -040051 indices = self.intersect_glyphs (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 Esfahbodb8d55882013-07-23 22:17:39 -040056def intersect_glyphs (self, glyphs):
57 "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)
61def intersects_glyphs_class (self, glyphs, klass):
62 "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 Esfahbodde71dca2013-07-24 12:40:54 -040066def subset_glyphs (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:
97 indices = self.Coverage.intersect_glyphs (glyphs)
98 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 Esfahbod0716eb42013-07-23 10:47:03 -0400105 indices = self.Coverage.subset_glyphs (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:
149 indices = self.Coverage.intersect_glyphs (glyphs)
150 if not indices or \
151 not all (c.intersect_glyphs (glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage):
152 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 Esfahbod0716eb42013-07-23 10:47:03 -0400160 indices = self.Coverage.subset_glyphs (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 Esfahbod4027dd82013-07-23 10:56:04 -0400163 return bool (self.GlyphCount and all (c.subset_glyphs (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 Esfahbod0716eb42013-07-23 10:47:03 -0400170 return len (self.Coverage.subset_glyphs (glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400171 elif self.Format == 2:
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400172 indices = self.Coverage.subset_glyphs (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 Esfahbod0716eb42013-07-23 10:47:03 -0400182 indices = self.Coverage.subset_glyphs (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 Esfahbodde71dca2013-07-24 12:40:54 -0400191 class1_map = self.ClassDef1.subset_glyphs (glyphs, remap=True)
192 class2_map = self.ClassDef2.subset_glyphs (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 Esfahbod4027dd82013-07-23 10:56:04 -0400198 return bool (self.Class1Count and self.Class2Count and self.Coverage.subset_glyphs (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 Esfahbod0716eb42013-07-23 10:47:03 -0400205 indices = self.Coverage.subset_glyphs (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 Esfahbod0716eb42013-07-23 10:47:03 -0400215 mark_indices = self.MarkCoverage.subset_glyphs (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 Esfahbod0716eb42013-07-23 10:47:03 -0400218 base_indices = self.BaseCoverage.subset_glyphs (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 Esfahbod0716eb42013-07-23 10:47:03 -0400235 mark_indices = self.MarkCoverage.subset_glyphs (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 Esfahbod0716eb42013-07-23 10:47:03 -0400238 ligature_indices = self.LigatureCoverage.subset_glyphs (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 Esfahbod0716eb42013-07-23 10:47:03 -0400256 mark1_indices = self.Mark1Coverage.subset_glyphs (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 Esfahbod0716eb42013-07-23 10:47:03 -0400259 mark2_indices = self.Mark2Coverage.subset_glyphs (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 Esfahbodeeca9822013-07-23 17:42:17 -0400385 indices = self.Coverage.intersect_glyphs (glyphs)
386 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 Esfahbod31084302013-07-23 22:22:38 -0400394 if not self.Coverage.intersect_glyphs (glyphs):
395 return []
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400396 indices = getattr (self, c.ClassDef).intersect_glyphs (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 Esfahbodb8d55882013-07-23 22:17:39 -0400401 if r and all (cd.intersects_glyphs_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 Esfahbodb178dca2013-07-23 22:51:50 -0400406 if not all (x.intersect_glyphs (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 Esfahbod0716eb42013-07-23 10:47:03 -0400419 indices = self.Coverage.subset_glyphs (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 Esfahbode9a3bd62013-07-23 22:41:11 -0400435 if not self.Coverage.subset_glyphs (glyphs):
436 return False
437 indices = getattr (self, c.ClassDef).intersect_glyphs (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 Esfahbodde71dca2013-07-24 12:40:54 -0400441 klass_maps = [x.subset_glyphs (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)
460
461 return all (x.subset_glyphs (glyphs) for x in c.ContextData (self))
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400462 elif self.Format == 3:
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400463 return all (x.subset_glyphs (glyphs) for x in c.RuleData (self))
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400464 else:
465 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400466
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400467@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
468 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400469def subset_lookups (self, lookup_indices):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400470 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400471
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400472 if self.Format in [1, 2]:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400473 for rs in getattr (self, c.RuleSet):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400474 if rs:
475 for r in getattr (rs, c.Rule):
476 if r:
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400477 setattr (r, c.LookupRecord, [ll for ll in getattr (r, c.LookupRecord) if ll \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400478 if ll.LookupListIndex in lookup_indices])
479 for ll in getattr (r, c.LookupRecord):
480 if ll:
481 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400482 elif self.Format == 3:
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400483 setattr (self, c.LookupRecord, [ll for ll in getattr (self, c.LookupRecord) if ll \
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400484 if ll.LookupListIndex in lookup_indices])
485 for ll in getattr (self, c.LookupRecord):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400486 if ll:
487 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400488 else:
489 assert 0, "unknown format: %s" % self.Format
490
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400491@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
492 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400493def collect_lookups (self):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400494 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400495
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400496 if self.Format in [1, 2]:
Behdad Esfahbod27108392013-07-23 16:40:47 -0400497 return [ll.LookupListIndex \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400498 for rs in getattr (self, c.RuleSet) if rs \
499 for r in getattr (rs, c.Rule) if r \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400500 for ll in getattr (r, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400501 elif self.Format == 3:
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400502 return [ll.LookupListIndex \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400503 for ll in getattr (self, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400504 else:
505 assert 0, "unknown format: %s" % self.Format
506
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400507@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
508def closure_glyphs (self, glyphs, table):
509 if self.Format == 1:
510 return self.ExtSubTable.closure_glyphs (glyphs, table)
511 else:
512 assert 0, "unknown format: %s" % self.Format
513
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400514@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400515def subset_glyphs (self, glyphs):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400516 if self.Format == 1:
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400517 return self.ExtSubTable.subset_glyphs (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400518 else:
519 assert 0, "unknown format: %s" % self.Format
520
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400521@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
522def subset_lookups (self, lookup_indices):
523 if self.Format == 1:
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400524 return self.ExtSubTable.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400525 else:
526 assert 0, "unknown format: %s" % self.Format
527
528@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
529def collect_lookups (self):
530 if self.Format == 1:
531 return self.ExtSubTable.collect_lookups ()
532 else:
533 assert 0, "unknown format: %s" % self.Format
534
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400535@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400536def closure_glyphs (self, glyphs, table):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400537 return sum ((s.closure_glyphs (glyphs, table) for s in self.SubTable if s), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400538
539@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400540def subset_glyphs (self, glyphs):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400541 self.SubTable = [s for s in self.SubTable if s and s.subset_glyphs (glyphs)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400542 self.SubTableCount = len (self.SubTable)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400543 return bool (self.SubTableCount)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400544
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400545@add_method(fontTools.ttLib.tables.otTables.Lookup)
546def subset_lookups (self, lookup_indices):
547 for s in self.SubTable:
548 s.subset_lookups (lookup_indices)
549
550@add_method(fontTools.ttLib.tables.otTables.Lookup)
551def collect_lookups (self):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400552 return unique_sorted (sum ((s.collect_lookups () for s in self.SubTable if s), []))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400553
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400554@add_method(fontTools.ttLib.tables.otTables.LookupList)
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400555def subset_glyphs (self, glyphs):
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400556 "Returns the indices of nonempty lookups."
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400557 return [i for (i,l) in enumerate (self.Lookup) if l and l.subset_glyphs (glyphs)]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400558
559@add_method(fontTools.ttLib.tables.otTables.LookupList)
560def subset_lookups (self, lookup_indices):
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400561 self.Lookup = [self.Lookup[i] for i in lookup_indices if i < self.LookupCount]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400562 self.LookupCount = len (self.Lookup)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400563 for l in self.Lookup:
564 l.subset_lookups (lookup_indices)
565
566@add_method(fontTools.ttLib.tables.otTables.LookupList)
567def closure_lookups (self, lookup_indices):
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400568 lookup_indices = unique_sorted (lookup_indices)
569 recurse = lookup_indices
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400570 while True:
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400571 recurse_lookups = sum ((self.Lookup[i].collect_lookups () for i in recurse if i < self.LookupCount), [])
572 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 -0400573 if not recurse_lookups:
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400574 return unique_sorted (lookup_indices)
575 recurse_lookups = unique_sorted (recurse_lookups)
576 lookup_indices.extend (recurse_lookups)
577 recurse = recurse_lookups
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400578
579@add_method(fontTools.ttLib.tables.otTables.Feature)
580def subset_lookups (self, lookup_indices):
581 self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices]
582 # Now map them.
583 self.LookupListIndex = [lookup_indices.index (l) for l in self.LookupListIndex]
584 self.LookupCount = len (self.LookupListIndex)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400585 return self.LookupCount
Behdad Esfahbod54660612013-07-21 18:16:55 -0400586
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400587@add_method(fontTools.ttLib.tables.otTables.Feature)
588def collect_lookups (self):
589 return self.LookupListIndex[:]
590
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400591@add_method(fontTools.ttLib.tables.otTables.FeatureList)
592def subset_lookups (self, lookup_indices):
593 "Returns the indices of nonempty features."
594 feature_indices = [i for (i,f) in enumerate (self.FeatureRecord) if f.Feature.subset_lookups (lookup_indices)]
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400595 self.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400596 return feature_indices
597
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400598@add_method(fontTools.ttLib.tables.otTables.FeatureList)
599def collect_lookups (self, feature_indices):
600 return unique_sorted (sum ((self.FeatureRecord[i].Feature.collect_lookups () for i in feature_indices
601 if i < self.FeatureCount), []))
602
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400603@add_method(fontTools.ttLib.tables.otTables.FeatureList)
604def subset_features (self, feature_indices):
605 self.FeatureRecord = [self.FeatureRecord[i] for i in feature_indices]
606 self.FeatureCount = len (self.FeatureRecord)
607 return bool (self.FeatureCount)
608
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400609@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
610def subset_features (self, feature_indices):
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400611 if self.ReqFeatureIndex in feature_indices:
612 self.ReqFeatureIndex = feature_indices.index (self.ReqFeatureIndex)
613 else:
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400614 self.ReqFeatureIndex = 65535
615 self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400616 # Now map them.
617 self.FeatureIndex = [feature_indices.index (f) for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400618 self.FeatureCount = len (self.FeatureIndex)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400619 return bool (self.FeatureCount or self.ReqFeatureIndex != 65535)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400620
621@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
622def collect_features (self):
623 feature_indices = self.FeatureIndex[:]
624 if self.ReqFeatureIndex != 65535:
625 feature_indices.append (self.ReqFeatureIndex)
626 return unique_sorted (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400627
628@add_method(fontTools.ttLib.tables.otTables.Script)
629def subset_features (self, feature_indices):
630 if self.DefaultLangSys and not self.DefaultLangSys.subset_features (feature_indices):
631 self.DefaultLangSys = None
632 self.LangSysRecord = [l for l in self.LangSysRecord if l.LangSys.subset_features (feature_indices)]
633 self.LangSysCount = len (self.LangSysRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400634 return bool (self.LangSysCount or self.DefaultLangSys)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400635
636@add_method(fontTools.ttLib.tables.otTables.Script)
637def collect_features (self):
Behdad Esfahbod2307c8b2013-07-23 11:18:13 -0400638 feature_indices = [l.LangSys.collect_features () for l in self.LangSysRecord]
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400639 if self.DefaultLangSys:
640 feature_indices.append (self.DefaultLangSys.collect_features ())
641 return unique_sorted (sum (feature_indices, []))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400642
643@add_method(fontTools.ttLib.tables.otTables.ScriptList)
644def subset_features (self, feature_indices):
645 self.ScriptRecord = [s for s in self.ScriptRecord if s.Script.subset_features (feature_indices)]
646 self.ScriptCount = len (self.ScriptRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400647 return bool (self.ScriptCount)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400648
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400649@add_method(fontTools.ttLib.tables.otTables.ScriptList)
650def collect_features (self):
651 return unique_sorted (sum ((s.Script.collect_features () for s in self.ScriptRecord), []))
652
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400653@add_method(fontTools.ttLib.getTableClass('GSUB'))
654def closure_glyphs (self, glyphs):
655 feature_indices = self.table.ScriptList.collect_features ()
656 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
657 glyphs = unique_sorted (glyphs)
658 while True:
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400659 additions = (sum ((self.table.LookupList.Lookup[i].closure_glyphs (glyphs, self) \
660 for i in lookup_indices if i < self.table.LookupList.LookupCount), []))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400661 additions = unique_sorted (g for g in additions if g not in glyphs)
662 if not additions:
663 return glyphs
664 glyphs.extend (additions)
665
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400666@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400667def subset_glyphs (self, glyphs):
668 lookup_indices = self.table.LookupList.subset_glyphs (glyphs)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400669 self.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400670 self.prune_lookups ()
671 return True
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400672
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400673@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400674def subset_lookups (self, lookup_indices):
675 "Retrains specified lookups, then removes empty features, language systems, and scripts."
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400676 self.table.LookupList.subset_lookups (lookup_indices)
677 feature_indices = self.table.FeatureList.subset_lookups (lookup_indices)
678 self.table.ScriptList.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400679
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400680@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
681def prune_lookups (self):
682 "Remove unreferenced lookups"
683 feature_indices = self.table.ScriptList.collect_features ()
684 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
685 lookup_indices = self.table.LookupList.closure_lookups (lookup_indices)
686 self.subset_lookups (lookup_indices)
687
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400688@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
689def subset_feature_tags (self, feature_tags):
690 feature_indices = [i for (i,f) in enumerate (self.table.FeatureList.FeatureRecord) if f.FeatureTag in feature_tags]
691 self.table.FeatureList.subset_features (feature_indices)
692 self.table.ScriptList.subset_features (feature_indices)
693
694@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400695def prune_pre_subset (self, options):
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400696 if options['layout-features'] and '*' not in options['layout-features']:
Behdad Esfahboded98c612013-07-23 12:37:41 -0400697 self.subset_feature_tags (options['layout-features'])
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400698 self.prune_lookups ()
699 return True
700
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400701@add_method(fontTools.ttLib.getTableClass('GDEF'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400702def subset_glyphs (self, glyphs):
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400703 table = self.table
704 if table.LigCaretList:
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400705 indices = table.LigCaretList.Coverage.subset_glyphs (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400706 table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i] for i in indices]
707 table.LigCaretList.LigGlyphCount = len (table.LigCaretList.LigGlyph)
708 if not table.LigCaretList.LigGlyphCount:
709 table.LigCaretList = None
710 if table.MarkAttachClassDef:
711 table.MarkAttachClassDef.classDefs = {g:v for g,v in table.MarkAttachClassDef.classDefs.items() if g in glyphs}
712 if not table.MarkAttachClassDef.classDefs:
713 table.MarkAttachClassDef = None
714 if table.GlyphClassDef:
715 table.GlyphClassDef.classDefs = {g:v for g,v in table.GlyphClassDef.classDefs.items() if g in glyphs}
716 if not table.GlyphClassDef.classDefs:
717 table.GlyphClassDef = None
718 if table.AttachList:
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400719 indices = table.AttachList.Coverage.subset_glyphs (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400720 table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i] for i in indices]
721 table.AttachList.GlyphCount = len (table.AttachList.AttachPoint)
722 if not table.AttachList.GlyphCount:
723 table.AttachList = None
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400724 return bool (table.LigCaretList or table.MarkAttachClassDef or table.GlyphClassDef or table.AttachList)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400725
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400726@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbodd4e33a72013-07-24 18:51:05 -0400727def prune_pre_subset (self, options):
728 # Prune unknown kern table types
729 self.kernTables = [t for t in self.kernTables if hasattr (t, 'kernTable')]
730 return bool (self.kernTables)
731
732@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400733def subset_glyphs (self, glyphs):
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400734 for t in self.kernTables:
735 t.kernTable = {(a,b):v for ((a,b),v) in t.kernTable.items() if a in glyphs and b in glyphs}
736 self.kernTables = [t for t in self.kernTables if t.kernTable]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400737 return bool (self.kernTables)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400738
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400739@add_method(fontTools.ttLib.getTableClass('hmtx'), fontTools.ttLib.getTableClass('vmtx'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400740def subset_glyphs (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400741 self.metrics = {g:v for g,v in self.metrics.items() if g in glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400742 return bool (self.metrics)
Behdad Esfahbodc7160442013-07-22 14:29:08 -0400743
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400744@add_method(fontTools.ttLib.getTableClass('hdmx'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400745def subset_glyphs (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400746 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 -0400747 return bool (self.hdmx)
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400748
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400749@add_method(fontTools.ttLib.getTableClass('VORG'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400750def subset_glyphs (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400751 self.VOriginRecords = {g:v for g,v in self.VOriginRecords.items() if g in glyphs}
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400752 self.numVertOriginYMetrics = len (self.VOriginRecords)
753 return True # Never drop; has default metrics
754
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400755@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400756def prune_pre_subset (self, options):
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400757 if not options['glyph-names']:
Behdad Esfahbod42648242013-07-23 12:56:06 -0400758 self.formatType = 3.0
759 return True
760
761@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400762def subset_glyphs (self, glyphs):
Behdad Esfahbod42648242013-07-23 12:56:06 -0400763 self.extraNames = [] # This seems to do it
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -0400764 return True
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400765
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400766# Copied from _g_l_y_f.py
767ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes
768ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points
769ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true
770WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0
771NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!)
772MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one
773WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy
774WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11
775WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow
776USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph
777OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts
778SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple)
779UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS)
780
781@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
782def getComponentNamesFast (self, glyfTable):
783 if struct.unpack(">h", self.data[:2])[0] >= 0:
784 return [] # Not composite
785 data = self.data
786 i = 10
787 components = []
788 more = 1
789 while more:
790 flags, glyphID = struct.unpack(">HH", data[i:i+4])
791 i += 4
792 flags = int(flags)
793 components.append (glyfTable.getGlyphName (int (glyphID)))
794
795 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
796 else: i += 2
797 if flags & WE_HAVE_A_SCALE: i += 2
798 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
799 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
800 more = flags & MORE_COMPONENTS
801 return components
802
803@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
804def remapComponentsFast (self, indices):
805 if struct.unpack(">h", self.data[:2])[0] >= 0:
806 return # Not composite
807 data = bytearray (self.data)
808 i = 10
809 more = 1
810 while more:
811 flags = (data[i] << 8) | data[i+1]
812 glyphID = (data[i+2] << 8) | data[i+3]
813 # Remap
814 glyphID = indices.index (glyphID)
815 data[i+2] = glyphID >> 8
816 data[i+3] = glyphID & 0xFF
817 i += 4
818 flags = int(flags)
819
820 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
821 else: i += 2
822 if flags & WE_HAVE_A_SCALE: i += 2
823 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
824 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
825 more = flags & MORE_COMPONENTS
826 self.data = str (data)
827
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400828@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
829def dropInstructionsFast (self):
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400830 numContours = struct.unpack(">h", self.data[:2])[0]
831 data = bytearray (self.data)
832 i = 10
833 if numContours >= 0:
834 i += 2 * numContours # endPtsOfContours
835 instructionLen = (data[i] << 8) | data[i+1]
836 # Zero it
837 data[i] = data [i+1] = 0
838 i += 2
Behdad Esfahbod0fb69882013-07-24 17:25:35 -0400839 if instructionLen:
840 # Splice it out
841 data = data[:i] + data[i+instructionLen:]
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400842 else:
843 more = 1
844 while more:
845 flags = (data[i] << 8) | data[i+1]
846 # Turn instruction flag off
847 flags &= ~WE_HAVE_INSTRUCTIONS
848 data[i+0] = flags >> 8
849 data[i+1] = flags & 0xFF
850 i += 4
851 flags = int(flags)
852
853 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
854 else: i += 2
855 if flags & WE_HAVE_A_SCALE: i += 2
856 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
857 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
858 more = flags & MORE_COMPONENTS
859 # Cut off
860 data = data[:i]
861 if len(data) % 4:
862 # add pad bytes
863 nPadBytes = 4 - (len(data) % 4)
864 for i in range (nPadBytes):
865 data.append (0)
866 self.data = str (data)
867
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400868@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400869def closure_glyphs (self, glyphs):
870 glyphs = unique_sorted (glyphs)
871 decompose = glyphs
872 # I don't know if component glyphs can be composite themselves.
873 # We handle them anyway.
874 while True:
875 components = []
876 for g in decompose:
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400877 if g not in self.glyphs:
Behdad Esfahbodf8c20e42013-07-23 23:13:23 -0400878 continue
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400879 gl = self.glyphs[g]
880 if hasattr (gl, "data"):
881 for c in gl.getComponentNamesFast (self):
882 if c not in glyphs:
883 components.append (c)
884 else:
885 # TTX seems to expand gid0..3 always
886 if gl.isComposite ():
887 for c in gl.components:
888 if c.glyphName not in glyphs:
889 components.append (c.glyphName)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400890 components = [c for c in components if c not in glyphs]
891 if not components:
892 return glyphs
893 decompose = unique_sorted (components)
894 glyphs.extend (components)
895
896@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400897def subset_glyphs (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400898 self.glyphs = {g:v for g,v in self.glyphs.items() if g in glyphs}
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400899 indices = [i for i,g in enumerate (self.glyphOrder) if g in glyphs]
900 for v in self.glyphs.values ():
901 if hasattr (v, "data"):
902 v.remapComponentsFast (indices)
903 else:
904 pass # No need
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400905 self.glyphOrder = [g for g in self.glyphOrder if g in glyphs]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400906 return bool (self.glyphs)
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400907
Behdad Esfahboded98c612013-07-23 12:37:41 -0400908@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400909def prune_post_subset (self, options):
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400910 if not options['hinting']:
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400911 for v in self.glyphs.values ():
912 if hasattr (v, "data"):
913 v.dropInstructionsFast ()
914 else:
915 v.program = fontTools.ttLib.tables.ttProgram.Program()
916 v.program.fromBytecode([])
Behdad Esfahboded98c612013-07-23 12:37:41 -0400917 return True
918
Behdad Esfahbod2b677c82013-07-23 13:37:13 -0400919@add_method(fontTools.ttLib.getTableClass('CFF '))
920def subset_glyphs (self, glyphs):
921 assert 0, "unimplemented"
922
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400923@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400924def prune_pre_subset (self, options):
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400925 if not options['legacy-cmap']:
926 # Drop non-Unicode / non-Symbol cmaps
927 self.tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [0, 1, 10]]
928 if not options['symbol-cmap']:
929 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 -0400930 # TODO Only keep one subtable?
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400931 # For now, drop format=0 which can't be subset_glyphs easily?
932 self.tables = [t for t in self.tables if t.format != 0]
933 return bool (self.tables)
934
935@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400936def subset_glyphs (self, glyphs):
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400937 for t in self.tables:
Behdad Esfahbod9453a362013-07-22 16:21:24 -0400938 # For reasons I don't understand I need this here
939 # to force decompilation of the cmap format 14.
940 try:
941 getattr (t, "asdf")
942 except AttributeError:
943 pass
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400944 if t.format == 14:
Behdad Esfahbod9453a362013-07-22 16:21:24 -0400945 # XXX We drop all the default-UVS mappings (g==None)
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400946 t.uvsDict = {v:[(u,g) for (u,g) in l if g in glyphs] for (v,l) in t.uvsDict.items()}
947 t.uvsDict = {v:l for (v,l) in t.uvsDict.items() if l}
948 else:
949 t.cmap = {u:g for (u,g) in t.cmap.items() if g in glyphs}
950 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 -0400951 # XXX Convert formats when needed
Behdad Esfahbod61addb42013-07-23 11:03:49 -0400952 return bool (self.tables)
953
Behdad Esfahbod61addb42013-07-23 11:03:49 -0400954@add_method(fontTools.ttLib.getTableClass('name'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400955def prune_pre_subset (self, options):
Behdad Esfahbod20faeb02013-07-23 13:19:03 -0400956 if '*' not in options['name-IDs']:
957 self.names = [n for n in self.names if n.nameID in options['name-IDs']]
958 if not options['name-legacy']:
959 self.names = [n for n in self.names if n.platformID == 3 and n.platEncID == 1]
960 if '*' not in options['name-languages']:
961 self.names = [n for n in self.names if n.langID in options['name-languages']]
962 return True # Retain even if empty
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400963
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400964
Behdad Esfahbodbc25f162013-07-23 12:56:54 -0400965drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'PCLT', 'LTSH']
Behdad Esfahbod103a12f2013-07-23 15:08:39 -0400966drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill'] # Graphite
Behdad Esfahbod38e852c2013-07-23 16:56:50 -0400967drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL'] # Color
Behdad Esfahboded98c612013-07-23 12:37:41 -0400968no_subset_tables = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2', 'loca', 'name', 'cvt ', 'fpgm', 'prep']
Behdad Esfahbodbc25f162013-07-23 12:56:54 -0400969hinting_tables = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
Behdad Esfahbod29df0462013-07-23 11:05:25 -0400970
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400971# Based on HarfBuzz shapers
972layout_features_dict = {
973 # Default shaper
974 'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
975 'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
976 'vertical': ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
977 'ltr': ['ltra', 'ltrm'],
978 'rtl': ['rtla', 'rtlm'],
979 # Complex shapers
980 'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3'],
981 'hangul': ['ljmo', 'vjmo', 'tjmo'],
982 'tibetal': ['abvs', 'blws', 'abvm', 'blwm'],
983 'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half', 'abvf', 'pstf', 'cfar', 'vatu', 'cjct',
984 'init', 'pres', 'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
985}
986layout_features_all = unique_sorted (sum (layout_features_dict.values (), []))
987
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400988options_default = {
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400989 'drop-tables': drop_tables_default,
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400990 'layout-features': layout_features_all,
991 'hinting': False,
992 'glyph-names': False,
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400993 'legacy-cmap': False,
994 'symbol-cmap': False,
Behdad Esfahbod20faeb02013-07-23 13:19:03 -0400995 'name-IDs': [1, 2], # Family and Style
996 'name-legacy': False,
997 'name-languages': [0x0409], # English
Behdad Esfahbode30ed122013-07-23 21:08:29 -0400998 'mandatory-glyphs': True, # First four for TrueType, .notdef for CFF
Behdad Esfahbod8e11c6d2013-07-24 16:17:03 -0400999 'recalc-bboxes': False, # Slows us down
Behdad Esfahbod4091ec62013-07-23 13:02:51 -04001000}
1001
Behdad Esfahbod29df0462013-07-23 11:05:25 -04001002
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -04001003# TODO OS/2 ulUnicodeRange / ulCodePageRange?
Behdad Esfahbodf71267b2013-07-23 12:59:13 -04001004# TODO Drop unneeded GSUB/GPOS Script/LangSys entries
Behdad Esfahbod398d3892013-07-23 15:29:40 -04001005# TODO Avoid recursing too much
Behdad Esfahbode94aa0e2013-07-23 13:22:04 -04001006# TODO Text direction considerations
1007# TODO Text script / language considerations
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001008# TODO Drop unknown tables? Using DefaultTable.prune?
Behdad Esfahbod8c4f7cc2013-07-24 17:58:29 -04001009# TODO Drop GPOS Device records if not hinting?
Behdad Esfahbod75e7ecf2013-07-29 12:05:15 -04001010# TODO subset_unicode values in cmap
Behdad Esfahbod56ebd042013-07-22 13:02:24 -04001011
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001012
1013def main ():
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001014
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001015 import sys, time
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001016 global last_time
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001017
1018 start_time = time.time ()
1019 last_time = start_time
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001020
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001021 verbose = False
1022 if "--verbose" in sys.argv:
1023 verbose = True
1024 sys.argv.remove ("--verbose")
Behdad Esfahbod350a5272013-07-22 12:02:16 -04001025 xml = False
1026 if "--xml" in sys.argv:
1027 xml = True
1028 sys.argv.remove ("--xml")
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001029 timing = False
1030 if "--timing" in sys.argv:
1031 timing = True
1032 sys.argv.remove ("--timing")
1033
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001034 options = options_default.copy ()
1035
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001036 def lapse (what):
1037 if not timing:
1038 return
1039 global last_time
1040 new_time = time.time ()
1041 print "Took %0.3fs to %s" % (new_time - last_time, what)
1042 last_time = new_time
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001043
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001044 if len (sys.argv) < 3:
1045 print >>sys.stderr, "usage: pyotlss.py font-file glyph..."
1046 sys.exit (1)
1047
1048 fontfile = sys.argv[1]
1049 glyphs = sys.argv[2:]
1050
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001051 # TODO Option for ignoreDecompileErrors?
Behdad Esfahbodd83bb6c2013-07-24 19:20:04 -04001052 font = fontTools.ttx.TTFont (fontfile, recalcBBoxes=options['recalc-bboxes'])
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001053 lapse ("load font")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001054
Behdad Esfahbode86b7982013-07-25 18:34:22 -04001055 # If we don't need glyph names, change 'post' class to not try to
1056 # load them. It avoid lots of headache with broken fonts as well
1057 # as loading time. We already change the table format during
1058 # pruning so we are safe for the encode side.
1059 #
1060 # Ideally ttLib should provide a way to ask it to skip loading
1061 # glyph names. But it currently doesn't provide such a thing.
1062 if not options['glyph-names'] \
1063 and all (any (g.startswith (p) \
1064 for p in ['gid', 'glyph', 'uni']) \
1065 for g in glyphs):
Behdad Esfahbod3684f4b2013-07-24 19:36:39 -04001066 post = fontTools.ttLib.getTableClass('post')
1067 post.decode_format_2_0 = post.decode_format_3_0
1068 del post
1069
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001070 if options["mandatory-glyphs"]:
1071 # Always include .notdef; anything else?
1072 if 'glyf' in font:
1073 glyphs.extend (['gid0', 'gid1', 'gid2', 'gid3'])
1074 if verbose:
1075 print "Added first four glyphs to subset"
1076 else:
1077 glyphs.append ('.notdef')
1078 if verbose:
1079 print "Added .notdef glyph to subset"
1080
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001081 names = font.getGlyphNames()
Behdad Esfahbod9bd59c42013-07-23 21:19:49 -04001082 lapse ("loading glyph names")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001083 # Convert to glyph names
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001084 glyph_names = []
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001085 cmap_tables = None
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001086 for g in glyphs:
1087 if g in names:
1088 glyph_names.append (g)
1089 continue
Behdad Esfahbod7c225a62013-07-23 21:33:13 -04001090 if g.startswith ('uni') and len (g) > 3:
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001091 if not cmap_tables:
1092 cmap = font['cmap']
1093 cmap_tables = [t for t in cmap.tables if t.platformID == 3 and t.platEncID in [1, 10]]
1094 del cmap
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001095 found = False
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001096 u = int (g[3:], 16)
1097 for table in cmap_tables:
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001098 if u in table.cmap:
1099 glyph_names.append (table.cmap[u])
1100 found = True
1101 break
1102 if not found:
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001103 if verbose:
1104 print ("No glyph for Unicode value %s; skipping." % g)
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001105 continue
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001106 if g.startswith ('gid') or g.startswith ('glyph'):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -04001107 if g.startswith ('gid') and len (g) > 3:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001108 g = g[3:]
Behdad Esfahbod7c225a62013-07-23 21:33:13 -04001109 elif g.startswith ('glyph') and len (g) > 5:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001110 g = g[5:]
1111 try:
1112 glyph_names.append (font.getGlyphName (int (g), requireReal=1))
1113 except ValueError:
1114 raise Exception ("Invalid glyph identifier %s" % g)
1115 continue
1116 raise Exception ("Invalid glyph identifier %s" % g)
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001117 del cmap_tables
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001118 glyphs = unique_sorted (glyph_names)
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001119 del glyph_names
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001120 lapse ("compile glyph list")
Behdad Esfahbod240d7e72013-07-23 23:12:06 -04001121 if verbose:
1122 print "Glyphs:", glyphs
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001123
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001124
1125 for tag in font.keys():
1126 if tag == 'GlyphOrder': continue
1127
1128 if tag in options['drop-tables'] or \
Behdad Esfahbodc0d59592013-07-24 14:41:47 -04001129 (tag in hinting_tables and not options['hinting']):
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001130 if verbose:
1131 print tag, "dropped."
1132 del font[tag]
1133 continue
1134
1135 clazz = fontTools.ttLib.getTableClass(tag)
1136
1137 if hasattr (clazz, 'prune_pre_subset'):
1138 table = font[tag]
1139 retain = table.prune_pre_subset (options)
1140 lapse ("prune '%s'" % tag)
1141 if not retain:
1142 if verbose:
1143 print tag, "pruned to empty; dropped."
1144 del font[tag]
1145 continue
1146 else:
1147 if verbose:
1148 print tag, "pruned."
1149
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001150 glyphs_requested = glyphs
1151 if 'GSUB' in font:
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001152 if verbose:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001153 print "Closing glyph list over 'GSUB': %d glyphs before" % len (glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001154 glyphs = font['GSUB'].closure_glyphs (glyphs)
1155 if verbose:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001156 print "Closed glyph list over 'GSUB': %d glyphs after" % len (glyphs)
Behdad Esfahbod240d7e72013-07-23 23:12:06 -04001157 print "Glyphs:", glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001158 lapse ("close glyph list over 'GSUB'")
1159 glyphs_gsubed = glyphs
1160
Behdad Esfahbod2a784ac2013-07-22 17:00:36 -04001161 # Close over composite glyphs
1162 if 'glyf' in font:
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001163 if verbose:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001164 print "Closing glyph list over 'glyf': %d glyphs before" % len (glyphs)
Behdad Esfahbod240d7e72013-07-23 23:12:06 -04001165 print "Glyphs:", glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001166 glyphs = font['glyf'].closure_glyphs (glyphs)
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001167 if verbose:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001168 print "Closed glyph list over 'glyf': %d glyphs after" % len (glyphs)
Behdad Esfahbod240d7e72013-07-23 23:12:06 -04001169 print "Glyphs:", glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001170 lapse ("close glyph list over 'glyf'")
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001171 else:
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001172 glyphs = glyphs
1173 glyphs_glyfed = glyphs
1174 glyphs_closed = glyphs
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001175 del glyphs
1176
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -04001177 if verbose:
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001178 print "Retaining %d glyphs: " % len (glyphs_closed)
Behdad Esfahbod2a784ac2013-07-22 17:00:36 -04001179
Behdad Esfahbod8842ce22013-07-22 13:01:33 -04001180 for tag in font.keys():
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001181 if tag == 'GlyphOrder': continue
Behdad Esfahbod4e214e42013-07-22 13:13:49 -04001182
Behdad Esfahbod8842ce22013-07-22 13:01:33 -04001183 clazz = fontTools.ttLib.getTableClass(tag)
Behdad Esfahbod4e214e42013-07-22 13:13:49 -04001184
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001185 if tag in no_subset_tables:
1186 if verbose:
1187 print tag, "subsetting not needed."
Behdad Esfahbod96f47042013-07-23 12:21:34 -04001188 elif hasattr (clazz, 'subset_glyphs'):
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001189 table = font[tag]
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001190 if tag == 'cmap': # What else?
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001191 glyphs = glyphs_requested
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001192 elif tag in ['GSUB', 'GPOS', 'GDEF', 'cmap', 'kern', 'post']: # What else?
1193 glyphs = glyphs_gsubed
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001194 else:
1195 glyphs = glyphs_closed
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001196 retain = table.subset_glyphs (glyphs)
1197 lapse ("subset '%s'" % tag)
1198 if not retain:
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001199 if verbose:
1200 print tag, "subsetted to empty; dropped."
Behdad Esfahbod8b411f32013-07-23 11:24:20 -04001201 del font[tag]
1202 continue
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001203 else:
1204 if verbose:
1205 print tag, "subsetted."
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001206 del glyphs
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001207 else:
Behdad Esfahbod350a5272013-07-22 12:02:16 -04001208 if verbose:
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001209 print tag, "NOT subset; don't know how to subset."
1210 continue
1211
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -04001212 if hasattr (clazz, 'prune_post_subset'):
1213 table = font[tag]
1214 retain = table.prune_post_subset (options)
1215 lapse ("prune '%s'" % tag)
1216 if not retain:
1217 if verbose:
1218 print tag, "pruned to empty; dropped."
1219 del font[tag]
1220 continue
1221 else:
1222 if verbose:
1223 print tag, "pruned."
1224
Behdad Esfahbodc7160442013-07-22 14:29:08 -04001225 glyphOrder = font.getGlyphOrder()
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001226 glyphOrder = [g for g in glyphOrder if g in glyphs_closed]
Behdad Esfahbodc7160442013-07-22 14:29:08 -04001227 font.setGlyphOrder (glyphOrder)
1228 font._buildReverseGlyphOrderDict ()
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001229 lapse ("subset GlyphOrder")
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -04001230
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001231 font.save (fontfile + '.subset')
1232 lapse ("compile and save font")
1233
1234 last_time = start_time
1235 lapse ("make one with everything (TOTAL TIME)")
1236
Behdad Esfahbod0f86ce92013-07-22 17:30:31 -04001237 if xml:
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001238 import xmlWriter
1239 writer = xmlWriter.XMLWriter (sys.stdout)
1240
Behdad Esfahbodd83bb6c2013-07-24 19:20:04 -04001241 font.disassembleInstructions = False # Work around ttx bug
1242
Behdad Esfahbod0f86ce92013-07-22 17:30:31 -04001243 for tag in font.keys():
1244 writer.begintag (tag)
1245 writer.newline ()
1246 font[tag].toXML(writer, font)
1247 writer.endtag (tag)
1248 writer.newline ()
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001249
1250if __name__ == '__main__':
1251 main ()