blob: 838fe0826bf6dd5aa61012db30952703432af796 [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):
40 return sorted ({v:1 for v in l}.keys ())
41
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):
561 self.Lookup = [self.Lookup[i] for i in lookup_indices]
562 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 Esfahbodbb7e2132013-07-23 13:48:35 -0400571 recurse_lookups = sum ((self.Lookup[i].collect_lookups () for i in recurse), [])
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400572 recurse_lookups = [l for l in recurse_lookups if l not in lookup_indices]
573 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:
659 additions = (sum ((self.table.LookupList.Lookup[i].closure_glyphs (glyphs, self) for i in lookup_indices), []))
660 additions = unique_sorted (g for g in additions if g not in glyphs)
661 if not additions:
662 return glyphs
663 glyphs.extend (additions)
664
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400665@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400666def subset_glyphs (self, glyphs):
667 lookup_indices = self.table.LookupList.subset_glyphs (glyphs)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400668 self.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400669 self.prune_lookups ()
670 return True
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400671
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400672@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400673def subset_lookups (self, lookup_indices):
674 "Retrains specified lookups, then removes empty features, language systems, and scripts."
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400675 self.table.LookupList.subset_lookups (lookup_indices)
676 feature_indices = self.table.FeatureList.subset_lookups (lookup_indices)
677 self.table.ScriptList.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400678
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400679@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
680def prune_lookups (self):
681 "Remove unreferenced lookups"
682 feature_indices = self.table.ScriptList.collect_features ()
683 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
684 lookup_indices = self.table.LookupList.closure_lookups (lookup_indices)
685 self.subset_lookups (lookup_indices)
686
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400687@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
688def subset_feature_tags (self, feature_tags):
689 feature_indices = [i for (i,f) in enumerate (self.table.FeatureList.FeatureRecord) if f.FeatureTag in feature_tags]
690 self.table.FeatureList.subset_features (feature_indices)
691 self.table.ScriptList.subset_features (feature_indices)
692
693@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400694def prune_pre_subset (self, options):
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400695 if options['layout-features'] and '*' not in options['layout-features']:
Behdad Esfahboded98c612013-07-23 12:37:41 -0400696 self.subset_feature_tags (options['layout-features'])
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400697 self.prune_lookups ()
698 return True
699
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400700@add_method(fontTools.ttLib.getTableClass('GDEF'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400701def subset_glyphs (self, glyphs):
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400702 table = self.table
703 if table.LigCaretList:
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400704 indices = table.LigCaretList.Coverage.subset_glyphs (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400705 table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i] for i in indices]
706 table.LigCaretList.LigGlyphCount = len (table.LigCaretList.LigGlyph)
707 if not table.LigCaretList.LigGlyphCount:
708 table.LigCaretList = None
709 if table.MarkAttachClassDef:
710 table.MarkAttachClassDef.classDefs = {g:v for g,v in table.MarkAttachClassDef.classDefs.items() if g in glyphs}
711 if not table.MarkAttachClassDef.classDefs:
712 table.MarkAttachClassDef = None
713 if table.GlyphClassDef:
714 table.GlyphClassDef.classDefs = {g:v for g,v in table.GlyphClassDef.classDefs.items() if g in glyphs}
715 if not table.GlyphClassDef.classDefs:
716 table.GlyphClassDef = None
717 if table.AttachList:
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400718 indices = table.AttachList.Coverage.subset_glyphs (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400719 table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i] for i in indices]
720 table.AttachList.GlyphCount = len (table.AttachList.AttachPoint)
721 if not table.AttachList.GlyphCount:
722 table.AttachList = None
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400723 return bool (table.LigCaretList or table.MarkAttachClassDef or table.GlyphClassDef or table.AttachList)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400724
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400725@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400726def subset_glyphs (self, glyphs):
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400727 for t in self.kernTables:
728 t.kernTable = {(a,b):v for ((a,b),v) in t.kernTable.items() if a in glyphs and b in glyphs}
729 self.kernTables = [t for t in self.kernTables if t.kernTable]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400730 return bool (self.kernTables)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400731
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400732@add_method(fontTools.ttLib.getTableClass('hmtx'), fontTools.ttLib.getTableClass('vmtx'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400733def subset_glyphs (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400734 self.metrics = {g:v for g,v in self.metrics.items() if g in glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400735 return bool (self.metrics)
Behdad Esfahbodc7160442013-07-22 14:29:08 -0400736
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400737@add_method(fontTools.ttLib.getTableClass('hdmx'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400738def subset_glyphs (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400739 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 -0400740 return bool (self.hdmx)
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400741
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400742@add_method(fontTools.ttLib.getTableClass('VORG'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400743def subset_glyphs (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400744 self.VOriginRecords = {g:v for g,v in self.VOriginRecords.items() if g in glyphs}
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400745 self.numVertOriginYMetrics = len (self.VOriginRecords)
746 return True # Never drop; has default metrics
747
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400748@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400749def prune_pre_subset (self, options):
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400750 if not options['glyph-names']:
Behdad Esfahbod42648242013-07-23 12:56:06 -0400751 self.formatType = 3.0
752 return True
753
754@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400755def subset_glyphs (self, glyphs):
Behdad Esfahbod42648242013-07-23 12:56:06 -0400756 self.extraNames = [] # This seems to do it
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -0400757 return True
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400758
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400759# Copied from _g_l_y_f.py
760ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes
761ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points
762ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true
763WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0
764NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!)
765MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one
766WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy
767WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11
768WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow
769USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph
770OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts
771SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple)
772UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS)
773
774@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
775def getComponentNamesFast (self, glyfTable):
776 if struct.unpack(">h", self.data[:2])[0] >= 0:
777 return [] # Not composite
778 data = self.data
779 i = 10
780 components = []
781 more = 1
782 while more:
783 flags, glyphID = struct.unpack(">HH", data[i:i+4])
784 i += 4
785 flags = int(flags)
786 components.append (glyfTable.getGlyphName (int (glyphID)))
787
788 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
789 else: i += 2
790 if flags & WE_HAVE_A_SCALE: i += 2
791 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
792 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
793 more = flags & MORE_COMPONENTS
794 return components
795
796@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
797def remapComponentsFast (self, indices):
798 if struct.unpack(">h", self.data[:2])[0] >= 0:
799 return # Not composite
800 data = bytearray (self.data)
801 i = 10
802 more = 1
803 while more:
804 flags = (data[i] << 8) | data[i+1]
805 glyphID = (data[i+2] << 8) | data[i+3]
806 # Remap
807 glyphID = indices.index (glyphID)
808 data[i+2] = glyphID >> 8
809 data[i+3] = glyphID & 0xFF
810 i += 4
811 flags = int(flags)
812
813 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
814 else: i += 2
815 if flags & WE_HAVE_A_SCALE: i += 2
816 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
817 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
818 more = flags & MORE_COMPONENTS
819 self.data = str (data)
820
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400821@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400822def closure_glyphs (self, glyphs):
823 glyphs = unique_sorted (glyphs)
824 decompose = glyphs
825 # I don't know if component glyphs can be composite themselves.
826 # We handle them anyway.
827 while True:
828 components = []
829 for g in decompose:
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400830 if g not in self.glyphs:
Behdad Esfahbodf8c20e42013-07-23 23:13:23 -0400831 continue
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400832 gl = self.glyphs[g]
833 if hasattr (gl, "data"):
834 for c in gl.getComponentNamesFast (self):
835 if c not in glyphs:
836 components.append (c)
837 else:
838 # TTX seems to expand gid0..3 always
839 if gl.isComposite ():
840 for c in gl.components:
841 if c.glyphName not in glyphs:
842 components.append (c.glyphName)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400843 components = [c for c in components if c not in glyphs]
844 if not components:
845 return glyphs
846 decompose = unique_sorted (components)
847 glyphs.extend (components)
848
849@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400850def subset_glyphs (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400851 self.glyphs = {g:v for g,v in self.glyphs.items() if g in glyphs}
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400852 indices = [i for i,g in enumerate (self.glyphOrder) if g in glyphs]
853 for v in self.glyphs.values ():
854 if hasattr (v, "data"):
855 v.remapComponentsFast (indices)
856 else:
857 pass # No need
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400858 self.glyphOrder = [g for g in self.glyphOrder if g in glyphs]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400859 return bool (self.glyphs)
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400860
Behdad Esfahboded98c612013-07-23 12:37:41 -0400861@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400862def prune_post_subset (self, options):
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400863 if not options['hinting']:
Behdad Esfahboded98c612013-07-23 12:37:41 -0400864 for g in self.glyphs.values ():
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400865 g.expand (self)
866 g.program = fontTools.ttLib.tables.ttProgram.Program()
867 g.program.fromBytecode([])
Behdad Esfahboded98c612013-07-23 12:37:41 -0400868 return True
869
Behdad Esfahbod2b677c82013-07-23 13:37:13 -0400870@add_method(fontTools.ttLib.getTableClass('CFF '))
871def subset_glyphs (self, glyphs):
872 assert 0, "unimplemented"
873
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400874@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400875def prune_pre_subset (self, options):
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400876 if not options['legacy-cmap']:
877 # Drop non-Unicode / non-Symbol cmaps
878 self.tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [0, 1, 10]]
879 if not options['symbol-cmap']:
880 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 -0400881 # TODO Only keep one subtable?
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400882 # For now, drop format=0 which can't be subset_glyphs easily?
883 self.tables = [t for t in self.tables if t.format != 0]
884 return bool (self.tables)
885
886@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod0716eb42013-07-23 10:47:03 -0400887def subset_glyphs (self, glyphs):
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400888 for t in self.tables:
Behdad Esfahbod9453a362013-07-22 16:21:24 -0400889 # For reasons I don't understand I need this here
890 # to force decompilation of the cmap format 14.
891 try:
892 getattr (t, "asdf")
893 except AttributeError:
894 pass
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400895 if t.format == 14:
Behdad Esfahbod9453a362013-07-22 16:21:24 -0400896 # XXX We drop all the default-UVS mappings (g==None)
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400897 t.uvsDict = {v:[(u,g) for (u,g) in l if g in glyphs] for (v,l) in t.uvsDict.items()}
898 t.uvsDict = {v:l for (v,l) in t.uvsDict.items() if l}
899 else:
900 t.cmap = {u:g for (u,g) in t.cmap.items() if g in glyphs}
901 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 -0400902 # XXX Convert formats when needed
Behdad Esfahbod61addb42013-07-23 11:03:49 -0400903 return bool (self.tables)
904
Behdad Esfahbod61addb42013-07-23 11:03:49 -0400905@add_method(fontTools.ttLib.getTableClass('name'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400906def prune_pre_subset (self, options):
Behdad Esfahbod20faeb02013-07-23 13:19:03 -0400907 if '*' not in options['name-IDs']:
908 self.names = [n for n in self.names if n.nameID in options['name-IDs']]
909 if not options['name-legacy']:
910 self.names = [n for n in self.names if n.platformID == 3 and n.platEncID == 1]
911 if '*' not in options['name-languages']:
912 self.names = [n for n in self.names if n.langID in options['name-languages']]
913 return True # Retain even if empty
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400914
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400915
Behdad Esfahbodbc25f162013-07-23 12:56:54 -0400916drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'PCLT', 'LTSH']
Behdad Esfahbod103a12f2013-07-23 15:08:39 -0400917drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill'] # Graphite
Behdad Esfahbod38e852c2013-07-23 16:56:50 -0400918drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL'] # Color
Behdad Esfahboded98c612013-07-23 12:37:41 -0400919no_subset_tables = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2', 'loca', 'name', 'cvt ', 'fpgm', 'prep']
Behdad Esfahbodbc25f162013-07-23 12:56:54 -0400920hinting_tables = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
Behdad Esfahbod29df0462013-07-23 11:05:25 -0400921
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400922# Based on HarfBuzz shapers
923layout_features_dict = {
924 # Default shaper
925 'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
926 'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
927 'vertical': ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
928 'ltr': ['ltra', 'ltrm'],
929 'rtl': ['rtla', 'rtlm'],
930 # Complex shapers
931 'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3'],
932 'hangul': ['ljmo', 'vjmo', 'tjmo'],
933 'tibetal': ['abvs', 'blws', 'abvm', 'blwm'],
934 'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half', 'abvf', 'pstf', 'cfar', 'vatu', 'cjct',
935 'init', 'pres', 'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
936}
937layout_features_all = unique_sorted (sum (layout_features_dict.values (), []))
938
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400939options_default = {
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400940 'drop-tables': drop_tables_default,
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400941 'layout-features': layout_features_all,
942 'hinting': False,
943 'glyph-names': False,
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400944 'legacy-cmap': False,
945 'symbol-cmap': False,
Behdad Esfahbod20faeb02013-07-23 13:19:03 -0400946 'name-IDs': [1, 2], # Family and Style
947 'name-legacy': False,
948 'name-languages': [0x0409], # English
Behdad Esfahbode30ed122013-07-23 21:08:29 -0400949 'mandatory-glyphs': True, # First four for TrueType, .notdef for CFF
Behdad Esfahbod4091ec62013-07-23 13:02:51 -0400950}
951
Behdad Esfahbod29df0462013-07-23 11:05:25 -0400952
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400953# TODO OS/2 ulUnicodeRange / ulCodePageRange?
Behdad Esfahbodf71267b2013-07-23 12:59:13 -0400954# TODO Drop unneeded GSUB/GPOS Script/LangSys entries
Behdad Esfahbod398d3892013-07-23 15:29:40 -0400955# TODO Avoid recursing too much
Behdad Esfahbode94aa0e2013-07-23 13:22:04 -0400956# TODO Text direction considerations
957# TODO Text script / language considerations
Behdad Esfahbod38e852c2013-07-23 16:56:50 -0400958# TODO Drop unknown tables
Behdad Esfahbod56ebd042013-07-22 13:02:24 -0400959
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400960
961def main ():
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400962
Behdad Esfahbodb70b4982013-07-23 11:38:26 -0400963 import sys, time
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400964 global last_time
Behdad Esfahbodb70b4982013-07-23 11:38:26 -0400965
966 start_time = time.time ()
967 last_time = start_time
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400968
Behdad Esfahbod4ae81712013-07-22 11:57:13 -0400969 verbose = False
970 if "--verbose" in sys.argv:
971 verbose = True
972 sys.argv.remove ("--verbose")
Behdad Esfahbod350a5272013-07-22 12:02:16 -0400973 xml = False
974 if "--xml" in sys.argv:
975 xml = True
976 sys.argv.remove ("--xml")
Behdad Esfahbodb70b4982013-07-23 11:38:26 -0400977 timing = False
978 if "--timing" in sys.argv:
979 timing = True
980 sys.argv.remove ("--timing")
981
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400982 options = options_default.copy ()
983
Behdad Esfahbodb70b4982013-07-23 11:38:26 -0400984 def lapse (what):
985 if not timing:
986 return
987 global last_time
988 new_time = time.time ()
989 print "Took %0.3fs to %s" % (new_time - last_time, what)
990 last_time = new_time
Behdad Esfahbod4ae81712013-07-22 11:57:13 -0400991
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400992 if len (sys.argv) < 3:
993 print >>sys.stderr, "usage: pyotlss.py font-file glyph..."
994 sys.exit (1)
995
996 fontfile = sys.argv[1]
997 glyphs = sys.argv[2:]
998
999 font = fontTools.ttx.TTFont (fontfile)
Behdad Esfahbod0f86ce92013-07-22 17:30:31 -04001000 font.disassembleInstructions = False
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001001 lapse ("load font")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001002
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001003 if options["mandatory-glyphs"]:
1004 # Always include .notdef; anything else?
1005 if 'glyf' in font:
1006 glyphs.extend (['gid0', 'gid1', 'gid2', 'gid3'])
1007 if verbose:
1008 print "Added first four glyphs to subset"
1009 else:
1010 glyphs.append ('.notdef')
1011 if verbose:
1012 print "Added .notdef glyph to subset"
1013
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001014 names = font.getGlyphNames()
Behdad Esfahbod9bd59c42013-07-23 21:19:49 -04001015 lapse ("loading glyph names")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001016 # Convert to glyph names
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001017 glyph_names = []
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001018 cmap_tables = None
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001019 for g in glyphs:
1020 if g in names:
1021 glyph_names.append (g)
1022 continue
Behdad Esfahbod7c225a62013-07-23 21:33:13 -04001023 if g.startswith ('uni') and len (g) > 3:
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001024 if not cmap_tables:
1025 cmap = font['cmap']
1026 cmap_tables = [t for t in cmap.tables if t.platformID == 3 and t.platEncID in [1, 10]]
1027 del cmap
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001028 found = False
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001029 u = int (g[3:], 16)
1030 for table in cmap_tables:
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001031 if u in table.cmap:
1032 glyph_names.append (table.cmap[u])
1033 found = True
1034 break
1035 if not found:
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001036 if verbose:
1037 print ("No glyph for Unicode value %s; skipping." % g)
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001038 continue
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001039 if g.startswith ('gid') or g.startswith ('glyph'):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -04001040 if g.startswith ('gid') and len (g) > 3:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001041 g = g[3:]
Behdad Esfahbod7c225a62013-07-23 21:33:13 -04001042 elif g.startswith ('glyph') and len (g) > 5:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001043 g = g[5:]
1044 try:
1045 glyph_names.append (font.getGlyphName (int (g), requireReal=1))
1046 except ValueError:
1047 raise Exception ("Invalid glyph identifier %s" % g)
1048 continue
1049 raise Exception ("Invalid glyph identifier %s" % g)
Behdad Esfahbode36061e2013-07-23 15:13:00 -04001050 del cmap_tables
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001051 glyphs = unique_sorted (glyph_names)
Behdad Esfahbod3f4b97e2013-07-23 15:04:25 -04001052 del glyph_names
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001053 lapse ("compile glyph list")
Behdad Esfahbod240d7e72013-07-23 23:12:06 -04001054 if verbose:
1055 print "Glyphs:", glyphs
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001056
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001057
1058 for tag in font.keys():
1059 if tag == 'GlyphOrder': continue
1060
1061 if tag in options['drop-tables'] or \
Behdad Esfahbodc0d59592013-07-24 14:41:47 -04001062 (tag in hinting_tables and not options['hinting']):
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001063 if verbose:
1064 print tag, "dropped."
1065 del font[tag]
1066 continue
1067
1068 clazz = fontTools.ttLib.getTableClass(tag)
1069
1070 if hasattr (clazz, 'prune_pre_subset'):
1071 table = font[tag]
1072 retain = table.prune_pre_subset (options)
1073 lapse ("prune '%s'" % tag)
1074 if not retain:
1075 if verbose:
1076 print tag, "pruned to empty; dropped."
1077 del font[tag]
1078 continue
1079 else:
1080 if verbose:
1081 print tag, "pruned."
1082
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001083 glyphs_requested = glyphs
1084 if 'GSUB' in font:
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001085 if verbose:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001086 print "Closing glyph list over 'GSUB': %d glyphs before" % len (glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001087 glyphs = font['GSUB'].closure_glyphs (glyphs)
1088 if verbose:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001089 print "Closed glyph list over 'GSUB': %d glyphs after" % len (glyphs)
Behdad Esfahbod240d7e72013-07-23 23:12:06 -04001090 print "Glyphs:", glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001091 lapse ("close glyph list over 'GSUB'")
1092 glyphs_gsubed = glyphs
1093
Behdad Esfahbod2a784ac2013-07-22 17:00:36 -04001094 # Close over composite glyphs
1095 if 'glyf' in font:
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001096 if verbose:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001097 print "Closing glyph list over 'glyf': %d glyphs before" % len (glyphs)
Behdad Esfahbod240d7e72013-07-23 23:12:06 -04001098 print "Glyphs:", glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001099 glyphs = font['glyf'].closure_glyphs (glyphs)
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001100 if verbose:
Behdad Esfahbode30ed122013-07-23 21:08:29 -04001101 print "Closed glyph list over 'glyf': %d glyphs after" % len (glyphs)
Behdad Esfahbod240d7e72013-07-23 23:12:06 -04001102 print "Glyphs:", glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001103 lapse ("close glyph list over 'glyf'")
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001104 else:
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001105 glyphs = glyphs
1106 glyphs_glyfed = glyphs
1107 glyphs_closed = glyphs
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001108 del glyphs
1109
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -04001110 if verbose:
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001111 print "Retaining %d glyphs: " % len (glyphs_closed)
Behdad Esfahbod2a784ac2013-07-22 17:00:36 -04001112
Behdad Esfahbod8842ce22013-07-22 13:01:33 -04001113 for tag in font.keys():
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001114 if tag == 'GlyphOrder': continue
Behdad Esfahbod4e214e42013-07-22 13:13:49 -04001115
Behdad Esfahbod8842ce22013-07-22 13:01:33 -04001116 clazz = fontTools.ttLib.getTableClass(tag)
Behdad Esfahbod4e214e42013-07-22 13:13:49 -04001117
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001118 if tag in no_subset_tables:
1119 if verbose:
1120 print tag, "subsetting not needed."
Behdad Esfahbod96f47042013-07-23 12:21:34 -04001121 elif hasattr (clazz, 'subset_glyphs'):
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001122 table = font[tag]
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001123 if tag == 'cmap': # What else?
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001124 glyphs = glyphs_requested
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001125 elif tag in ['GSUB', 'GPOS', 'GDEF', 'cmap', 'kern', 'post']: # What else?
1126 glyphs = glyphs_gsubed
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001127 else:
1128 glyphs = glyphs_closed
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001129 retain = table.subset_glyphs (glyphs)
1130 lapse ("subset '%s'" % tag)
1131 if not retain:
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001132 if verbose:
1133 print tag, "subsetted to empty; dropped."
Behdad Esfahbod8b411f32013-07-23 11:24:20 -04001134 del font[tag]
1135 continue
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001136 else:
1137 if verbose:
1138 print tag, "subsetted."
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001139 del glyphs
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001140 else:
Behdad Esfahbod350a5272013-07-22 12:02:16 -04001141 if verbose:
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001142 print tag, "NOT subset; don't know how to subset."
1143 continue
1144
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -04001145 if hasattr (clazz, 'prune_post_subset'):
1146 table = font[tag]
1147 retain = table.prune_post_subset (options)
1148 lapse ("prune '%s'" % tag)
1149 if not retain:
1150 if verbose:
1151 print tag, "pruned to empty; dropped."
1152 del font[tag]
1153 continue
1154 else:
1155 if verbose:
1156 print tag, "pruned."
1157
Behdad Esfahbodc7160442013-07-22 14:29:08 -04001158 glyphOrder = font.getGlyphOrder()
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04001159 glyphOrder = [g for g in glyphOrder if g in glyphs_closed]
Behdad Esfahbodc7160442013-07-22 14:29:08 -04001160 font.setGlyphOrder (glyphOrder)
1161 font._buildReverseGlyphOrderDict ()
Behdad Esfahbodb70b4982013-07-23 11:38:26 -04001162 lapse ("subset GlyphOrder")
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -04001163
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001164 font.save (fontfile + '.subset')
1165 lapse ("compile and save font")
1166
1167 last_time = start_time
1168 lapse ("make one with everything (TOTAL TIME)")
1169
Behdad Esfahbod0f86ce92013-07-22 17:30:31 -04001170 if xml:
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001171 import xmlWriter
1172 writer = xmlWriter.XMLWriter (sys.stdout)
1173
Behdad Esfahbod0f86ce92013-07-22 17:30:31 -04001174 for tag in font.keys():
1175 writer.begintag (tag)
1176 writer.newline ()
1177 font[tag].toXML(writer, font)
1178 writer.endtag (tag)
1179 writer.newline ()
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001180
1181if __name__ == '__main__':
1182 main ()