blob: 9d0d185506fc3ce4d89c1e667fd91b3c66630b00 [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
Behdad Esfahbod97e17b82013-07-31 15:59:21 -040042def safeEval(data, eval=eval):
43 """A (kindof) safe replacement for eval."""
44 return eval(data, {"__builtins__":{}}, {})
45
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040046
Behdad Esfahbod54660612013-07-21 18:16:55 -040047@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040048def intersect (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -040049 "Returns ascending list of matching coverage values."
50 return [i for (i,g) in enumerate (self.glyphs) if g in glyphs]
51
52@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040053def subset (self, glyphs):
Behdad Esfahbodd821ea02013-07-23 10:50:43 -040054 "Returns ascending list of remaining coverage values."
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040055 indices = self.intersect (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -040056 self.glyphs = [g for g in self.glyphs if g in glyphs]
57 return indices
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040058
Behdad Esfahbod54660612013-07-21 18:16:55 -040059@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040060def intersect (self, glyphs):
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040061 "Returns ascending list of matching class values."
62 return unique_sorted (v for g,v in self.classDefs.items() if g in glyphs)
63
64@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040065def intersects_class (self, glyphs, klass):
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040066 "Returns true if any of glyphs has requested class."
67 return any (g in glyphs for g,v in self.classDefs.items() if v == klass)
68
69@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040070def subset (self, glyphs, remap=False):
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -040071 "Returns ascending list of remaining classes."
Behdad Esfahbod54660612013-07-21 18:16:55 -040072 self.classDefs = {g:v for g,v in self.classDefs.items() if g in glyphs}
Behdad Esfahbodde71dca2013-07-24 12:40:54 -040073 indices = unique_sorted (self.classDefs.values ())
74 if remap:
75 self.remap (indices)
76 return indices
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -040077
78@add_method(fontTools.ttLib.tables.otTables.ClassDef)
79def remap (self, class_map):
80 "Remaps classes."
81 self.classDefs = {g:class_map.index (v) for g,v in self.classDefs.items()}
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040082
Behdad Esfahbod54660612013-07-21 18:16:55 -040083@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -040084def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -040085 if self.Format in [1, 2]:
Behdad Esfahbod254442b2013-07-31 14:20:13 -040086 return [v for g,v in self.mapping.items() if g in s.glyphs]
Behdad Esfahbod610b0552013-07-23 14:52:18 -040087 else:
88 assert 0, "unknown format: %s" % self.Format
89
90@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -040091def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -040092 if self.Format in [1, 2]:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -040093 self.mapping = {g:v for g,v in self.mapping.items() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -040094 return bool (self.mapping)
Behdad Esfahbod54660612013-07-21 18:16:55 -040095 else:
96 assert 0, "unknown format: %s" % self.Format
97
98@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -040099def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400100 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400101 indices = self.Coverage.intersect (s.glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400102 return sum ((self.Sequence[i].Substitute for i in indices), [])
103 else:
104 assert 0, "unknown format: %s" % self.Format
105
106@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400107def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400108 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400109 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400110 self.Sequence = [self.Sequence[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400111 self.SequenceCount = len (self.Sequence)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400112 return bool (self.SequenceCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400113 else:
114 assert 0, "unknown format: %s" % self.Format
115
116@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400117def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400118 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400119 return sum ((v for g,v in self.alternates.items() if g in s.glyphs), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400120 else:
121 assert 0, "unknown format: %s" % self.Format
122
123@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400124def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400125 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400126 self.alternates = {g:v for g,v in self.alternates.items() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400127 return bool (self.alternates)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400128 else:
129 assert 0, "unknown format: %s" % self.Format
130
131@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400132def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400133 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400134 return sum (([seq.LigGlyph for seq in seqs if all(c in s.glyphs for c in seq.Component)]
135 for g,seqs in self.ligatures.items() if g in s.glyphs), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400136 else:
137 assert 0, "unknown format: %s" % self.Format
138
139@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400140def subset_glyphs (self, s):
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400141 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400142 self.ligatures = {g:v for g,v in self.ligatures.items() if g in s.glyphs}
143 self.ligatures = {g:[seq for seq in seqs if all(c in s.glyphs for c in seq.Component)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400144 for g,seqs in self.ligatures.items()}
145 self.ligatures = {g:v for g,v in self.ligatures.items() if v}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400146 return bool (self.ligatures)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400147 else:
148 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400149
Behdad Esfahbod54660612013-07-21 18:16:55 -0400150@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400151def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400152 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400153 indices = self.Coverage.intersect (s.glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400154 if not indices or \
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400155 not all (c.intersect (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400156 return []
157 return [self.Substitute[i] for i in indices]
158 else:
159 assert 0, "unknown format: %s" % self.Format
160
161@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400162def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400163 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400164 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400165 self.Substitute = [self.Substitute[i] for i in indices]
166 self.GlyphCount = len (self.Substitute)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400167 return bool (self.GlyphCount and all (c.subset (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400168 else:
169 assert 0, "unknown format: %s" % self.Format
170
171@add_method(fontTools.ttLib.tables.otTables.SinglePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400172def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400173 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400174 return len (self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400175 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400176 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400177 self.Value = [self.Value[i] for i in indices]
178 self.ValueCount = len (self.Value)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400179 return bool (self.ValueCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400180 else:
181 assert 0, "unknown format: %s" % self.Format
182
183@add_method(fontTools.ttLib.tables.otTables.PairPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400184def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400185 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400186 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400187 self.PairSet = [self.PairSet[i] for i in indices]
188 for p in self.PairSet:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400189 p.PairValueRecord = [r for r in p.PairValueRecord if r.SecondGlyph in s.glyphs]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400190 p.PairValueCount = len (p.PairValueRecord)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400191 self.PairSet = [p for p in self.PairSet if p.PairValueCount]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400192 self.PairSetCount = len (self.PairSet)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400193 return bool (self.PairSetCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400194 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400195 class1_map = self.ClassDef1.subset (s.glyphs, remap=True)
196 class2_map = self.ClassDef2.subset (s.glyphs, remap=True)
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -0400197 self.Class1Record = [self.Class1Record[i] for i in class1_map]
198 for c in self.Class1Record:
199 c.Class2Record = [c.Class2Record[i] for i in class2_map]
200 self.Class1Count = len (class1_map)
201 self.Class2Count = len (class2_map)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400202 return bool (self.Class1Count and self.Class2Count and self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400203 else:
204 assert 0, "unknown format: %s" % self.Format
205
206@add_method(fontTools.ttLib.tables.otTables.CursivePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400207def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400208 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400209 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400210 self.EntryExitRecord = [self.EntryExitRecord[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400211 self.EntryExitCount = len (self.EntryExitRecord)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400212 return bool (self.EntryExitCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400213 else:
214 assert 0, "unknown format: %s" % self.Format
215
216@add_method(fontTools.ttLib.tables.otTables.MarkBasePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400217def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400218 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400219 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400220 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
221 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400222 base_indices = self.BaseCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400223 self.BaseArray.BaseRecord = [self.BaseArray.BaseRecord[i] for i in base_indices]
224 self.BaseArray.BaseCount = len (self.BaseArray.BaseRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400225 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400226 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400227 self.ClassCount = len (class_indices)
228 for m in self.MarkArray.MarkRecord:
229 m.Class = class_indices.index (m.Class)
230 for b in self.BaseArray.BaseRecord:
231 b.BaseAnchor = [b.BaseAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400232 return bool (self.ClassCount and self.MarkArray.MarkCount and self.BaseArray.BaseCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400233 else:
234 assert 0, "unknown format: %s" % self.Format
235
236@add_method(fontTools.ttLib.tables.otTables.MarkLigPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400237def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400238 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400239 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400240 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
241 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400242 ligature_indices = self.LigatureCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400243 self.LigatureArray.LigatureAttach = [self.LigatureArray.LigatureAttach[i] for i in ligature_indices]
244 self.LigatureArray.LigatureCount = len (self.LigatureArray.LigatureAttach)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400245 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400246 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400247 self.ClassCount = len (class_indices)
248 for m in self.MarkArray.MarkRecord:
249 m.Class = class_indices.index (m.Class)
250 for l in self.LigatureArray.LigatureAttach:
251 for c in l.ComponentRecord:
252 c.LigatureAnchor = [c.LigatureAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400253 return bool (self.ClassCount and self.MarkArray.MarkCount and self.LigatureArray.LigatureCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400254 else:
255 assert 0, "unknown format: %s" % self.Format
256
257@add_method(fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400258def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400259 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400260 mark1_indices = self.Mark1Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400261 self.Mark1Array.MarkRecord = [self.Mark1Array.MarkRecord[i] for i in mark1_indices]
262 self.Mark1Array.MarkCount = len (self.Mark1Array.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400263 mark2_indices = self.Mark2Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400264 self.Mark2Array.Mark2Record = [self.Mark2Array.Mark2Record[i] for i in mark2_indices]
265 self.Mark2Array.MarkCount = len (self.Mark2Array.Mark2Record)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400266 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400267 class_indices = unique_sorted (v.Class for v in self.Mark1Array.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400268 self.ClassCount = len (class_indices)
269 for m in self.Mark1Array.MarkRecord:
270 m.Class = class_indices.index (m.Class)
271 for b in self.Mark2Array.Mark2Record:
272 b.Mark2Anchor = [b.Mark2Anchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400273 return bool (self.ClassCount and self.Mark1Array.MarkCount and self.Mark2Array.MarkCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400274 else:
275 assert 0, "unknown format: %s" % self.Format
276
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400277@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
278 fontTools.ttLib.tables.otTables.MultipleSubst,
279 fontTools.ttLib.tables.otTables.AlternateSubst,
280 fontTools.ttLib.tables.otTables.LigatureSubst,
281 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
282 fontTools.ttLib.tables.otTables.SinglePos,
283 fontTools.ttLib.tables.otTables.PairPos,
284 fontTools.ttLib.tables.otTables.CursivePos,
285 fontTools.ttLib.tables.otTables.MarkBasePos,
286 fontTools.ttLib.tables.otTables.MarkLigPos,
287 fontTools.ttLib.tables.otTables.MarkMarkPos)
288def subset_lookups (self, lookup_indices):
289 pass
290
291@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
292 fontTools.ttLib.tables.otTables.MultipleSubst,
293 fontTools.ttLib.tables.otTables.AlternateSubst,
294 fontTools.ttLib.tables.otTables.LigatureSubst,
295 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
296 fontTools.ttLib.tables.otTables.SinglePos,
297 fontTools.ttLib.tables.otTables.PairPos,
298 fontTools.ttLib.tables.otTables.CursivePos,
299 fontTools.ttLib.tables.otTables.MarkBasePos,
300 fontTools.ttLib.tables.otTables.MarkLigPos,
301 fontTools.ttLib.tables.otTables.MarkMarkPos)
302def collect_lookups (self):
303 return []
304
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400305@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
306 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
307def __classify_context (self):
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400308
309 class ContextHelper:
310 def __init__ (self, klass, Format):
311 if klass.__name__.endswith ('Subst'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400312 Typ = 'Sub'
313 Type = 'Subst'
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400314 else:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400315 Typ = 'Pos'
316 Type = 'Pos'
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400317 if klass.__name__.startswith ('Chain'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400318 Chain = 'Chain'
319 else:
320 Chain = ''
321 ChainTyp = Chain+Typ
322
323 self.Typ = Typ
324 self.Type = Type
325 self.Chain = Chain
326 self.ChainTyp = ChainTyp
327
328 self.LookupRecord = Type+'LookupRecord'
329
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400330 if Format == 1:
331 ContextData = None
332 ChainContextData = None
333 RuleData = lambda r: r.Input
334 ChainRuleData = lambda r: r.Backtrack + r.Input + r.LookAhead
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400335 SetRuleData = None
336 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400337 elif Format == 2:
Behdad Esfahbode3f20732013-07-24 11:26:43 -0400338 ContextData = lambda r: (r.ClassDef,)
339 ChainContextData = lambda r: (r.LookAheadClassDef, r.InputClassDef, r.BacktrackClassDef)
340 RuleData = lambda r: (r.Class,)
341 ChainRuleData = lambda r: (r.LookAhead, r.Input, r.Backtrack)
342 def SetRuleData (r, d): (r.Class,) = d
343 def ChainSetRuleData (r, d): (r.LookAhead, r.Input, r.Backtrack) = d
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400344 elif Format == 3:
345 ContextData = None
346 ChainContextData = None
347 RuleData = lambda r: r.Coverage
348 ChainRuleData = lambda r: r.LookAheadCoverage + r.InputCoverage + r.BacktrackCoverage
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400349 SetRuleData = None
350 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400351 else:
352 assert 0, "unknown format: %s" % Format
353
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400354 if Chain:
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400355 self.ContextData = ChainContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400356 self.RuleData = ChainRuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400357 self.SetRuleData = ChainSetRuleData
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400358 else:
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400359 self.ContextData = ContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400360 self.RuleData = RuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400361 self.SetRuleData = SetRuleData
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400362
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400363 if Format == 1:
364 self.Rule = ChainTyp+'Rule'
365 self.RuleCount = ChainTyp+'RuleCount'
366 self.RuleSet = ChainTyp+'RuleSet'
367 self.RuleSetCount = ChainTyp+'RuleSetCount'
368 elif Format == 2:
369 self.Rule = ChainTyp+'ClassRule'
370 self.RuleCount = ChainTyp+'ClassRuleCount'
371 self.RuleSet = ChainTyp+'ClassSet'
372 self.RuleSetCount = ChainTyp+'ClassSetCount'
Behdad Esfahbod89987002013-07-23 23:07:42 -0400373
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400374 self.ClassDef = 'InputClassDef' if Chain else 'ClassDef'
Behdad Esfahbod27108392013-07-23 16:40:47 -0400375
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400376 if self.Format not in [1, 2, 3]:
377 return None # Don't shoot the messenger; let it go
378 if not hasattr (self.__class__, "__ContextHelpers"):
379 self.__class__.__ContextHelpers = {}
380 if self.Format not in self.__class__.__ContextHelpers:
381 self.__class__.__ContextHelpers[self.Format] = ContextHelper (self.__class__, self.Format)
382 return self.__class__.__ContextHelpers[self.Format]
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400383
Behdad Esfahbodf2b6d9c2013-07-23 17:31:54 -0400384@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400385def closure_glyphs (self, s):
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400386 c = self.__classify_context ()
387
Behdad Esfahbod00776972013-07-23 15:33:00 -0400388 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400389 indices = self.Coverage.intersect (s.glyphs)
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400390 rss = getattr (self, c.RuleSet)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400391 return sum ((s.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs (s) \
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400392 for i in indices \
393 for r in getattr (rss[i], c.Rule) \
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400394 if r and all (g in s.glyphs for g in c.RuleData (r)) \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400395 for ll in getattr (r, c.LookupRecord) if ll \
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400396 ), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400397 elif self.Format == 2:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400398 if not self.Coverage.intersect (s.glyphs):
Behdad Esfahbod31084302013-07-23 22:22:38 -0400399 return []
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400400 indices = getattr (self, c.ClassDef).intersect (s.glyphs)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400401 rss = getattr (self, c.RuleSet)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400402 return sum ((s.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs (s) \
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400403 for i in indices \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400404 for r in getattr (rss[i], c.Rule) \
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400405 if r and all (cd.intersects_class (s.glyphs, k) \
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400406 for cd,k in zip (c.ContextData (self), c.RuleData (r))) \
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400407 for ll in getattr (r, c.LookupRecord) if ll \
408 ), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400409 elif self.Format == 3:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400410 if not all (x.intersect (s.glyphs) for x in c.RuleData (self)):
Behdad Esfahbod00776972013-07-23 15:33:00 -0400411 return []
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400412 return sum ((s.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs (s) \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400413 for ll in getattr (self, c.LookupRecord) if ll), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400414 else:
415 assert 0, "unknown format: %s" % self.Format
416
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400417@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ContextPos,
418 fontTools.ttLib.tables.otTables.ChainContextSubst, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400419def subset_glyphs (self, s):
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400420 c = self.__classify_context ()
421
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400422 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400423 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400424 rss = getattr (self, c.RuleSet)
425 rss = [rss[i] for i in indices]
426 for rs in rss:
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400427 if rs:
428 ss = getattr (rs, c.Rule)
429 ss = [r for r in ss \
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400430 if r and all (g in s.glyphs for g in c.RuleData (r))]
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400431 setattr (rs, c.Rule, ss)
432 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400433 # Prune empty subrulesets
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400434 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400435 setattr (self, c.RuleSet, rss)
436 setattr (self, c.RuleSetCount, len (rss))
437 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400438 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400439 if not self.Coverage.subset (s.glyphs):
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400440 return False
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400441 indices = getattr (self, c.ClassDef).intersect (s.glyphs)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400442 rss = getattr (self, c.RuleSet)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400443 rss = [rss[i] for i in indices]
444 ContextData = c.ContextData (self)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400445 klass_maps = [x.subset (s.glyphs, remap=True) for x in ContextData]
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400446 for rs in rss:
447 if rs:
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400448 ss = getattr (rs, c.Rule)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400449 ss = [r for r in ss \
450 if r and all (k in klass_map \
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400451 for klass_map,k in zip (klass_maps, c.RuleData (r)))]
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400452 setattr (rs, c.Rule, ss)
453 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400454
455 # Remap rule classes
456 for r in ss:
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400457 c.SetRuleData (r, (klass_map.index (k) \
458 for klassmap,k in zip (klass_maps, c.RuleData (r))))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400459 # Prune empty subrulesets
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400460 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
461 setattr (self, c.RuleSet, rss)
462 setattr (self, c.RuleSetCount, len (rss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400463 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400464 elif self.Format == 3:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400465 return all (x.subset (s.glyphs) for x in c.RuleData (self))
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400466 else:
467 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400468
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400469@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
470 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400471def subset_lookups (self, lookup_indices):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400472 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400473
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400474 if self.Format in [1, 2]:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400475 for rs in getattr (self, c.RuleSet):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400476 if rs:
477 for r in getattr (rs, c.Rule):
478 if r:
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400479 setattr (r, c.LookupRecord, [ll for ll in getattr (r, c.LookupRecord) if ll \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400480 if ll.LookupListIndex in lookup_indices])
481 for ll in getattr (r, c.LookupRecord):
482 if ll:
483 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400484 elif self.Format == 3:
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400485 setattr (self, c.LookupRecord, [ll for ll in getattr (self, c.LookupRecord) if ll \
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400486 if ll.LookupListIndex in lookup_indices])
487 for ll in getattr (self, c.LookupRecord):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400488 if ll:
489 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400490 else:
491 assert 0, "unknown format: %s" % self.Format
492
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400493@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
494 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400495def collect_lookups (self):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400496 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400497
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400498 if self.Format in [1, 2]:
Behdad Esfahbod27108392013-07-23 16:40:47 -0400499 return [ll.LookupListIndex \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400500 for rs in getattr (self, c.RuleSet) if rs \
501 for r in getattr (rs, c.Rule) if r \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400502 for ll in getattr (r, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400503 elif self.Format == 3:
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400504 return [ll.LookupListIndex \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400505 for ll in getattr (self, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400506 else:
507 assert 0, "unknown format: %s" % self.Format
508
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400509@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400510def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400511 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400512 return self.ExtSubTable.closure_glyphs (s)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400513 else:
514 assert 0, "unknown format: %s" % self.Format
515
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400516@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400517def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400518 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400519 return self.ExtSubTable.subset_glyphs (s)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400520 else:
521 assert 0, "unknown format: %s" % self.Format
522
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400523@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
524def subset_lookups (self, lookup_indices):
525 if self.Format == 1:
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400526 return self.ExtSubTable.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400527 else:
528 assert 0, "unknown format: %s" % self.Format
529
530@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
531def collect_lookups (self):
532 if self.Format == 1:
533 return self.ExtSubTable.collect_lookups ()
534 else:
535 assert 0, "unknown format: %s" % self.Format
536
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400537@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400538def closure_glyphs (self, s):
539 return sum ((st.closure_glyphs (s) for st in self.SubTable if st), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400540
541@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400542def subset_glyphs (self, s):
543 self.SubTable = [st for st in self.SubTable if st and st.subset_glyphs (s)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400544 self.SubTableCount = len (self.SubTable)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400545 return bool (self.SubTableCount)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400546
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400547@add_method(fontTools.ttLib.tables.otTables.Lookup)
548def subset_lookups (self, lookup_indices):
549 for s in self.SubTable:
550 s.subset_lookups (lookup_indices)
551
552@add_method(fontTools.ttLib.tables.otTables.Lookup)
553def collect_lookups (self):
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400554 return unique_sorted (sum ((st.collect_lookups () for st in self.SubTable if st), []))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400555
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400556@add_method(fontTools.ttLib.tables.otTables.LookupList)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400557def subset_glyphs (self, s):
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400558 "Returns the indices of nonempty lookups."
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400559 return [i for (i,l) in enumerate (self.Lookup) if l and l.subset_glyphs (s)]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400560
561@add_method(fontTools.ttLib.tables.otTables.LookupList)
562def subset_lookups (self, lookup_indices):
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400563 self.Lookup = [self.Lookup[i] for i in lookup_indices if i < self.LookupCount]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400564 self.LookupCount = len (self.Lookup)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400565 for l in self.Lookup:
566 l.subset_lookups (lookup_indices)
567
568@add_method(fontTools.ttLib.tables.otTables.LookupList)
569def closure_lookups (self, lookup_indices):
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400570 lookup_indices = unique_sorted (lookup_indices)
571 recurse = lookup_indices
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400572 while True:
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400573 recurse_lookups = sum ((self.Lookup[i].collect_lookups () for i in recurse if i < self.LookupCount), [])
574 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 -0400575 if not recurse_lookups:
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400576 return unique_sorted (lookup_indices)
577 recurse_lookups = unique_sorted (recurse_lookups)
578 lookup_indices.extend (recurse_lookups)
579 recurse = recurse_lookups
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400580
581@add_method(fontTools.ttLib.tables.otTables.Feature)
582def subset_lookups (self, lookup_indices):
583 self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices]
584 # Now map them.
585 self.LookupListIndex = [lookup_indices.index (l) for l in self.LookupListIndex]
586 self.LookupCount = len (self.LookupListIndex)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400587 return self.LookupCount
Behdad Esfahbod54660612013-07-21 18:16:55 -0400588
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400589@add_method(fontTools.ttLib.tables.otTables.Feature)
590def collect_lookups (self):
591 return self.LookupListIndex[:]
592
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400593@add_method(fontTools.ttLib.tables.otTables.FeatureList)
594def subset_lookups (self, lookup_indices):
595 "Returns the indices of nonempty features."
596 feature_indices = [i for (i,f) in enumerate (self.FeatureRecord) if f.Feature.subset_lookups (lookup_indices)]
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400597 self.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400598 return feature_indices
599
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400600@add_method(fontTools.ttLib.tables.otTables.FeatureList)
601def collect_lookups (self, feature_indices):
602 return unique_sorted (sum ((self.FeatureRecord[i].Feature.collect_lookups () for i in feature_indices
603 if i < self.FeatureCount), []))
604
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400605@add_method(fontTools.ttLib.tables.otTables.FeatureList)
606def subset_features (self, feature_indices):
607 self.FeatureRecord = [self.FeatureRecord[i] for i in feature_indices]
608 self.FeatureCount = len (self.FeatureRecord)
609 return bool (self.FeatureCount)
610
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400611@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
612def subset_features (self, feature_indices):
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400613 if self.ReqFeatureIndex in feature_indices:
614 self.ReqFeatureIndex = feature_indices.index (self.ReqFeatureIndex)
615 else:
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400616 self.ReqFeatureIndex = 65535
617 self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400618 # Now map them.
619 self.FeatureIndex = [feature_indices.index (f) for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400620 self.FeatureCount = len (self.FeatureIndex)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400621 return bool (self.FeatureCount or self.ReqFeatureIndex != 65535)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400622
623@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
624def collect_features (self):
625 feature_indices = self.FeatureIndex[:]
626 if self.ReqFeatureIndex != 65535:
627 feature_indices.append (self.ReqFeatureIndex)
628 return unique_sorted (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400629
630@add_method(fontTools.ttLib.tables.otTables.Script)
631def subset_features (self, feature_indices):
632 if self.DefaultLangSys and not self.DefaultLangSys.subset_features (feature_indices):
633 self.DefaultLangSys = None
634 self.LangSysRecord = [l for l in self.LangSysRecord if l.LangSys.subset_features (feature_indices)]
635 self.LangSysCount = len (self.LangSysRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400636 return bool (self.LangSysCount or self.DefaultLangSys)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400637
638@add_method(fontTools.ttLib.tables.otTables.Script)
639def collect_features (self):
Behdad Esfahbod2307c8b2013-07-23 11:18:13 -0400640 feature_indices = [l.LangSys.collect_features () for l in self.LangSysRecord]
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400641 if self.DefaultLangSys:
642 feature_indices.append (self.DefaultLangSys.collect_features ())
643 return unique_sorted (sum (feature_indices, []))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400644
645@add_method(fontTools.ttLib.tables.otTables.ScriptList)
646def subset_features (self, feature_indices):
647 self.ScriptRecord = [s for s in self.ScriptRecord if s.Script.subset_features (feature_indices)]
648 self.ScriptCount = len (self.ScriptRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400649 return bool (self.ScriptCount)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400650
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400651@add_method(fontTools.ttLib.tables.otTables.ScriptList)
652def collect_features (self):
653 return unique_sorted (sum ((s.Script.collect_features () for s in self.ScriptRecord), []))
654
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400655@add_method(fontTools.ttLib.getTableClass('GSUB'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400656def closure_glyphs (self, s):
657 s.table = self.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400658 feature_indices = self.table.ScriptList.collect_features ()
659 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400660 orig_glyphs = s.glyphs
661 glyphs = unique_sorted (s.glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400662 while True:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400663 s.glyphs = glyphs
664 additions = (sum ((self.table.LookupList.Lookup[i].closure_glyphs (s) \
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400665 for i in lookup_indices if i < self.table.LookupList.LookupCount), []))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400666 additions = unique_sorted (g for g in additions if g not in glyphs)
667 if not additions:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400668 s.glyphs = orig_glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400669 return glyphs
670 glyphs.extend (additions)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400671 del s.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400672
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400673@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400674def subset_glyphs (self, s):
675 lookup_indices = self.table.LookupList.subset_glyphs (s)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400676 self.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400677 self.prune_lookups ()
678 return True
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400679
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400680@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400681def subset_lookups (self, lookup_indices):
682 "Retrains specified lookups, then removes empty features, language systems, and scripts."
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400683 self.table.LookupList.subset_lookups (lookup_indices)
684 feature_indices = self.table.FeatureList.subset_lookups (lookup_indices)
685 self.table.ScriptList.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400686
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400687@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
688def prune_lookups (self):
689 "Remove unreferenced lookups"
690 feature_indices = self.table.ScriptList.collect_features ()
691 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
692 lookup_indices = self.table.LookupList.closure_lookups (lookup_indices)
693 self.subset_lookups (lookup_indices)
694
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400695@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
696def subset_feature_tags (self, feature_tags):
697 feature_indices = [i for (i,f) in enumerate (self.table.FeatureList.FeatureRecord) if f.FeatureTag in feature_tags]
698 self.table.FeatureList.subset_features (feature_indices)
699 self.table.ScriptList.subset_features (feature_indices)
700
701@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400702def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400703 if options.layout_features and '*' not in options.layout_features:
704 self.subset_feature_tags (options.layout_features)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400705 self.prune_lookups ()
706 return True
707
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400708@add_method(fontTools.ttLib.getTableClass('GDEF'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400709def subset_glyphs (self, s):
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400710 table = self.table
711 if table.LigCaretList:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400712 indices = table.LigCaretList.Coverage.subset (s.glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400713 table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i] for i in indices]
714 table.LigCaretList.LigGlyphCount = len (table.LigCaretList.LigGlyph)
715 if not table.LigCaretList.LigGlyphCount:
716 table.LigCaretList = None
717 if table.MarkAttachClassDef:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400718 table.MarkAttachClassDef.classDefs = {g:v for g,v in table.MarkAttachClassDef.classDefs.items() if g in s.glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400719 if not table.MarkAttachClassDef.classDefs:
720 table.MarkAttachClassDef = None
721 if table.GlyphClassDef:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400722 table.GlyphClassDef.classDefs = {g:v for g,v in table.GlyphClassDef.classDefs.items() if g in s.glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400723 if not table.GlyphClassDef.classDefs:
724 table.GlyphClassDef = None
725 if table.AttachList:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400726 indices = table.AttachList.Coverage.subset (s.glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400727 table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i] for i in indices]
728 table.AttachList.GlyphCount = len (table.AttachList.AttachPoint)
729 if not table.AttachList.GlyphCount:
730 table.AttachList = None
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400731 return bool (table.LigCaretList or table.MarkAttachClassDef or table.GlyphClassDef or table.AttachList)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400732
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400733@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbodd4e33a72013-07-24 18:51:05 -0400734def prune_pre_subset (self, options):
735 # Prune unknown kern table types
736 self.kernTables = [t for t in self.kernTables if hasattr (t, 'kernTable')]
737 return bool (self.kernTables)
738
739@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400740def subset_glyphs (self, s):
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400741 for t in self.kernTables:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400742 t.kernTable = {(a,b):v for ((a,b),v) in t.kernTable.items() if a in s.glyphs and b in s.glyphs}
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400743 self.kernTables = [t for t in self.kernTables if t.kernTable]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400744 return bool (self.kernTables)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400745
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400746@add_method(fontTools.ttLib.getTableClass('hmtx'), fontTools.ttLib.getTableClass('vmtx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400747def subset_glyphs (self, s):
748 self.metrics = {g:v for g,v in self.metrics.items() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400749 return bool (self.metrics)
Behdad Esfahbodc7160442013-07-22 14:29:08 -0400750
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400751@add_method(fontTools.ttLib.getTableClass('hdmx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400752def subset_glyphs (self, s):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400753 self.hdmx = {sz:{g:v for g,v in l.items() if g in s.glyphs} for (sz,l) in self.hdmx.items()}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400754 return bool (self.hdmx)
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400755
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400756@add_method(fontTools.ttLib.getTableClass('VORG'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400757def subset_glyphs (self, s):
758 self.VOriginRecords = {g:v for g,v in self.VOriginRecords.items() if g in s.glyphs}
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400759 self.numVertOriginYMetrics = len (self.VOriginRecords)
760 return True # Never drop; has default metrics
761
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400762@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400763def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400764 if not options.glyph_names:
Behdad Esfahbod42648242013-07-23 12:56:06 -0400765 self.formatType = 3.0
766 return True
767
768@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400769def subset_glyphs (self, s):
Behdad Esfahbod42648242013-07-23 12:56:06 -0400770 self.extraNames = [] # This seems to do it
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -0400771 return True
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400772
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400773# Copied from _g_l_y_f.py
774ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes
775ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points
776ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true
777WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0
778NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!)
779MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one
780WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy
781WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11
782WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow
783USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph
784OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts
785SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple)
786UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS)
787
788@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
789def getComponentNamesFast (self, glyfTable):
790 if struct.unpack(">h", self.data[:2])[0] >= 0:
791 return [] # Not composite
792 data = self.data
793 i = 10
794 components = []
795 more = 1
796 while more:
797 flags, glyphID = struct.unpack(">HH", data[i:i+4])
798 i += 4
799 flags = int(flags)
800 components.append (glyfTable.getGlyphName (int (glyphID)))
801
802 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
803 else: i += 2
804 if flags & WE_HAVE_A_SCALE: i += 2
805 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
806 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
807 more = flags & MORE_COMPONENTS
808 return components
809
810@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
811def remapComponentsFast (self, indices):
812 if struct.unpack(">h", self.data[:2])[0] >= 0:
813 return # Not composite
814 data = bytearray (self.data)
815 i = 10
816 more = 1
817 while more:
818 flags = (data[i] << 8) | data[i+1]
819 glyphID = (data[i+2] << 8) | data[i+3]
820 # Remap
821 glyphID = indices.index (glyphID)
822 data[i+2] = glyphID >> 8
823 data[i+3] = glyphID & 0xFF
824 i += 4
825 flags = int(flags)
826
827 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
828 else: i += 2
829 if flags & WE_HAVE_A_SCALE: i += 2
830 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
831 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
832 more = flags & MORE_COMPONENTS
833 self.data = str (data)
834
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400835@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
836def dropInstructionsFast (self):
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400837 numContours = struct.unpack(">h", self.data[:2])[0]
838 data = bytearray (self.data)
839 i = 10
840 if numContours >= 0:
841 i += 2 * numContours # endPtsOfContours
842 instructionLen = (data[i] << 8) | data[i+1]
843 # Zero it
844 data[i] = data [i+1] = 0
845 i += 2
Behdad Esfahbod0fb69882013-07-24 17:25:35 -0400846 if instructionLen:
847 # Splice it out
848 data = data[:i] + data[i+instructionLen:]
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400849 else:
850 more = 1
851 while more:
852 flags = (data[i] << 8) | data[i+1]
853 # Turn instruction flag off
854 flags &= ~WE_HAVE_INSTRUCTIONS
855 data[i+0] = flags >> 8
856 data[i+1] = flags & 0xFF
857 i += 4
858 flags = int(flags)
859
860 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
861 else: i += 2
862 if flags & WE_HAVE_A_SCALE: i += 2
863 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
864 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
865 more = flags & MORE_COMPONENTS
866 # Cut off
867 data = data[:i]
868 if len(data) % 4:
869 # add pad bytes
870 nPadBytes = 4 - (len(data) % 4)
871 for i in range (nPadBytes):
872 data.append (0)
873 self.data = str (data)
874
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400875@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400876def closure_glyphs (self, s):
877 glyphs = unique_sorted (s.glyphs)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400878 decompose = glyphs
879 # I don't know if component glyphs can be composite themselves.
880 # We handle them anyway.
881 while True:
882 components = []
883 for g in decompose:
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400884 if g not in self.glyphs:
Behdad Esfahbodf8c20e42013-07-23 23:13:23 -0400885 continue
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400886 gl = self.glyphs[g]
887 if hasattr (gl, "data"):
888 for c in gl.getComponentNamesFast (self):
889 if c not in glyphs:
890 components.append (c)
891 else:
892 # TTX seems to expand gid0..3 always
893 if gl.isComposite ():
894 for c in gl.components:
895 if c.glyphName not in glyphs:
896 components.append (c.glyphName)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400897 components = [c for c in components if c not in glyphs]
898 if not components:
899 return glyphs
900 decompose = unique_sorted (components)
901 glyphs.extend (components)
902
903@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400904def subset_glyphs (self, s):
905 self.glyphs = {g:v for g,v in self.glyphs.items() if g in s.glyphs}
906 indices = [i for i,g in enumerate (self.glyphOrder) if g in s.glyphs]
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400907 for v in self.glyphs.values ():
908 if hasattr (v, "data"):
909 v.remapComponentsFast (indices)
910 else:
911 pass # No need
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400912 self.glyphOrder = [g for g in self.glyphOrder if g in s.glyphs]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400913 return bool (self.glyphs)
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400914
Behdad Esfahboded98c612013-07-23 12:37:41 -0400915@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400916def prune_post_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400917 if not options.hinting:
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400918 for v in self.glyphs.values ():
919 if hasattr (v, "data"):
920 v.dropInstructionsFast ()
921 else:
922 v.program = fontTools.ttLib.tables.ttProgram.Program()
923 v.program.fromBytecode([])
Behdad Esfahboded98c612013-07-23 12:37:41 -0400924 return True
925
Behdad Esfahbod2b677c82013-07-23 13:37:13 -0400926@add_method(fontTools.ttLib.getTableClass('CFF '))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400927def subset_glyphs (self, s):
Behdad Esfahbod2b677c82013-07-23 13:37:13 -0400928 assert 0, "unimplemented"
929
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400930@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400931def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400932 if not options.legacy_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400933 # Drop non-Unicode / non-Symbol cmaps
934 self.tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [0, 1, 10]]
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400935 if not options.symbol_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400936 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 -0400937 # TODO Only keep one subtable?
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400938 # For now, drop format=0 which can't be subset_glyphs easily?
939 self.tables = [t for t in self.tables if t.format != 0]
940 return bool (self.tables)
941
942@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400943def subset_glyphs (self, s):
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400944 for t in self.tables:
Behdad Esfahbod9453a362013-07-22 16:21:24 -0400945 # For reasons I don't understand I need this here
946 # to force decompilation of the cmap format 14.
947 try:
948 getattr (t, "asdf")
949 except AttributeError:
950 pass
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400951 if t.format == 14:
Behdad Esfahbod9453a362013-07-22 16:21:24 -0400952 # XXX We drop all the default-UVS mappings (g==None)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400953 t.uvsDict = {v:[(u,g) for (u,g) in l if g in s.glyphs] for (v,l) in t.uvsDict.items()}
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400954 t.uvsDict = {v:l for (v,l) in t.uvsDict.items() if l}
955 else:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400956 t.cmap = {u:g for (u,g) in t.cmap.items() if g in s.glyphs}
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400957 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 -0400958 # XXX Convert formats when needed
Behdad Esfahbod61addb42013-07-23 11:03:49 -0400959 return bool (self.tables)
960
Behdad Esfahbod61addb42013-07-23 11:03:49 -0400961@add_method(fontTools.ttLib.getTableClass('name'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400962def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400963 if '*' not in options.name_IDs:
964 self.names = [n for n in self.names if n.nameID in options.name_IDs]
965 if not options.name_legacy:
Behdad Esfahbod20faeb02013-07-23 13:19:03 -0400966 self.names = [n for n in self.names if n.platformID == 3 and n.platEncID == 1]
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400967 if '*' not in options.name_languages:
968 self.names = [n for n in self.names if n.langID in options.name_languages]
Behdad Esfahbod20faeb02013-07-23 13:19:03 -0400969 return True # Retain even if empty
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400970
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400971
Behdad Esfahbodbc25f162013-07-23 12:56:54 -0400972drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'PCLT', 'LTSH']
Behdad Esfahbod103a12f2013-07-23 15:08:39 -0400973drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill'] # Graphite
Behdad Esfahbod38e852c2013-07-23 16:56:50 -0400974drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL'] # Color
Behdad Esfahboded98c612013-07-23 12:37:41 -0400975no_subset_tables = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2', 'loca', 'name', 'cvt ', 'fpgm', 'prep']
Behdad Esfahbodbc25f162013-07-23 12:56:54 -0400976hinting_tables = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
Behdad Esfahbod29df0462013-07-23 11:05:25 -0400977
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400978# Based on HarfBuzz shapers
979layout_features_dict = {
980 # Default shaper
981 'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
982 'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
983 'vertical': ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
984 'ltr': ['ltra', 'ltrm'],
985 'rtl': ['rtla', 'rtlm'],
986 # Complex shapers
987 'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3'],
988 'hangul': ['ljmo', 'vjmo', 'tjmo'],
989 'tibetal': ['abvs', 'blws', 'abvm', 'blwm'],
990 'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half', 'abvf', 'pstf', 'cfar', 'vatu', 'cjct',
991 'init', 'pres', 'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
992}
993layout_features_all = unique_sorted (sum (layout_features_dict.values (), []))
994
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400995# TODO OS/2 ulUnicodeRange / ulCodePageRange?
Behdad Esfahbodf71267b2013-07-23 12:59:13 -0400996# TODO Drop unneeded GSUB/GPOS Script/LangSys entries
Behdad Esfahbod398d3892013-07-23 15:29:40 -0400997# TODO Avoid recursing too much
Behdad Esfahbode94aa0e2013-07-23 13:22:04 -0400998# TODO Text direction considerations
999# TODO Text script / language considerations
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001000# TODO Drop unknown tables? Using DefaultTable.prune?
Behdad Esfahbod8c4f7cc2013-07-24 17:58:29 -04001001# TODO Drop GPOS Device records if not hinting?
Behdad Esfahbod75e7ecf2013-07-29 12:05:15 -04001002# TODO subset_unicode values in cmap
Behdad Esfahbod56ebd042013-07-22 13:02:24 -04001003
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001004
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001005class Subsetter:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001006
1007 class Options:
1008 drop_tables = drop_tables_default
1009 layout_features = layout_features_all
1010 hinting = False
1011 glyph_names = False
1012 legacy_cmap = False
1013 symbol_cmap = False
1014 name_IDs = [1, 2] # Family and Style
1015 name_legacy = False
1016 name_languages = [0x0409] # English
1017 mandatory_glyphs = True # First four for TrueType, .notdef for CFF
1018 recalc_bboxes = False # Slows us down
1019
1020 def __init__ (self, **kwargs):
1021
1022 self.set (**kwargs)
1023
1024 def set (self, **kwargs):
1025 for k,v in kwargs.items ():
1026 if not hasattr (self, k):
1027 raise Exception ("Unknown option '%s'" % k)
1028 setattr (self, k, v)
1029
1030 def parse_opts (self, argv, ignore_unknown=False):
1031 ret = []
1032 opts = {}
1033 for a in argv:
1034 if not a.startswith ('--'):
1035 ret.append (a)
1036 continue
1037 a = a[2:]
1038 i = a.find ('=')
1039 if i == -1:
1040 if a.startswith ("no-"):
1041 k = a[3:]
1042 v = False
1043 else:
1044 k = a
1045 v = True
1046 else:
1047 k = a[:i]
1048 v = a[i+1:]
1049 k = k.replace ('-', '_')
1050 if not hasattr (self, k):
1051 if ignore_unknown:
1052 ret.append (a)
1053 continue
1054 else:
1055 raise Exception ("Unknown option '%s'" % a)
1056
1057 ov = getattr (self, k)
1058 if isinstance (ov, bool):
1059 v = bool (v)
1060 elif isinstance (ov, int):
1061 v = int (v)
1062 elif isinstance (ov, list):
1063 v = v.split (',')
1064 v = [int (x, 0) if x[0] in range (10) else x for x in v]
1065
1066 opts[k] = v
1067 self.set (**opts)
1068
1069 return ret
1070
1071
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001072 def __init__ (self, font=None, options=None, log=None):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001073
1074 if isinstance (font, basestring):
1075 font = fontTools.ttx.TTFont (font)
1076 if not log:
1077 log = Logger()
1078 if not options:
1079 options = Options()
1080
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001081 self.font = font
1082 self.options = options
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001083 self.log = log
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001084
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001085 def subset (self, font, glyphs):
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001086
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001087 glyphs = set (glyphs)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001088
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001089 font.recalcBBoxes = self.options.recalc_bboxes
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001090
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001091 if self.options.mandatory_glyphs:
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001092 if 'glyf' in font:
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001093 for i in range (4):
1094 glyphs.add (font.getGlyphName (i))
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001095 self.log ("Added first four glyphs to subset")
1096 else:
1097 glyphs.append ('.notdef')
1098 self.log ("Added .notdef glyph to subset")
1099
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001100 for tag in font.keys():
1101 if tag == 'GlyphOrder': continue
1102
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001103 if tag in self.options.drop_tables or \
1104 (tag in hinting_tables and not self.options.hinting):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001105 self.log (tag, "dropped")
1106 del font[tag]
1107 continue
1108
1109 clazz = fontTools.ttLib.getTableClass(tag)
1110
1111 if hasattr (clazz, 'prune_pre_subset'):
1112 table = font[tag]
1113 retain = table.prune_pre_subset (self.options)
1114 self.log.lapse ("prune '%s'" % tag)
1115 if not retain:
1116 self.log (tag, "pruned to empty; dropped")
1117 del font[tag]
1118 continue
1119 else:
1120 self.log (tag, "pruned")
1121
1122 glyphs_requested = glyphs
1123 if 'GSUB' in font:
1124 self.log ("Closing glyph list over 'GSUB': %d glyphs before" % len (glyphs))
1125 self.glyphs = glyphs
1126 glyphs = font['GSUB'].closure_glyphs (self)
1127 self.log ("Closed glyph list over 'GSUB': %d glyphs after" % len (glyphs))
1128 self.log ("Glyphs:", glyphs)
1129 self.log.lapse ("close glyph list over 'GSUB'")
1130 glyphs_gsubed = glyphs
1131
1132 # Close over composite glyphs
1133 if 'glyf' in font:
1134 self.log ("Closing glyph list over 'glyf': %d glyphs before" % len (glyphs))
1135 self.log ("Glyphs:", glyphs)
1136 self.glyphs = glyphs
1137 glyphs = font['glyf'].closure_glyphs (self)
1138 self.log ("Closed glyph list over 'glyf': %d glyphs after" % len (glyphs))
1139 self.log ("Glyphs:", glyphs)
1140 self.log.lapse ("close glyph list over 'glyf'")
1141 else:
1142 glyphs = glyphs
1143 glyphs_glyfed = glyphs
1144 glyphs_closed = glyphs
1145 del glyphs
1146
1147 self.log ("Retaining %d glyphs: " % len (glyphs_closed))
1148
1149 for tag in font.keys():
1150 if tag == 'GlyphOrder': continue
1151
1152 clazz = fontTools.ttLib.getTableClass(tag)
1153
1154 if tag in no_subset_tables:
1155 self.log (tag, "subsetting not needed")
1156 elif hasattr (clazz, 'subset_glyphs'):
1157 table = font[tag]
1158 if tag == 'cmap': # What else?
1159 glyphs = glyphs_requested
1160 elif tag in ['GSUB', 'GPOS', 'GDEF', 'cmap', 'kern', 'post']: # What else?
1161 glyphs = glyphs_gsubed
1162 else:
1163 glyphs = glyphs_closed
1164 self.glyphs = glyphs
1165 retain = table.subset_glyphs (self)
1166 self.log.lapse ("subset '%s'" % tag)
1167 if not retain:
1168 self.log (tag, "subsetted to empty; dropped")
1169 del font[tag]
1170 continue
1171 else:
1172 self.log (tag, "subsetted")
1173 del glyphs
1174 else:
1175 self.log (tag, "NOT subset; don't know how to subset")
1176 continue
1177
1178 if hasattr (clazz, 'prune_post_subset'):
1179 table = font[tag]
1180 retain = table.prune_post_subset (self.options)
1181 self.log.lapse ("prune '%s'" % tag)
1182 if not retain:
1183 self.log (tag, "pruned to empty; dropped")
1184 del font[tag]
1185 continue
1186 else:
1187 self.log (tag, "pruned")
1188
1189 glyphOrder = font.getGlyphOrder()
1190 glyphOrder = [g for g in glyphOrder if g in glyphs_closed]
1191 font.setGlyphOrder (glyphOrder)
1192 font._buildReverseGlyphOrderDict ()
1193 self.log.lapse ("subset GlyphOrder")
1194
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001195import sys, time
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001196
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001197class Logger:
1198
1199 def __init__ (self, verbose=False, xml=False, timing=False):
1200 self.verbose = verbose
1201 self.xml = xml
1202 self.timing = timing
1203 self.last_time = self.start_time = time.time ()
1204
1205 def parse_opts (self, argv):
1206 argv = argv[:]
1207 for v in ['verbose', 'xml', 'timing']:
1208 if "--"+v in argv:
1209 setattr (self, v, True)
1210 argv.remove ("--"+v)
1211 return argv
1212
1213 def __call__ (self, *things):
1214 if not self.verbose:
1215 return
1216 print ' '.join (str (x) for x in things)
1217
1218 def lapse (self, *things):
1219 if not self.timing:
1220 return
1221 new_time = time.time ()
1222 print "Took %0.3fs to %s" % (new_time - self.last_time, ' '.join (str (x) for x in things))
1223 self.last_time = new_time
1224
1225 def font (self, font, file=sys.stdout):
1226 if not self.xml:
1227 return
1228 import xmlWriter, sys
1229 writer = xmlWriter.XMLWriter (file)
1230 font.disassembleInstructions = False # Work around ttx bug
1231 for tag in font.keys():
1232 writer.begintag (tag)
1233 writer.newline ()
1234 font[tag].toXML(writer, font)
1235 writer.endtag (tag)
1236 writer.newline ()
1237
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001238def main (args):
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001239
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001240 log = Logger ()
1241 args = log.parse_opts (args)
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001242
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001243 options = Subsetter.Options ()
1244 args = options.parse_opts (args)
1245
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001246 if len (args) < 2:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001247 import sys
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001248 print >>sys.stderr, "usage: pyotlss.py font-file glyph..."
1249 sys.exit (1)
1250
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001251 fontfile = args[0]
1252 glyphs = args[1:]
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001253
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001254 # TODO Option for ignoreDecompileErrors?
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001255 font = fontTools.ttx.TTFont (fontfile)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001256 s = Subsetter (font=font, options=options, log=log)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001257 log.lapse ("load font")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001258
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001259 # Hack:
1260 #
1261 # If we don't need glyph names, change 'post' class to not try to
1262 # load them. It avoid lots of headache with broken fonts as well
1263 # as loading time.
1264 #
1265 # Ideally ttLib should provide a way to ask it to skip loading
1266 # glyph names. But it currently doesn't provide such a thing.
1267 #
1268 if not options.glyph_names \
1269 and all (any (g.startswith (p) for p in ['gid', 'glyph', 'uni']) \
1270 for g in glyphs):
1271 post = fontTools.ttLib.getTableClass('post')
1272 saved = post.decode_format_2_0
1273 post.decode_format_2_0 = post.decode_format_3_0
1274 f = font['post']
1275 if f.formatType == 2.0:
1276 f.formatType = 3.0
1277 post.decode_format_2_0 = saved
1278 del post, saved, f
1279
1280 names = font.getGlyphNames()
1281 log.lapse ("loading glyph names")
1282 # Convert to glyph names
1283 glyph_names = []
1284 cmap_tables = None
1285 for g in glyphs:
1286 if g in names:
1287 glyph_names.append (g)
1288 continue
1289 if g.startswith ('uni') and len (g) > 3:
1290 if not cmap_tables:
1291 cmap = font['cmap']
1292 cmap_tables = [t for t in cmap.tables if t.platformID == 3 and t.platEncID in [1, 10]]
1293 del cmap
1294 found = False
1295 u = int (g[3:], 16)
1296 for table in cmap_tables:
1297 if u in table.cmap:
1298 glyph_names.append (table.cmap[u])
1299 found = True
1300 break
1301 if not found:
1302 log ("No glyph for Unicode value %s; skipping." % g)
1303 continue
1304 if g.startswith ('gid') or g.startswith ('glyph'):
1305 if g.startswith ('gid') and len (g) > 3:
1306 g = g[3:]
1307 elif g.startswith ('glyph') and len (g) > 5:
1308 g = g[5:]
1309 try:
1310 glyph_names.append (font.getGlyphName (int (g), requireReal=1))
1311 except ValueError:
1312 raise Exception ("Invalid glyph identifier %s" % g)
1313 continue
1314 raise Exception ("Invalid glyph identifier %s" % g)
1315 del cmap_tables
1316 glyphs = set (glyph_names)
1317 del glyph_names
1318 log.lapse ("compile glyph list")
1319 log ("Glyphs:", glyphs)
1320
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001321 s.subset (font, glyphs)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -04001322
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001323 font.save (fontfile + '.subset')
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001324 log.lapse ("compile and save font")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001325
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001326 log.last_time = s.log.start_time
1327 log.lapse ("make one with everything (TOTAL TIME)")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001328
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001329 log.font (font)
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001330
1331if __name__ == '__main__':
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001332 import sys
1333 main (sys.argv[1:])