blob: eea0daf84cdd1451ed03fa896c6e1f07f8938e36 [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 Esfahbod849d25c2013-08-12 19:24:24 -040053def intersect_glyphs (self, glyphs):
54 "Returns set of intersecting glyphs."
55 return set (g for g in self.glyphs if g in glyphs)
56
57@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040058def subset (self, glyphs):
Behdad Esfahbodd821ea02013-07-23 10:50:43 -040059 "Returns ascending list of remaining coverage values."
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040060 indices = self.intersect (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -040061 self.glyphs = [g for g in self.glyphs if g in glyphs]
62 return indices
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040063
Behdad Esfahbod14374262013-08-08 22:26:49 -040064@add_method(fontTools.ttLib.tables.otTables.Coverage)
65def remap (self, coverage_map):
66 "Remaps coverage."
67 self.glyphs = [self.glyphs[i] for i in coverage_map]
68
Behdad Esfahbod54660612013-07-21 18:16:55 -040069@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040070def intersect (self, glyphs):
Behdad Esfahbode10803e2013-08-08 21:09:27 -040071 "Returns ascending list of matching class values."
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040072 return unique_sorted (([0] if any (g not in self.classDefs for g in glyphs) else []) + \
Behdad Esfahbode10803e2013-08-08 21:09:27 -040073 [v for g,v in self.classDefs.items() if g in glyphs])
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040074
75@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -040076def intersect_class (self, glyphs, klass):
77 "Returns set of glyphs matching class."
Behdad Esfahbod0befd6b2013-08-05 22:47:14 -040078 if klass == 0:
Behdad Esfahbod849d25c2013-08-12 19:24:24 -040079 return set (g for g in glyphs if g not in self.classDefs)
80 return set (g for g,v in self.classDefs.items() if v == klass and g in glyphs)
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040081
82@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040083def subset (self, glyphs, remap=False):
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040084 "Returns ascending list of remaining classes."
Behdad Esfahbod54660612013-07-21 18:16:55 -040085 self.classDefs = {g:v for g,v in self.classDefs.items() if g in glyphs}
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040086 # Note: while class 0 has the special meaning of "not matched", if no glyph will
87 # ever /not match/, we can optimize class 0 out too.
88 indices = unique_sorted (([0] if any (g not in self.classDefs for g in glyphs) else []) + \
89 self.classDefs.values ())
Behdad Esfahbodde71dca2013-07-24 12:40:54 -040090 if remap:
91 self.remap (indices)
92 return indices
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -040093
94@add_method(fontTools.ttLib.tables.otTables.ClassDef)
95def remap (self, class_map):
96 "Remaps classes."
97 self.classDefs = {g:class_map.index (v) for g,v in self.classDefs.items()}
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040098
Behdad Esfahbod54660612013-07-21 18:16:55 -040099@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400100def closure_glyphs (self, s, cur_glyphs=None):
101 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400102 if self.Format in [1, 2]:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400103 return [v for g,v in self.mapping.items() if g in cur_glyphs]
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400104 else:
105 assert 0, "unknown format: %s" % self.Format
106
107@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400108def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400109 if self.Format in [1, 2]:
Behdad Esfahbod14374262013-08-08 22:26:49 -0400110 self.mapping = {g:v for g,v in self.mapping.items() if g in s.glyphs and v in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400111 return bool (self.mapping)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400112 else:
113 assert 0, "unknown format: %s" % self.Format
114
115@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400116def closure_glyphs (self, s, cur_glyphs=None):
117 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400118 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400119 indices = self.Coverage.intersect (cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400120 return sum ((self.Sequence[i].Substitute for i in indices), [])
121 else:
122 assert 0, "unknown format: %s" % self.Format
123
124@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400125def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400126 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400127 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400128 self.Sequence = [self.Sequence[i] for i in indices]
Behdad Esfahbod14374262013-08-08 22:26:49 -0400129 # Now drop rules generating glyphs we don't want
130 indices = [i for i,seq in enumerate (self.Sequence) \
131 if all (sub in s.glyphs for sub in seq.Substitute)]
132 self.Sequence = [self.Sequence[i] for i in indices]
133 self.Coverage.remap (indices)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400134 self.SequenceCount = len (self.Sequence)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400135 return bool (self.SequenceCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400136 else:
137 assert 0, "unknown format: %s" % self.Format
138
139@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400140def closure_glyphs (self, s, cur_glyphs=None):
141 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400142 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400143 return sum ((vlist for g,vlist in self.alternates.items() if g in cur_glyphs), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400144 else:
145 assert 0, "unknown format: %s" % self.Format
146
147@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400148def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400149 if self.Format == 1:
Behdad Esfahbod14374262013-08-08 22:26:49 -0400150 self.alternates = {g:vlist for g,vlist in self.alternates.items() \
151 if g in s.glyphs and all (v in s.glyphs for v in vlist)}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400152 return bool (self.alternates)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400153 else:
154 assert 0, "unknown format: %s" % self.Format
155
156@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400157def closure_glyphs (self, s, cur_glyphs=None):
158 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400159 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400160 return sum (([seq.LigGlyph for seq in seqs if all(c in s.glyphs for c in seq.Component)]
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400161 for g,seqs in self.ligatures.items() if g in cur_glyphs), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400162 else:
163 assert 0, "unknown format: %s" % self.Format
164
165@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400166def subset_glyphs (self, s):
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400167 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400168 self.ligatures = {g:v for g,v in self.ligatures.items() if g in s.glyphs}
Behdad Esfahbod14374262013-08-08 22:26:49 -0400169 self.ligatures = {g:[seq for seq in seqs \
170 if seq.LigGlyph in s.glyphs and \
171 all(c in s.glyphs for c in seq.Component)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400172 for g,seqs in self.ligatures.items()}
173 self.ligatures = {g:v for g,v in self.ligatures.items() if v}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400174 return bool (self.ligatures)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400175 else:
176 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400177
Behdad Esfahbod54660612013-07-21 18:16:55 -0400178@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400179def closure_glyphs (self, s, cur_glyphs=None):
180 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400181 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400182 indices = self.Coverage.intersect (cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400183 if not indices or \
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400184 not all (c.intersect (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400185 return []
186 return [self.Substitute[i] for i in indices]
187 else:
188 assert 0, "unknown format: %s" % self.Format
189
190@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400191def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400192 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400193 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400194 self.Substitute = [self.Substitute[i] for i in indices]
Behdad Esfahbod14374262013-08-08 22:26:49 -0400195 # Now drop rules generating glyphs we don't want
196 indices = [i for i,sub in enumerate (self.Substitute) \
197 if sub in s.glyphs]
198 self.Substitute = [self.Substitute[i] for i in indices]
199 self.Coverage.remap (indices)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400200 self.GlyphCount = len (self.Substitute)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400201 return bool (self.GlyphCount and all (c.subset (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400202 else:
203 assert 0, "unknown format: %s" % self.Format
204
205@add_method(fontTools.ttLib.tables.otTables.SinglePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400206def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400207 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400208 return len (self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400209 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400210 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400211 self.Value = [self.Value[i] for i in indices]
212 self.ValueCount = len (self.Value)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400213 return bool (self.ValueCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400214 else:
215 assert 0, "unknown format: %s" % self.Format
216
217@add_method(fontTools.ttLib.tables.otTables.PairPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400218def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400219 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400220 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400221 self.PairSet = [self.PairSet[i] for i in indices]
222 for p in self.PairSet:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400223 p.PairValueRecord = [r for r in p.PairValueRecord if r.SecondGlyph in s.glyphs]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400224 p.PairValueCount = len (p.PairValueRecord)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400225 self.PairSet = [p for p in self.PairSet if p.PairValueCount]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400226 self.PairSetCount = len (self.PairSet)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400227 return bool (self.PairSetCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400228 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400229 class1_map = self.ClassDef1.subset (s.glyphs, remap=True)
230 class2_map = self.ClassDef2.subset (s.glyphs, remap=True)
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -0400231 self.Class1Record = [self.Class1Record[i] for i in class1_map]
232 for c in self.Class1Record:
233 c.Class2Record = [c.Class2Record[i] for i in class2_map]
234 self.Class1Count = len (class1_map)
235 self.Class2Count = len (class2_map)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400236 return bool (self.Class1Count and self.Class2Count and self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400237 else:
238 assert 0, "unknown format: %s" % self.Format
239
240@add_method(fontTools.ttLib.tables.otTables.CursivePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400241def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400242 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400243 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400244 self.EntryExitRecord = [self.EntryExitRecord[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400245 self.EntryExitCount = len (self.EntryExitRecord)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400246 return bool (self.EntryExitCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400247 else:
248 assert 0, "unknown format: %s" % self.Format
249
250@add_method(fontTools.ttLib.tables.otTables.MarkBasePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400251def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400252 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400253 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400254 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
255 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400256 base_indices = self.BaseCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400257 self.BaseArray.BaseRecord = [self.BaseArray.BaseRecord[i] for i in base_indices]
258 self.BaseArray.BaseCount = len (self.BaseArray.BaseRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400259 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400260 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400261 self.ClassCount = len (class_indices)
262 for m in self.MarkArray.MarkRecord:
263 m.Class = class_indices.index (m.Class)
264 for b in self.BaseArray.BaseRecord:
265 b.BaseAnchor = [b.BaseAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400266 return bool (self.ClassCount and self.MarkArray.MarkCount and self.BaseArray.BaseCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400267 else:
268 assert 0, "unknown format: %s" % self.Format
269
270@add_method(fontTools.ttLib.tables.otTables.MarkLigPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400271def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400272 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400273 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400274 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
275 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400276 ligature_indices = self.LigatureCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400277 self.LigatureArray.LigatureAttach = [self.LigatureArray.LigatureAttach[i] for i in ligature_indices]
278 self.LigatureArray.LigatureCount = len (self.LigatureArray.LigatureAttach)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400279 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400280 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400281 self.ClassCount = len (class_indices)
282 for m in self.MarkArray.MarkRecord:
283 m.Class = class_indices.index (m.Class)
284 for l in self.LigatureArray.LigatureAttach:
285 for c in l.ComponentRecord:
286 c.LigatureAnchor = [c.LigatureAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400287 return bool (self.ClassCount and self.MarkArray.MarkCount and self.LigatureArray.LigatureCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400288 else:
289 assert 0, "unknown format: %s" % self.Format
290
291@add_method(fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400292def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400293 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400294 mark1_indices = self.Mark1Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400295 self.Mark1Array.MarkRecord = [self.Mark1Array.MarkRecord[i] for i in mark1_indices]
296 self.Mark1Array.MarkCount = len (self.Mark1Array.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400297 mark2_indices = self.Mark2Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400298 self.Mark2Array.Mark2Record = [self.Mark2Array.Mark2Record[i] for i in mark2_indices]
299 self.Mark2Array.MarkCount = len (self.Mark2Array.Mark2Record)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400300 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400301 class_indices = unique_sorted (v.Class for v in self.Mark1Array.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400302 self.ClassCount = len (class_indices)
303 for m in self.Mark1Array.MarkRecord:
304 m.Class = class_indices.index (m.Class)
305 for b in self.Mark2Array.Mark2Record:
306 b.Mark2Anchor = [b.Mark2Anchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400307 return bool (self.ClassCount and self.Mark1Array.MarkCount and self.Mark2Array.MarkCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400308 else:
309 assert 0, "unknown format: %s" % self.Format
310
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400311@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400312 fontTools.ttLib.tables.otTables.MultipleSubst,
313 fontTools.ttLib.tables.otTables.AlternateSubst,
314 fontTools.ttLib.tables.otTables.LigatureSubst,
315 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
316 fontTools.ttLib.tables.otTables.SinglePos,
317 fontTools.ttLib.tables.otTables.PairPos,
318 fontTools.ttLib.tables.otTables.CursivePos,
319 fontTools.ttLib.tables.otTables.MarkBasePos,
320 fontTools.ttLib.tables.otTables.MarkLigPos,
321 fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400322def subset_lookups (self, lookup_indices):
323 pass
324
325@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400326 fontTools.ttLib.tables.otTables.MultipleSubst,
327 fontTools.ttLib.tables.otTables.AlternateSubst,
328 fontTools.ttLib.tables.otTables.LigatureSubst,
329 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
330 fontTools.ttLib.tables.otTables.SinglePos,
331 fontTools.ttLib.tables.otTables.PairPos,
332 fontTools.ttLib.tables.otTables.CursivePos,
333 fontTools.ttLib.tables.otTables.MarkBasePos,
334 fontTools.ttLib.tables.otTables.MarkLigPos,
335 fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400336def collect_lookups (self):
337 return []
338
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400339@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
340 fontTools.ttLib.tables.otTables.AlternateSubst,
341 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
342def may_have_non_1to1 (self):
343 return False
344
345@add_method(fontTools.ttLib.tables.otTables.MultipleSubst,
346 fontTools.ttLib.tables.otTables.LigatureSubst,
347 fontTools.ttLib.tables.otTables.ContextSubst,
348 fontTools.ttLib.tables.otTables.ChainContextSubst)
349def may_have_non_1to1 (self):
350 return True
351
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400352@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
353 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
354def __classify_context (self):
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400355
356 class ContextHelper:
357 def __init__ (self, klass, Format):
358 if klass.__name__.endswith ('Subst'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400359 Typ = 'Sub'
360 Type = 'Subst'
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400361 else:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400362 Typ = 'Pos'
363 Type = 'Pos'
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400364 if klass.__name__.startswith ('Chain'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400365 Chain = 'Chain'
366 else:
367 Chain = ''
368 ChainTyp = Chain+Typ
369
370 self.Typ = Typ
371 self.Type = Type
372 self.Chain = Chain
373 self.ChainTyp = ChainTyp
374
375 self.LookupRecord = Type+'LookupRecord'
376
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400377 if Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400378 Coverage = lambda r: r.Coverage
379 ChainCoverage = lambda r: r.Coverage
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400380 ContextData = lambda r: (None,)
381 ChainContextData = lambda r: (None, None, None)
382 RuleData = lambda r: (r.Input,)
383 ChainRuleData = lambda r: (r.Backtrack, r.Input, r.LookAhead)
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400384 SetRuleData = None
385 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400386 elif Format == 2:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400387 Coverage = lambda r: r.Coverage
388 ChainCoverage = lambda r: r.Coverage
Behdad Esfahbode3f20732013-07-24 11:26:43 -0400389 ContextData = lambda r: (r.ClassDef,)
390 ChainContextData = lambda r: (r.LookAheadClassDef, r.InputClassDef, r.BacktrackClassDef)
391 RuleData = lambda r: (r.Class,)
392 ChainRuleData = lambda r: (r.LookAhead, r.Input, r.Backtrack)
393 def SetRuleData (r, d): (r.Class,) = d
394 def ChainSetRuleData (r, d): (r.LookAhead, r.Input, r.Backtrack) = d
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400395 elif Format == 3:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400396 Coverage = lambda r: r.Coverage[0]
397 ChainCoverage = lambda r: r.InputCoverage[0]
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400398 ContextData = None
399 ChainContextData = None
400 RuleData = lambda r: r.Coverage
401 ChainRuleData = lambda r: r.LookAheadCoverage + r.InputCoverage + r.BacktrackCoverage
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400402 SetRuleData = None
403 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400404 else:
405 assert 0, "unknown format: %s" % Format
406
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400407 if Chain:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400408 self.Coverage = ChainCoverage
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400409 self.ContextData = ChainContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400410 self.RuleData = ChainRuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400411 self.SetRuleData = ChainSetRuleData
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400412 else:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400413 self.Coverage = Coverage
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400414 self.ContextData = ContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400415 self.RuleData = RuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400416 self.SetRuleData = SetRuleData
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400417
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400418 if Format == 1:
419 self.Rule = ChainTyp+'Rule'
420 self.RuleCount = ChainTyp+'RuleCount'
421 self.RuleSet = ChainTyp+'RuleSet'
422 self.RuleSetCount = ChainTyp+'RuleSetCount'
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400423 self.Intersect = lambda glyphs, ContextData, RuleData: [RuleData] if RuleData in glyphs else []
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400424 elif Format == 2:
425 self.Rule = ChainTyp+'ClassRule'
426 self.RuleCount = ChainTyp+'ClassRuleCount'
427 self.RuleSet = ChainTyp+'ClassSet'
428 self.RuleSetCount = ChainTyp+'ClassSetCount'
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400429 self.Intersect = lambda glyphs, ContextData, RuleData: ContextData.intersect_class (glyphs, RuleData)
Behdad Esfahbod89987002013-07-23 23:07:42 -0400430
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400431 self.ClassDef = 'InputClassDef' if Chain else 'ClassDef'
Behdad Esfahbod27108392013-07-23 16:40:47 -0400432
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400433 if self.Format not in [1, 2, 3]:
434 return None # Don't shoot the messenger; let it go
435 if not hasattr (self.__class__, "__ContextHelpers"):
436 self.__class__.__ContextHelpers = {}
437 if self.Format not in self.__class__.__ContextHelpers:
438 self.__class__.__ContextHelpers[self.Format] = ContextHelper (self.__class__, self.Format)
439 return self.__class__.__ContextHelpers[self.Format]
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400440
Behdad Esfahbodf2b6d9c2013-07-23 17:31:54 -0400441@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400442def closure_glyphs (self, s, cur_glyphs=None):
443 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400444 c = self.__classify_context ()
445
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400446 indices = c.Coverage (self).intersect (s.glyphs)
447 if not indices:
448 return []
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400449 cur_glyphs = c.Coverage (self).intersect_glyphs (s.glyphs);
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400450
Behdad Esfahbod00776972013-07-23 15:33:00 -0400451 if self.Format == 1:
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400452 ContextData = c.ContextData (self)
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400453 rss = getattr (self, c.RuleSet)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400454 add = []
455 for i in indices:
456 if not rss[i]: continue
457 for r in getattr (rss[i], c.Rule):
458 if not r: continue
459 if all (all (c.Intersect (s.glyphs, cd, k) for k in klist)
460 for cd,klist in zip (ContextData, c.RuleData (r))):
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400461 chaos = False
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400462 for ll in getattr (r, c.LookupRecord):
463 if not ll: continue
464 seqi = ll.SequenceIndex
465 if seqi == 0:
466 pos_glyphs = set (c.Coverage (self).glyphs[i])
467 else:
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400468 if chaos:
469 pos_glyphs = s.glyphs
470 else:
471 pos_glyphs = set (r.Input[seqi - 1])
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400472 lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400473 chaos = chaos or lookup.may_have_non_1to1 ()
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400474 add.extend (lookup.closure_glyphs (s, cur_glyphs=pos_glyphs))
475 return add
Behdad Esfahbod00776972013-07-23 15:33:00 -0400476 elif self.Format == 2:
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400477 ClassDef = getattr (self, c.ClassDef)
478 indices = ClassDef.intersect (cur_glyphs)
479 ContextData = c.ContextData (self)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400480 rss = getattr (self, c.RuleSet)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400481 add = []
482 for i in indices:
483 if not rss[i]: continue
484 for r in getattr (rss[i], c.Rule):
485 if not r: continue
486 if all (all (c.Intersect (s.glyphs, cd, k) for k in klist)
487 for cd,klist in zip (ContextData, c.RuleData (r))):
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400488 chaos = False
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400489 for ll in getattr (r, c.LookupRecord):
490 if not ll: continue
491 seqi = ll.SequenceIndex
492 if seqi == 0:
493 pos_glyphs = ClassDef.intersect_class (cur_glyphs, i)
494 else:
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400495 if chaos:
496 pos_glyphs = s.glyphs
497 else:
498 pos_glyphs = ClassDef.intersect_class (s.glyphs, r.Input[seqi - 1])
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400499 lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400500 chaos = chaos or lookup.may_have_non_1to1 ()
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400501 add.extend (lookup.closure_glyphs (s, cur_glyphs=pos_glyphs))
502 return add
Behdad Esfahbod00776972013-07-23 15:33:00 -0400503 elif self.Format == 3:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400504 if not all (x.intersect (s.glyphs) for x in c.RuleData (self)):
Behdad Esfahbod00776972013-07-23 15:33:00 -0400505 return []
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400506 r = self
507 add = []
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400508 chaos = False
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400509 for ll in getattr (r, c.LookupRecord):
510 if not ll: continue
511 seqi = ll.SequenceIndex
512 if seqi == 0:
513 pos_glyphs = cur_glyphs
514 else:
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400515 if chaos:
516 pos_glyphs = s.glyphs
517 else:
518 pos_glyphs = r.InputCoverage[seqi].intersect_glyphs (s.glyphs)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400519 lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400520 chaos = chaos or lookup.may_have_non_1to1 ()
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400521 add.extend (lookup.closure_glyphs (s, cur_glyphs=pos_glyphs))
522 return add
Behdad Esfahbod00776972013-07-23 15:33:00 -0400523 else:
524 assert 0, "unknown format: %s" % self.Format
525
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400526@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ContextPos,
527 fontTools.ttLib.tables.otTables.ChainContextSubst, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400528def subset_glyphs (self, s):
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400529 c = self.__classify_context ()
530
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400531 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400532 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400533 rss = getattr (self, c.RuleSet)
534 rss = [rss[i] for i in indices]
535 for rs in rss:
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400536 if not rs: continue
537 ss = getattr (rs, c.Rule)
538 ss = [r for r in ss \
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400539 if r and all (all (g in s.glyphs for g in glist) \
540 for glist in c.RuleData (r))]
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400541 setattr (rs, c.Rule, ss)
542 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400543 # Prune empty subrulesets
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400544 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400545 setattr (self, c.RuleSet, rss)
546 setattr (self, c.RuleSetCount, len (rss))
547 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400548 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400549 if not self.Coverage.subset (s.glyphs):
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400550 return False
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400551 indices = getattr (self, c.ClassDef).subset (self.Coverage.glyphs, remap=False)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400552 rss = getattr (self, c.RuleSet)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400553 rss = [rss[i] for i in indices]
554 ContextData = c.ContextData (self)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400555 klass_maps = [x.subset (s.glyphs, remap=True) for x in ContextData]
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400556 for rs in rss:
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400557 if not rs: continue
558 ss = getattr (rs, c.Rule)
559 ss = [r for r in ss \
560 if r and all (all (k in klass_map for k in klist) \
561 for klass_map,klist in zip (klass_maps, c.RuleData (r)))]
562 setattr (rs, c.Rule, ss)
563 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400564
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400565 # Remap rule classes
566 for r in ss:
567 c.SetRuleData (r, [[klass_map.index (k) for k in klist] \
568 for klass_map,klist in zip (klass_maps, c.RuleData (r))])
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400569 # Prune empty subrulesets
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400570 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
571 setattr (self, c.RuleSet, rss)
572 setattr (self, c.RuleSetCount, len (rss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400573 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400574 elif self.Format == 3:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400575 return all (x.subset (s.glyphs) for x in c.RuleData (self))
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400576 else:
577 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400578
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400579@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
580 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400581def subset_lookups (self, lookup_indices):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400582 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400583
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400584 if self.Format in [1, 2]:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400585 for rs in getattr (self, c.RuleSet):
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400586 if not rs: continue
587 for r in getattr (rs, c.Rule):
588 if not r: continue
589 setattr (r, c.LookupRecord, [ll for ll in getattr (r, c.LookupRecord) if ll \
590 if ll.LookupListIndex in lookup_indices])
591 for ll in getattr (r, c.LookupRecord):
592 if not ll: continue
593 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400594 elif self.Format == 3:
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400595 setattr (self, c.LookupRecord, [ll for ll in getattr (self, c.LookupRecord) if ll \
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400596 if ll.LookupListIndex in lookup_indices])
597 for ll in getattr (self, c.LookupRecord):
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400598 if not ll: continue
599 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400600 else:
601 assert 0, "unknown format: %s" % self.Format
602
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400603@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
604 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400605def collect_lookups (self):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400606 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400607
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400608 if self.Format in [1, 2]:
Behdad Esfahbod27108392013-07-23 16:40:47 -0400609 return [ll.LookupListIndex \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400610 for rs in getattr (self, c.RuleSet) if rs \
611 for r in getattr (rs, c.Rule) if r \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400612 for ll in getattr (r, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400613 elif self.Format == 3:
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400614 return [ll.LookupListIndex \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400615 for ll in getattr (self, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400616 else:
617 assert 0, "unknown format: %s" % self.Format
618
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400619@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400620def closure_glyphs (self, s, cur_glyphs=None):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400621 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400622 return self.ExtSubTable.closure_glyphs (s, cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400623 else:
624 assert 0, "unknown format: %s" % self.Format
625
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400626@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
627def may_have_non_1to1 (self):
628 if self.Format == 1:
629 return self.ExtSubTable.may_have_non_1to1 ()
630 else:
631 assert 0, "unknown format: %s" % self.Format
632
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400633@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400634def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400635 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400636 return self.ExtSubTable.subset_glyphs (s)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400637 else:
638 assert 0, "unknown format: %s" % self.Format
639
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400640@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
641def subset_lookups (self, lookup_indices):
642 if self.Format == 1:
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400643 return self.ExtSubTable.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400644 else:
645 assert 0, "unknown format: %s" % self.Format
646
647@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
648def collect_lookups (self):
649 if self.Format == 1:
650 return self.ExtSubTable.collect_lookups ()
651 else:
652 assert 0, "unknown format: %s" % self.Format
653
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400654@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400655def closure_glyphs (self, s, cur_glyphs=None):
656 return sum ((st.closure_glyphs (s, cur_glyphs) for st in self.SubTable if st), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400657
658@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400659def subset_glyphs (self, s):
660 self.SubTable = [st for st in self.SubTable if st and st.subset_glyphs (s)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400661 self.SubTableCount = len (self.SubTable)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400662 return bool (self.SubTableCount)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400663
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400664@add_method(fontTools.ttLib.tables.otTables.Lookup)
665def subset_lookups (self, lookup_indices):
666 for s in self.SubTable:
667 s.subset_lookups (lookup_indices)
668
669@add_method(fontTools.ttLib.tables.otTables.Lookup)
670def collect_lookups (self):
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400671 return unique_sorted (sum ((st.collect_lookups () for st in self.SubTable if st), []))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400672
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400673@add_method(fontTools.ttLib.tables.otTables.Lookup)
674def may_have_non_1to1 (self):
675 return any (st.may_have_non_1to1 () for st in self.SubTable if st)
676
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400677@add_method(fontTools.ttLib.tables.otTables.LookupList)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400678def subset_glyphs (self, s):
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400679 "Returns the indices of nonempty lookups."
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400680 return [i for (i,l) in enumerate (self.Lookup) if l and l.subset_glyphs (s)]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400681
682@add_method(fontTools.ttLib.tables.otTables.LookupList)
683def subset_lookups (self, lookup_indices):
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400684 self.Lookup = [self.Lookup[i] for i in lookup_indices if i < self.LookupCount]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400685 self.LookupCount = len (self.Lookup)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400686 for l in self.Lookup:
687 l.subset_lookups (lookup_indices)
688
689@add_method(fontTools.ttLib.tables.otTables.LookupList)
690def closure_lookups (self, lookup_indices):
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400691 lookup_indices = unique_sorted (lookup_indices)
692 recurse = lookup_indices
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400693 while True:
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400694 recurse_lookups = sum ((self.Lookup[i].collect_lookups () for i in recurse if i < self.LookupCount), [])
695 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 -0400696 if not recurse_lookups:
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400697 return unique_sorted (lookup_indices)
698 recurse_lookups = unique_sorted (recurse_lookups)
699 lookup_indices.extend (recurse_lookups)
700 recurse = recurse_lookups
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400701
702@add_method(fontTools.ttLib.tables.otTables.Feature)
703def subset_lookups (self, lookup_indices):
704 self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices]
705 # Now map them.
706 self.LookupListIndex = [lookup_indices.index (l) for l in self.LookupListIndex]
707 self.LookupCount = len (self.LookupListIndex)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400708 return self.LookupCount
Behdad Esfahbod54660612013-07-21 18:16:55 -0400709
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400710@add_method(fontTools.ttLib.tables.otTables.Feature)
711def collect_lookups (self):
712 return self.LookupListIndex[:]
713
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400714@add_method(fontTools.ttLib.tables.otTables.FeatureList)
715def subset_lookups (self, lookup_indices):
716 "Returns the indices of nonempty features."
717 feature_indices = [i for (i,f) in enumerate (self.FeatureRecord) if f.Feature.subset_lookups (lookup_indices)]
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400718 self.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400719 return feature_indices
720
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400721@add_method(fontTools.ttLib.tables.otTables.FeatureList)
722def collect_lookups (self, feature_indices):
723 return unique_sorted (sum ((self.FeatureRecord[i].Feature.collect_lookups () for i in feature_indices
724 if i < self.FeatureCount), []))
725
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400726@add_method(fontTools.ttLib.tables.otTables.FeatureList)
727def subset_features (self, feature_indices):
728 self.FeatureRecord = [self.FeatureRecord[i] for i in feature_indices]
729 self.FeatureCount = len (self.FeatureRecord)
730 return bool (self.FeatureCount)
731
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400732@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
733def subset_features (self, feature_indices):
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400734 if self.ReqFeatureIndex in feature_indices:
735 self.ReqFeatureIndex = feature_indices.index (self.ReqFeatureIndex)
736 else:
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400737 self.ReqFeatureIndex = 65535
738 self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400739 # Now map them.
740 self.FeatureIndex = [feature_indices.index (f) for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400741 self.FeatureCount = len (self.FeatureIndex)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400742 return bool (self.FeatureCount or self.ReqFeatureIndex != 65535)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400743
744@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
745def collect_features (self):
746 feature_indices = self.FeatureIndex[:]
747 if self.ReqFeatureIndex != 65535:
748 feature_indices.append (self.ReqFeatureIndex)
749 return unique_sorted (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400750
751@add_method(fontTools.ttLib.tables.otTables.Script)
752def subset_features (self, feature_indices):
753 if self.DefaultLangSys and not self.DefaultLangSys.subset_features (feature_indices):
754 self.DefaultLangSys = None
755 self.LangSysRecord = [l for l in self.LangSysRecord if l.LangSys.subset_features (feature_indices)]
756 self.LangSysCount = len (self.LangSysRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400757 return bool (self.LangSysCount or self.DefaultLangSys)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400758
759@add_method(fontTools.ttLib.tables.otTables.Script)
760def collect_features (self):
Behdad Esfahbod2307c8b2013-07-23 11:18:13 -0400761 feature_indices = [l.LangSys.collect_features () for l in self.LangSysRecord]
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400762 if self.DefaultLangSys:
763 feature_indices.append (self.DefaultLangSys.collect_features ())
764 return unique_sorted (sum (feature_indices, []))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400765
766@add_method(fontTools.ttLib.tables.otTables.ScriptList)
767def subset_features (self, feature_indices):
768 self.ScriptRecord = [s for s in self.ScriptRecord if s.Script.subset_features (feature_indices)]
769 self.ScriptCount = len (self.ScriptRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400770 return bool (self.ScriptCount)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400771
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400772@add_method(fontTools.ttLib.tables.otTables.ScriptList)
773def collect_features (self):
774 return unique_sorted (sum ((s.Script.collect_features () for s in self.ScriptRecord), []))
775
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400776@add_method(fontTools.ttLib.getTableClass('GSUB'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400777def closure_glyphs (self, s):
778 s.table = self.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400779 feature_indices = self.table.ScriptList.collect_features ()
780 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400781 orig_glyphs = s.glyphs
782 glyphs = unique_sorted (s.glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400783 while True:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400784 s.glyphs = glyphs
785 additions = (sum ((self.table.LookupList.Lookup[i].closure_glyphs (s) \
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400786 for i in lookup_indices if i < self.table.LookupList.LookupCount), []))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400787 additions = unique_sorted (g for g in additions if g not in glyphs)
788 if not additions:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400789 s.glyphs = orig_glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400790 return glyphs
791 glyphs.extend (additions)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400792 del s.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400793
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400794@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400795def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400796 s.glyphs = s.glyphs_gsubed
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400797 lookup_indices = self.table.LookupList.subset_glyphs (s)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400798 self.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400799 self.prune_lookups ()
800 return True
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400801
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400802@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400803def subset_lookups (self, lookup_indices):
804 "Retrains specified lookups, then removes empty features, language systems, and scripts."
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400805 self.table.LookupList.subset_lookups (lookup_indices)
806 feature_indices = self.table.FeatureList.subset_lookups (lookup_indices)
807 self.table.ScriptList.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400808
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400809@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
810def prune_lookups (self):
811 "Remove unreferenced lookups"
812 feature_indices = self.table.ScriptList.collect_features ()
813 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
814 lookup_indices = self.table.LookupList.closure_lookups (lookup_indices)
815 self.subset_lookups (lookup_indices)
816
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400817@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
818def subset_feature_tags (self, feature_tags):
819 feature_indices = [i for (i,f) in enumerate (self.table.FeatureList.FeatureRecord) if f.FeatureTag in feature_tags]
820 self.table.FeatureList.subset_features (feature_indices)
821 self.table.ScriptList.subset_features (feature_indices)
822
823@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400824def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400825 if options.layout_features and '*' not in options.layout_features:
826 self.subset_feature_tags (options.layout_features)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400827 self.prune_lookups ()
828 return True
829
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400830@add_method(fontTools.ttLib.getTableClass('GDEF'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400831def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400832 glyphs = s.glyphs_gsubed
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400833 table = self.table
834 if table.LigCaretList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400835 indices = table.LigCaretList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400836 table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i] for i in indices]
837 table.LigCaretList.LigGlyphCount = len (table.LigCaretList.LigGlyph)
838 if not table.LigCaretList.LigGlyphCount:
839 table.LigCaretList = None
840 if table.MarkAttachClassDef:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400841 table.MarkAttachClassDef.classDefs = {g:v for g,v in table.MarkAttachClassDef.classDefs.items() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400842 if not table.MarkAttachClassDef.classDefs:
843 table.MarkAttachClassDef = None
844 if table.GlyphClassDef:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400845 table.GlyphClassDef.classDefs = {g:v for g,v in table.GlyphClassDef.classDefs.items() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400846 if not table.GlyphClassDef.classDefs:
847 table.GlyphClassDef = None
848 if table.AttachList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400849 indices = table.AttachList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400850 table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i] for i in indices]
851 table.AttachList.GlyphCount = len (table.AttachList.AttachPoint)
852 if not table.AttachList.GlyphCount:
853 table.AttachList = None
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400854 return bool (table.LigCaretList or table.MarkAttachClassDef or table.GlyphClassDef or table.AttachList)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400855
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400856@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbodd4e33a72013-07-24 18:51:05 -0400857def prune_pre_subset (self, options):
858 # Prune unknown kern table types
859 self.kernTables = [t for t in self.kernTables if hasattr (t, 'kernTable')]
860 return bool (self.kernTables)
861
862@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400863def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400864 glyphs = s.glyphs_gsubed
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400865 for t in self.kernTables:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400866 t.kernTable = {(a,b):v for ((a,b),v) in t.kernTable.items() if a in glyphs and b in glyphs}
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400867 self.kernTables = [t for t in self.kernTables if t.kernTable]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400868 return bool (self.kernTables)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400869
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400870@add_method(fontTools.ttLib.getTableClass('hmtx'), fontTools.ttLib.getTableClass('vmtx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400871def subset_glyphs (self, s):
872 self.metrics = {g:v for g,v in self.metrics.items() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400873 return bool (self.metrics)
Behdad Esfahbodc7160442013-07-22 14:29:08 -0400874
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400875@add_method(fontTools.ttLib.getTableClass('hdmx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400876def subset_glyphs (self, s):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400877 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 -0400878 return bool (self.hdmx)
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400879
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400880@add_method(fontTools.ttLib.getTableClass('VORG'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400881def subset_glyphs (self, s):
882 self.VOriginRecords = {g:v for g,v in self.VOriginRecords.items() if g in s.glyphs}
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400883 self.numVertOriginYMetrics = len (self.VOriginRecords)
884 return True # Never drop; has default metrics
885
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400886@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400887def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400888 if not options.glyph_names:
Behdad Esfahbod42648242013-07-23 12:56:06 -0400889 self.formatType = 3.0
890 return True
891
892@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400893def subset_glyphs (self, s):
Behdad Esfahbod42648242013-07-23 12:56:06 -0400894 self.extraNames = [] # This seems to do it
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -0400895 return True
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400896
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400897# Copied from _g_l_y_f.py
898ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes
899ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points
900ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true
901WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0
902NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!)
903MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one
904WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy
905WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11
906WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow
907USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph
908OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts
909SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple)
910UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS)
911
912@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
913def getComponentNamesFast (self, glyfTable):
914 if struct.unpack(">h", self.data[:2])[0] >= 0:
915 return [] # Not composite
916 data = self.data
917 i = 10
918 components = []
919 more = 1
920 while more:
921 flags, glyphID = struct.unpack(">HH", data[i:i+4])
922 i += 4
923 flags = int(flags)
924 components.append (glyfTable.getGlyphName (int (glyphID)))
925
926 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
927 else: i += 2
928 if flags & WE_HAVE_A_SCALE: i += 2
929 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
930 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
931 more = flags & MORE_COMPONENTS
932 return components
933
934@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
935def remapComponentsFast (self, indices):
936 if struct.unpack(">h", self.data[:2])[0] >= 0:
937 return # Not composite
938 data = bytearray (self.data)
939 i = 10
940 more = 1
941 while more:
942 flags = (data[i] << 8) | data[i+1]
943 glyphID = (data[i+2] << 8) | data[i+3]
944 # Remap
945 glyphID = indices.index (glyphID)
946 data[i+2] = glyphID >> 8
947 data[i+3] = glyphID & 0xFF
948 i += 4
949 flags = int(flags)
950
951 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
952 else: i += 2
953 if flags & WE_HAVE_A_SCALE: i += 2
954 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
955 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
956 more = flags & MORE_COMPONENTS
957 self.data = str (data)
958
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400959@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
960def dropInstructionsFast (self):
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400961 numContours = struct.unpack(">h", self.data[:2])[0]
962 data = bytearray (self.data)
963 i = 10
964 if numContours >= 0:
965 i += 2 * numContours # endPtsOfContours
966 instructionLen = (data[i] << 8) | data[i+1]
967 # Zero it
968 data[i] = data [i+1] = 0
969 i += 2
Behdad Esfahbod0fb69882013-07-24 17:25:35 -0400970 if instructionLen:
971 # Splice it out
972 data = data[:i] + data[i+instructionLen:]
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400973 else:
974 more = 1
975 while more:
976 flags = (data[i] << 8) | data[i+1]
977 # Turn instruction flag off
978 flags &= ~WE_HAVE_INSTRUCTIONS
979 data[i+0] = flags >> 8
980 data[i+1] = flags & 0xFF
981 i += 4
982 flags = int(flags)
983
984 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
985 else: i += 2
986 if flags & WE_HAVE_A_SCALE: i += 2
987 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
988 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
989 more = flags & MORE_COMPONENTS
990 # Cut off
991 data = data[:i]
992 if len(data) % 4:
993 # add pad bytes
994 nPadBytes = 4 - (len(data) % 4)
995 for i in range (nPadBytes):
996 data.append (0)
997 self.data = str (data)
998
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400999@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -04001000def closure_glyphs (self, s):
1001 glyphs = unique_sorted (s.glyphs)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001002 decompose = glyphs
1003 # I don't know if component glyphs can be composite themselves.
1004 # We handle them anyway.
1005 while True:
1006 components = []
1007 for g in decompose:
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001008 if g not in self.glyphs:
Behdad Esfahbodf8c20e42013-07-23 23:13:23 -04001009 continue
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001010 gl = self.glyphs[g]
1011 if hasattr (gl, "data"):
1012 for c in gl.getComponentNamesFast (self):
1013 if c not in glyphs:
1014 components.append (c)
1015 else:
1016 # TTX seems to expand gid0..3 always
1017 if gl.isComposite ():
1018 for c in gl.components:
1019 if c.glyphName not in glyphs:
1020 components.append (c.glyphName)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001021 components = [c for c in components if c not in glyphs]
1022 if not components:
1023 return glyphs
1024 decompose = unique_sorted (components)
1025 glyphs.extend (components)
1026
1027@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001028def subset_glyphs (self, s):
1029 self.glyphs = {g:v for g,v in self.glyphs.items() if g in s.glyphs}
1030 indices = [i for i,g in enumerate (self.glyphOrder) if g in s.glyphs]
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001031 for v in self.glyphs.values ():
1032 if hasattr (v, "data"):
1033 v.remapComponentsFast (indices)
1034 else:
1035 pass # No need
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001036 self.glyphOrder = [g for g in self.glyphOrder if g in s.glyphs]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -04001037 return bool (self.glyphs)
Behdad Esfahbod861d9152013-07-22 16:47:24 -04001038
Behdad Esfahboded98c612013-07-23 12:37:41 -04001039@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -04001040def prune_post_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001041 if not options.hinting:
Behdad Esfahbod6ec88542013-07-24 16:52:47 -04001042 for v in self.glyphs.values ():
1043 if hasattr (v, "data"):
1044 v.dropInstructionsFast ()
1045 else:
1046 v.program = fontTools.ttLib.tables.ttProgram.Program()
1047 v.program.fromBytecode([])
Behdad Esfahboded98c612013-07-23 12:37:41 -04001048 return True
1049
Behdad Esfahbod2b677c82013-07-23 13:37:13 -04001050@add_method(fontTools.ttLib.getTableClass('CFF '))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001051def subset_glyphs (self, s):
Behdad Esfahbod2b677c82013-07-23 13:37:13 -04001052 assert 0, "unimplemented"
1053
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001054@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001055def closure_glyphs (self, s):
1056 tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [1, 10]]
1057 extra = []
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001058 for u in s.unicodes_requested:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001059 found = False
1060 for table in tables:
1061 if u in table.cmap:
1062 extra.append (table.cmap[u])
1063 found = True
1064 break
1065 if not found:
1066 s.log ("No glyph for Unicode value %s; skipping." % u)
1067 return extra
1068
1069@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001070def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001071 if not options.legacy_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -04001072 # Drop non-Unicode / non-Symbol cmaps
1073 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 -04001074 if not options.symbol_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -04001075 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 -04001076 # TODO Only keep one subtable?
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001077 # For now, drop format=0 which can't be subset_glyphs easily?
1078 self.tables = [t for t in self.tables if t.format != 0]
1079 return bool (self.tables)
1080
1081@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001082def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -04001083 s.glyphs = s.glyphs_cmaped
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001084 for t in self.tables:
Behdad Esfahbod9453a362013-07-22 16:21:24 -04001085 # For reasons I don't understand I need this here
1086 # to force decompilation of the cmap format 14.
1087 try:
1088 getattr (t, "asdf")
1089 except AttributeError:
1090 pass
Behdad Esfahbodb13d7902013-07-22 16:01:15 -04001091 if t.format == 14:
Behdad Esfahbod9453a362013-07-22 16:21:24 -04001092 # XXX We drop all the default-UVS mappings (g==None)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001093 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 -04001094 t.uvsDict = {v:l for (v,l) in t.uvsDict.items() if l}
1095 else:
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001096 t.cmap = {u:g for (u,g) in t.cmap.items() if g in s.glyphs_requested or u in s.unicodes_requested}
Behdad Esfahbodb13d7902013-07-22 16:01:15 -04001097 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 -04001098 # XXX Convert formats when needed
Behdad Esfahbod2ac36302013-08-08 23:49:00 -04001099 # In particular, if we have a format=12 without non-BMP
1100 # characters, either drop format=12 one or convert it
1101 # to format=4 if there's not one.
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001102 return bool (self.tables)
1103
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001104@add_method(fontTools.ttLib.getTableClass('name'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -04001105def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001106 if '*' not in options.name_IDs:
1107 self.names = [n for n in self.names if n.nameID in options.name_IDs]
1108 if not options.name_legacy:
Behdad Esfahbod20faeb02013-07-23 13:19:03 -04001109 self.names = [n for n in self.names if n.platformID == 3 and n.platEncID == 1]
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001110 if '*' not in options.name_languages:
1111 self.names = [n for n in self.names if n.langID in options.name_languages]
Behdad Esfahbod20faeb02013-07-23 13:19:03 -04001112 return True # Retain even if empty
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001113
Behdad Esfahbod8c646f62013-07-22 15:06:23 -04001114
Behdad Esfahbodbc25f162013-07-23 12:56:54 -04001115drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'PCLT', 'LTSH']
Behdad Esfahbod103a12f2013-07-23 15:08:39 -04001116drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill'] # Graphite
Behdad Esfahbod38e852c2013-07-23 16:56:50 -04001117drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL'] # Color
Behdad Esfahboded98c612013-07-23 12:37:41 -04001118no_subset_tables = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2', 'loca', 'name', 'cvt ', 'fpgm', 'prep']
Behdad Esfahbodbc25f162013-07-23 12:56:54 -04001119hinting_tables = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
Behdad Esfahbod29df0462013-07-23 11:05:25 -04001120
Behdad Esfahbod356c42e2013-07-23 12:10:46 -04001121# Based on HarfBuzz shapers
1122layout_features_dict = {
1123 # Default shaper
1124 'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
1125 'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
1126 'vertical': ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
1127 'ltr': ['ltra', 'ltrm'],
1128 'rtl': ['rtla', 'rtlm'],
1129 # Complex shapers
Behdad Esfahbodf36b5a92013-08-04 16:54:46 -04001130 'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3', 'cswh', 'mset'],
Behdad Esfahbod356c42e2013-07-23 12:10:46 -04001131 'hangul': ['ljmo', 'vjmo', 'tjmo'],
1132 'tibetal': ['abvs', 'blws', 'abvm', 'blwm'],
1133 'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half', 'abvf', 'pstf', 'cfar', 'vatu', 'cjct',
1134 'init', 'pres', 'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
1135}
1136layout_features_all = unique_sorted (sum (layout_features_dict.values (), []))
1137
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -04001138# TODO OS/2 ulUnicodeRange / ulCodePageRange?
Behdad Esfahbodf71267b2013-07-23 12:59:13 -04001139# TODO Drop unneeded GSUB/GPOS Script/LangSys entries
Behdad Esfahbod398d3892013-07-23 15:29:40 -04001140# TODO Avoid recursing too much
Behdad Esfahbode94aa0e2013-07-23 13:22:04 -04001141# TODO Text direction considerations
1142# TODO Text script / language considerations
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001143# TODO Drop unknown tables? Using DefaultTable.prune?
Behdad Esfahbod8c4f7cc2013-07-24 17:58:29 -04001144# TODO Drop GPOS Device records if not hinting?
Behdad Esfahbod93e26362013-08-09 14:22:48 -04001145# TODO Hookup options.verbose to font.verbose?
1146# TODO Move font name loading hack to Subsetter?
Behdad Esfahbod56ebd042013-07-22 13:02:24 -04001147
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001148
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001149class Subsetter:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001150
1151 class Options:
1152 drop_tables = drop_tables_default
1153 layout_features = layout_features_all
1154 hinting = False
1155 glyph_names = False
1156 legacy_cmap = False
1157 symbol_cmap = False
1158 name_IDs = [1, 2] # Family and Style
1159 name_legacy = False
1160 name_languages = [0x0409] # English
1161 mandatory_glyphs = True # First four for TrueType, .notdef for CFF
1162 recalc_bboxes = False # Slows us down
1163
1164 def __init__ (self, **kwargs):
1165
1166 self.set (**kwargs)
1167
1168 def set (self, **kwargs):
1169 for k,v in kwargs.items ():
1170 if not hasattr (self, k):
1171 raise Exception ("Unknown option '%s'" % k)
1172 setattr (self, k, v)
1173
1174 def parse_opts (self, argv, ignore_unknown=False):
1175 ret = []
1176 opts = {}
1177 for a in argv:
1178 if not a.startswith ('--'):
1179 ret.append (a)
1180 continue
1181 a = a[2:]
1182 i = a.find ('=')
1183 if i == -1:
1184 if a.startswith ("no-"):
1185 k = a[3:]
1186 v = False
1187 else:
1188 k = a
1189 v = True
1190 else:
1191 k = a[:i]
1192 v = a[i+1:]
1193 k = k.replace ('-', '_')
1194 if not hasattr (self, k):
1195 if ignore_unknown:
1196 ret.append (a)
1197 continue
1198 else:
1199 raise Exception ("Unknown option '%s'" % a)
1200
1201 ov = getattr (self, k)
1202 if isinstance (ov, bool):
1203 v = bool (v)
1204 elif isinstance (ov, int):
1205 v = int (v)
1206 elif isinstance (ov, list):
1207 v = v.split (',')
1208 v = [int (x, 0) if x[0] in range (10) else x for x in v]
1209
1210 opts[k] = v
1211 self.set (**opts)
1212
1213 return ret
1214
1215
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001216 def __init__ (self, font=None, options=None, log=None):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001217
1218 if isinstance (font, basestring):
1219 font = fontTools.ttx.TTFont (font)
1220 if not log:
1221 log = Logger()
1222 if not options:
1223 options = Options()
1224
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001225 self.font = font
1226 self.options = options
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001227 self.log = log
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001228 self.unicodes_requested = set ()
1229 self.glyphs_requested = set ()
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001230
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001231 def populate (self, glyphs=[], unicodes=[], text=""):
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001232 self.unicodes_requested.update (unicodes)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001233 if isinstance (text, str):
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001234 text = text.decode ("utf8")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001235 for u in text:
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001236 self.unicodes_requested.add (ord (u))
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001237 self.glyphs_requested.update (glyphs)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001238
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001239 def pre_prune (self):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001240
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001241 for tag in self.font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001242 if tag == 'GlyphOrder': continue
1243
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001244 if tag in self.options.drop_tables or \
1245 (tag in hinting_tables and not self.options.hinting):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001246 self.log (tag, "dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001247 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001248 continue
1249
1250 clazz = fontTools.ttLib.getTableClass(tag)
1251
1252 if hasattr (clazz, 'prune_pre_subset'):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001253 table = self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001254 retain = table.prune_pre_subset (self.options)
1255 self.log.lapse ("prune '%s'" % tag)
1256 if not retain:
1257 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001258 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001259 continue
1260 else:
1261 self.log (tag, "pruned")
1262
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001263 def closure_glyphs (self):
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001264
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001265 self.glyphs = self.glyphs_requested
1266
1267 if 'cmap' in self.font:
1268 extra_glyphs = self.font['cmap'].closure_glyphs (self)
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001269 self.glyph = self.glyphs.copy ()
1270 self.glyphs.update (extra_glyphs)
1271 self.glyphs_cmaped = self.glyphs
1272
1273 if self.options.mandatory_glyphs:
1274 self.glyphs = self.glyphs.copy ()
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001275 if 'glyf' in self.font:
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001276 for i in range (4):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001277 self.glyphs.add (self.font.getGlyphName (i))
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001278 self.log ("Added first four glyphs to subset")
1279 else:
1280 self.glyphs.add ('.notdef')
1281 self.log ("Added .notdef glyph to subset")
1282
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001283 if 'GSUB' in self.font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001284 self.log ("Closing glyph list over 'GSUB': %d glyphs before" % len (self.glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001285 self.log.glyphs (self.glyphs, font=self.font)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001286 self.glyphs = set (self.font['GSUB'].closure_glyphs (self))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001287 self.log ("Closed glyph list over 'GSUB': %d glyphs after" % len (self.glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001288 self.log.glyphs (self.glyphs, font=self.font)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001289 self.log.lapse ("close glyph list over 'GSUB'")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001290 self.glyphs_gsubed = self.glyphs
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001291
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001292 if 'glyf' in self.font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001293 self.log ("Closing glyph list over 'glyf': %d glyphs before" % len (self.glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001294 self.log.glyphs (self.glyphs, font=self.font)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001295 self.glyphs = set (self.font['glyf'].closure_glyphs (self))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001296 self.log ("Closed glyph list over 'glyf': %d glyphs after" % len (self.glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001297 self.log.glyphs (self.glyphs, font=self.font)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001298 self.log.lapse ("close glyph list over 'glyf'")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001299 self.glyphs_glyfed = self.glyphs
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001300
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001301 self.glyphs_all = self.glyphs
1302
1303 self.log ("Retaining %d glyphs: " % len (self.glyphs_all))
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001304
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001305 def subset_glyphs (self):
1306 for tag in self.font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001307 if tag == 'GlyphOrder': continue
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001308 clazz = fontTools.ttLib.getTableClass(tag)
1309
1310 if tag in no_subset_tables:
1311 self.log (tag, "subsetting not needed")
1312 elif hasattr (clazz, 'subset_glyphs'):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001313 table = self.font[tag]
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -04001314 self.glyphs = self.glyphs_all
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001315 retain = table.subset_glyphs (self)
1316 self.log.lapse ("subset '%s'" % tag)
1317 if not retain:
1318 self.log (tag, "subsetted to empty; dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001319 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001320 else:
1321 self.log (tag, "subsetted")
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001322 else:
1323 self.log (tag, "NOT subset; don't know how to subset")
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001324
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001325 glyphOrder = self.font.getGlyphOrder()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001326 glyphOrder = [g for g in glyphOrder if g in self.glyphs_all]
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001327 self.font.setGlyphOrder (glyphOrder)
1328 self.font._buildReverseGlyphOrderDict ()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001329 self.log.lapse ("subset GlyphOrder")
1330
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001331 def post_prune (self):
1332 for tag in self.font.keys():
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001333 if tag == 'GlyphOrder': continue
1334 clazz = fontTools.ttLib.getTableClass(tag)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001335 if hasattr (clazz, 'prune_post_subset'):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001336 table = self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001337 retain = table.prune_post_subset (self.options)
1338 self.log.lapse ("prune '%s'" % tag)
1339 if not retain:
1340 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001341 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001342 else:
1343 self.log (tag, "pruned")
1344
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001345 def subset (self, font):
1346
1347 self.font = font
Behdad Esfahbod756af492013-08-01 12:05:26 -04001348
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001349 self.font.recalcBBoxes = self.options.recalc_bboxes
1350
1351 self.pre_prune ()
1352 self.closure_glyphs ()
1353 self.subset_glyphs ()
1354 self.post_prune ()
1355
Behdad Esfahbod756af492013-08-01 12:05:26 -04001356 del self.font
1357
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001358import sys, time
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001359
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001360class Logger:
1361
1362 def __init__ (self, verbose=False, xml=False, timing=False):
1363 self.verbose = verbose
1364 self.xml = xml
1365 self.timing = timing
1366 self.last_time = self.start_time = time.time ()
1367
1368 def parse_opts (self, argv):
1369 argv = argv[:]
1370 for v in ['verbose', 'xml', 'timing']:
1371 if "--"+v in argv:
1372 setattr (self, v, True)
1373 argv.remove ("--"+v)
1374 return argv
1375
1376 def __call__ (self, *things):
1377 if not self.verbose:
1378 return
1379 print ' '.join (str (x) for x in things)
1380
1381 def lapse (self, *things):
1382 if not self.timing:
1383 return
1384 new_time = time.time ()
1385 print "Took %0.3fs to %s" % (new_time - self.last_time, ' '.join (str (x) for x in things))
1386 self.last_time = new_time
1387
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001388 def glyphs (self, glyphs, glyph_names=True, font=None):
1389 self ("Names: ", sorted (glyphs))
1390 if font:
1391 glyphOrder = font.getGlyphOrder()
1392 self ("Gids : ", sorted (glyphOrder.index (g) for g in glyphs))
1393
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001394 def font (self, font, file=sys.stdout):
1395 if not self.xml:
1396 return
1397 import xmlWriter, sys
1398 writer = xmlWriter.XMLWriter (file)
1399 font.disassembleInstructions = False # Work around ttx bug
1400 for tag in font.keys():
1401 writer.begintag (tag)
1402 writer.newline ()
1403 font[tag].toXML(writer, font)
1404 writer.endtag (tag)
1405 writer.newline ()
1406
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001407def main (args):
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001408
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001409 log = Logger ()
1410 args = log.parse_opts (args)
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001411
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001412 options = Subsetter.Options ()
1413 args = options.parse_opts (args)
1414
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001415 if len (args) < 2:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001416 import sys
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001417 print >>sys.stderr, "usage: pyotlss.py font-file glyph..."
1418 sys.exit (1)
1419
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001420 fontfile = args[0]
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001421 args = args[1:]
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001422
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001423 # TODO Option for ignoreDecompileErrors?
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001424 font = fontTools.ttx.TTFont (fontfile)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001425 s = Subsetter (font=font, options=options, log=log)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001426 log.lapse ("load font")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001427
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001428 # Hack:
1429 #
1430 # If we don't need glyph names, change 'post' class to not try to
1431 # load them. It avoid lots of headache with broken fonts as well
1432 # as loading time.
1433 #
1434 # Ideally ttLib should provide a way to ask it to skip loading
1435 # glyph names. But it currently doesn't provide such a thing.
1436 #
1437 if not options.glyph_names \
Behdad Esfahbod9ae5d282013-08-08 21:18:17 -04001438 and all (any (g.startswith (p) for p in ['gid', 'glyph', 'uni', 'U+']) \
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001439 for g in args):
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001440 post = fontTools.ttLib.getTableClass('post')
1441 saved = post.decode_format_2_0
1442 post.decode_format_2_0 = post.decode_format_3_0
1443 f = font['post']
1444 if f.formatType == 2.0:
1445 f.formatType = 3.0
1446 post.decode_format_2_0 = saved
1447 del post, saved, f
1448
1449 names = font.getGlyphNames()
1450 log.lapse ("loading glyph names")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001451
1452 glyphs = []
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001453 unicodes = []
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001454 for g in args:
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001455 if g in names:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001456 glyphs.append (g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001457 continue
Behdad Esfahbod9ae5d282013-08-08 21:18:17 -04001458 if g.startswith ('uni') or g.startswith ('U+'):
1459 if g.startswith ('uni') and len (g) > 3:
1460 g = g[3:]
1461 elif g.startswith ('U+') and len (g) > 2:
1462 g = g[2:]
1463 u = int (g, 16)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001464 unicodes.append (u)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001465 continue
1466 if g.startswith ('gid') or g.startswith ('glyph'):
1467 if g.startswith ('gid') and len (g) > 3:
1468 g = g[3:]
1469 elif g.startswith ('glyph') and len (g) > 5:
1470 g = g[5:]
1471 try:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001472 glyphs.append (font.getGlyphName (int (g), requireReal=1))
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001473 except ValueError:
1474 raise Exception ("Invalid glyph identifier %s" % g)
1475 continue
1476 raise Exception ("Invalid glyph identifier %s" % g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001477 log.lapse ("compile glyph list")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001478 log ("Unicodes:", unicodes)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001479 log ("Glyphs:", glyphs)
1480
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001481 s.populate (glyphs=glyphs, unicodes=unicodes)
1482 s.subset (font)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -04001483
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001484 font.save (fontfile + '.subset')
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001485 log.lapse ("compile and save font")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001486
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001487 log.last_time = s.log.start_time
1488 log.lapse ("make one with everything (TOTAL TIME)")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001489
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001490 log.font (font)
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001491
1492if __name__ == '__main__':
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001493 import sys
1494 main (sys.argv[1:])