blob: 17d941fe07a668835e67f8f134b54c49e8cf1bb1 [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 Esfahbod14374262013-08-08 22:26:49 -040059@add_method(fontTools.ttLib.tables.otTables.Coverage)
60def remap (self, coverage_map):
61 "Remaps coverage."
62 self.glyphs = [self.glyphs[i] for i in coverage_map]
63
Behdad Esfahbod54660612013-07-21 18:16:55 -040064@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040065def intersect (self, glyphs):
Behdad Esfahbode10803e2013-08-08 21:09:27 -040066 "Returns ascending list of matching class values."
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040067 return unique_sorted (([0] if any (g not in self.classDefs for g in glyphs) else []) + \
Behdad Esfahbode10803e2013-08-08 21:09:27 -040068 [v for g,v in self.classDefs.items() if g in glyphs])
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040069
70@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040071def intersects_class (self, glyphs, klass):
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040072 "Returns true if any of glyphs has requested class."
Behdad Esfahbode10803e2013-08-08 21:09:27 -040073 assert isinstance (klass, int)
Behdad Esfahbod0befd6b2013-08-05 22:47:14 -040074 if klass == 0:
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040075 if any (g not in self.classDefs for g in glyphs):
Behdad Esfahbod0befd6b2013-08-05 22:47:14 -040076 return True
77 # Fall through
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040078 return any (g in glyphs for g,v in self.classDefs.items() if v == klass)
79
80@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040081def subset (self, glyphs, remap=False):
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040082 "Returns ascending list of remaining classes."
Behdad Esfahbod54660612013-07-21 18:16:55 -040083 self.classDefs = {g:v for g,v in self.classDefs.items() if g in glyphs}
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040084 # Note: while class 0 has the special meaning of "not matched", if no glyph will
85 # ever /not match/, we can optimize class 0 out too.
86 indices = unique_sorted (([0] if any (g not in self.classDefs for g in glyphs) else []) + \
87 self.classDefs.values ())
Behdad Esfahbodde71dca2013-07-24 12:40:54 -040088 if remap:
89 self.remap (indices)
90 return indices
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -040091
92@add_method(fontTools.ttLib.tables.otTables.ClassDef)
93def remap (self, class_map):
94 "Remaps classes."
95 self.classDefs = {g:class_map.index (v) for g,v in self.classDefs.items()}
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040096
Behdad Esfahbod54660612013-07-21 18:16:55 -040097@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -040098def closure_glyphs (self, s, cur_glyphs=None):
99 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400100 if self.Format in [1, 2]:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400101 return [v for g,v in self.mapping.items() if g in cur_glyphs]
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400102 else:
103 assert 0, "unknown format: %s" % self.Format
104
105@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400106def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400107 if self.Format in [1, 2]:
Behdad Esfahbod14374262013-08-08 22:26:49 -0400108 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 -0400109 return bool (self.mapping)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400110 else:
111 assert 0, "unknown format: %s" % self.Format
112
113@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400114def closure_glyphs (self, s, cur_glyphs=None):
115 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400116 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400117 indices = self.Coverage.intersect (cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400118 return sum ((self.Sequence[i].Substitute for i in indices), [])
119 else:
120 assert 0, "unknown format: %s" % self.Format
121
122@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400123def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400124 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400125 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400126 self.Sequence = [self.Sequence[i] for i in indices]
Behdad Esfahbod14374262013-08-08 22:26:49 -0400127 # Now drop rules generating glyphs we don't want
128 indices = [i for i,seq in enumerate (self.Sequence) \
129 if all (sub in s.glyphs for sub in seq.Substitute)]
130 self.Sequence = [self.Sequence[i] for i in indices]
131 self.Coverage.remap (indices)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400132 self.SequenceCount = len (self.Sequence)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400133 return bool (self.SequenceCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400134 else:
135 assert 0, "unknown format: %s" % self.Format
136
137@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400138def closure_glyphs (self, s, cur_glyphs=None):
139 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400140 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400141 return sum ((vlist for g,vlist in self.alternates.items() if g in cur_glyphs), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400142 else:
143 assert 0, "unknown format: %s" % self.Format
144
145@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400146def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400147 if self.Format == 1:
Behdad Esfahbod14374262013-08-08 22:26:49 -0400148 self.alternates = {g:vlist for g,vlist in self.alternates.items() \
149 if g in s.glyphs and all (v in s.glyphs for v in vlist)}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400150 return bool (self.alternates)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400151 else:
152 assert 0, "unknown format: %s" % self.Format
153
154@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400155def closure_glyphs (self, s, cur_glyphs=None):
156 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400157 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400158 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 -0400159 for g,seqs in self.ligatures.items() if g in cur_glyphs), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400160 else:
161 assert 0, "unknown format: %s" % self.Format
162
163@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400164def subset_glyphs (self, s):
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400165 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400166 self.ligatures = {g:v for g,v in self.ligatures.items() if g in s.glyphs}
Behdad Esfahbod14374262013-08-08 22:26:49 -0400167 self.ligatures = {g:[seq for seq in seqs \
168 if seq.LigGlyph in s.glyphs and \
169 all(c in s.glyphs for c in seq.Component)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400170 for g,seqs in self.ligatures.items()}
171 self.ligatures = {g:v for g,v in self.ligatures.items() if v}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400172 return bool (self.ligatures)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400173 else:
174 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400175
Behdad Esfahbod54660612013-07-21 18:16:55 -0400176@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400177def closure_glyphs (self, s, cur_glyphs=None):
178 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400179 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400180 indices = self.Coverage.intersect (cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400181 if not indices or \
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400182 not all (c.intersect (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400183 return []
184 return [self.Substitute[i] for i in indices]
185 else:
186 assert 0, "unknown format: %s" % self.Format
187
188@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400189def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400190 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400191 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400192 self.Substitute = [self.Substitute[i] for i in indices]
Behdad Esfahbod14374262013-08-08 22:26:49 -0400193 # Now drop rules generating glyphs we don't want
194 indices = [i for i,sub in enumerate (self.Substitute) \
195 if sub in s.glyphs]
196 self.Substitute = [self.Substitute[i] for i in indices]
197 self.Coverage.remap (indices)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400198 self.GlyphCount = len (self.Substitute)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400199 return bool (self.GlyphCount and all (c.subset (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400200 else:
201 assert 0, "unknown format: %s" % self.Format
202
203@add_method(fontTools.ttLib.tables.otTables.SinglePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400204def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400205 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400206 return len (self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400207 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400208 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400209 self.Value = [self.Value[i] for i in indices]
210 self.ValueCount = len (self.Value)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400211 return bool (self.ValueCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400212 else:
213 assert 0, "unknown format: %s" % self.Format
214
215@add_method(fontTools.ttLib.tables.otTables.PairPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400216def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400217 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400218 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400219 self.PairSet = [self.PairSet[i] for i in indices]
220 for p in self.PairSet:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400221 p.PairValueRecord = [r for r in p.PairValueRecord if r.SecondGlyph in s.glyphs]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400222 p.PairValueCount = len (p.PairValueRecord)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400223 self.PairSet = [p for p in self.PairSet if p.PairValueCount]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400224 self.PairSetCount = len (self.PairSet)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400225 return bool (self.PairSetCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400226 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400227 class1_map = self.ClassDef1.subset (s.glyphs, remap=True)
228 class2_map = self.ClassDef2.subset (s.glyphs, remap=True)
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -0400229 self.Class1Record = [self.Class1Record[i] for i in class1_map]
230 for c in self.Class1Record:
231 c.Class2Record = [c.Class2Record[i] for i in class2_map]
232 self.Class1Count = len (class1_map)
233 self.Class2Count = len (class2_map)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400234 return bool (self.Class1Count and self.Class2Count and self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400235 else:
236 assert 0, "unknown format: %s" % self.Format
237
238@add_method(fontTools.ttLib.tables.otTables.CursivePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400239def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400240 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400241 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400242 self.EntryExitRecord = [self.EntryExitRecord[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400243 self.EntryExitCount = len (self.EntryExitRecord)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400244 return bool (self.EntryExitCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400245 else:
246 assert 0, "unknown format: %s" % self.Format
247
248@add_method(fontTools.ttLib.tables.otTables.MarkBasePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400249def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400250 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400251 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400252 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
253 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400254 base_indices = self.BaseCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400255 self.BaseArray.BaseRecord = [self.BaseArray.BaseRecord[i] for i in base_indices]
256 self.BaseArray.BaseCount = len (self.BaseArray.BaseRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400257 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400258 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400259 self.ClassCount = len (class_indices)
260 for m in self.MarkArray.MarkRecord:
261 m.Class = class_indices.index (m.Class)
262 for b in self.BaseArray.BaseRecord:
263 b.BaseAnchor = [b.BaseAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400264 return bool (self.ClassCount and self.MarkArray.MarkCount and self.BaseArray.BaseCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400265 else:
266 assert 0, "unknown format: %s" % self.Format
267
268@add_method(fontTools.ttLib.tables.otTables.MarkLigPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400269def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400270 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400271 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400272 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
273 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400274 ligature_indices = self.LigatureCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400275 self.LigatureArray.LigatureAttach = [self.LigatureArray.LigatureAttach[i] for i in ligature_indices]
276 self.LigatureArray.LigatureCount = len (self.LigatureArray.LigatureAttach)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400277 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400278 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400279 self.ClassCount = len (class_indices)
280 for m in self.MarkArray.MarkRecord:
281 m.Class = class_indices.index (m.Class)
282 for l in self.LigatureArray.LigatureAttach:
283 for c in l.ComponentRecord:
284 c.LigatureAnchor = [c.LigatureAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400285 return bool (self.ClassCount and self.MarkArray.MarkCount and self.LigatureArray.LigatureCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400286 else:
287 assert 0, "unknown format: %s" % self.Format
288
289@add_method(fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400290def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400291 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400292 mark1_indices = self.Mark1Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400293 self.Mark1Array.MarkRecord = [self.Mark1Array.MarkRecord[i] for i in mark1_indices]
294 self.Mark1Array.MarkCount = len (self.Mark1Array.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400295 mark2_indices = self.Mark2Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400296 self.Mark2Array.Mark2Record = [self.Mark2Array.Mark2Record[i] for i in mark2_indices]
297 self.Mark2Array.MarkCount = len (self.Mark2Array.Mark2Record)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400298 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400299 class_indices = unique_sorted (v.Class for v in self.Mark1Array.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400300 self.ClassCount = len (class_indices)
301 for m in self.Mark1Array.MarkRecord:
302 m.Class = class_indices.index (m.Class)
303 for b in self.Mark2Array.Mark2Record:
304 b.Mark2Anchor = [b.Mark2Anchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400305 return bool (self.ClassCount and self.Mark1Array.MarkCount and self.Mark2Array.MarkCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400306 else:
307 assert 0, "unknown format: %s" % self.Format
308
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400309@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
310 fontTools.ttLib.tables.otTables.MultipleSubst,
311 fontTools.ttLib.tables.otTables.AlternateSubst,
312 fontTools.ttLib.tables.otTables.LigatureSubst,
313 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
314 fontTools.ttLib.tables.otTables.SinglePos,
315 fontTools.ttLib.tables.otTables.PairPos,
316 fontTools.ttLib.tables.otTables.CursivePos,
317 fontTools.ttLib.tables.otTables.MarkBasePos,
318 fontTools.ttLib.tables.otTables.MarkLigPos,
319 fontTools.ttLib.tables.otTables.MarkMarkPos)
320def subset_lookups (self, lookup_indices):
321 pass
322
323@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
324 fontTools.ttLib.tables.otTables.MultipleSubst,
325 fontTools.ttLib.tables.otTables.AlternateSubst,
326 fontTools.ttLib.tables.otTables.LigatureSubst,
327 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
328 fontTools.ttLib.tables.otTables.SinglePos,
329 fontTools.ttLib.tables.otTables.PairPos,
330 fontTools.ttLib.tables.otTables.CursivePos,
331 fontTools.ttLib.tables.otTables.MarkBasePos,
332 fontTools.ttLib.tables.otTables.MarkLigPos,
333 fontTools.ttLib.tables.otTables.MarkMarkPos)
334def collect_lookups (self):
335 return []
336
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400337@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
338 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
339def __classify_context (self):
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400340
341 class ContextHelper:
342 def __init__ (self, klass, Format):
343 if klass.__name__.endswith ('Subst'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400344 Typ = 'Sub'
345 Type = 'Subst'
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400346 else:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400347 Typ = 'Pos'
348 Type = 'Pos'
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400349 if klass.__name__.startswith ('Chain'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400350 Chain = 'Chain'
351 else:
352 Chain = ''
353 ChainTyp = Chain+Typ
354
355 self.Typ = Typ
356 self.Type = Type
357 self.Chain = Chain
358 self.ChainTyp = ChainTyp
359
360 self.LookupRecord = Type+'LookupRecord'
361
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400362 if Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400363 Coverage = lambda r: r.Coverage
364 ChainCoverage = lambda r: r.Coverage
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400365 ContextData = None
366 ChainContextData = None
367 RuleData = lambda r: r.Input
368 ChainRuleData = lambda r: r.Backtrack + r.Input + r.LookAhead
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400369 SetRuleData = None
370 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400371 elif Format == 2:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400372 Coverage = lambda r: r.Coverage
373 ChainCoverage = lambda r: r.Coverage
Behdad Esfahbode3f20732013-07-24 11:26:43 -0400374 ContextData = lambda r: (r.ClassDef,)
375 ChainContextData = lambda r: (r.LookAheadClassDef, r.InputClassDef, r.BacktrackClassDef)
376 RuleData = lambda r: (r.Class,)
377 ChainRuleData = lambda r: (r.LookAhead, r.Input, r.Backtrack)
378 def SetRuleData (r, d): (r.Class,) = d
379 def ChainSetRuleData (r, d): (r.LookAhead, r.Input, r.Backtrack) = d
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400380 elif Format == 3:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400381 Coverage = lambda r: r.Coverage[0]
382 ChainCoverage = lambda r: r.InputCoverage[0]
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400383 ContextData = None
384 ChainContextData = None
385 RuleData = lambda r: r.Coverage
386 ChainRuleData = lambda r: r.LookAheadCoverage + r.InputCoverage + r.BacktrackCoverage
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400387 SetRuleData = None
388 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400389 else:
390 assert 0, "unknown format: %s" % Format
391
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400392 if Chain:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400393 self.Coverage = ChainCoverage
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400394 self.ContextData = ChainContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400395 self.RuleData = ChainRuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400396 self.SetRuleData = ChainSetRuleData
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400397 else:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400398 self.Coverage = Coverage
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400399 self.ContextData = ContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400400 self.RuleData = RuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400401 self.SetRuleData = SetRuleData
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400402
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400403 if Format == 1:
404 self.Rule = ChainTyp+'Rule'
405 self.RuleCount = ChainTyp+'RuleCount'
406 self.RuleSet = ChainTyp+'RuleSet'
407 self.RuleSetCount = ChainTyp+'RuleSetCount'
408 elif Format == 2:
409 self.Rule = ChainTyp+'ClassRule'
410 self.RuleCount = ChainTyp+'ClassRuleCount'
411 self.RuleSet = ChainTyp+'ClassSet'
412 self.RuleSetCount = ChainTyp+'ClassSetCount'
Behdad Esfahbod89987002013-07-23 23:07:42 -0400413
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400414 self.ClassDef = 'InputClassDef' if Chain else 'ClassDef'
Behdad Esfahbod27108392013-07-23 16:40:47 -0400415
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400416 if self.Format not in [1, 2, 3]:
417 return None # Don't shoot the messenger; let it go
418 if not hasattr (self.__class__, "__ContextHelpers"):
419 self.__class__.__ContextHelpers = {}
420 if self.Format not in self.__class__.__ContextHelpers:
421 self.__class__.__ContextHelpers[self.Format] = ContextHelper (self.__class__, self.Format)
422 return self.__class__.__ContextHelpers[self.Format]
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400423
Behdad Esfahbodf2b6d9c2013-07-23 17:31:54 -0400424@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400425def closure_glyphs (self, s, cur_glyphs=None):
426 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400427 c = self.__classify_context ()
428
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400429 indices = c.Coverage (self).intersect (s.glyphs)
430 if not indices:
431 return []
432 cur_glyphs = set (g for g in c.Coverage (self).glyphs if g in s.glyphs)
433
Behdad Esfahbod00776972013-07-23 15:33:00 -0400434 if self.Format == 1:
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400435 rss = getattr (self, c.RuleSet)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400436 return sum ((s.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs \
437 (s, cur_glyphs=(cur_glyphs if ll.SequenceIndex == 0 else s.glyphs)) \
Behdad Esfahboddd6fc842013-08-06 11:12:49 -0400438 for i in indices if rss[i] \
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400439 for r in getattr (rss[i], c.Rule) \
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400440 if r and all (g in s.glyphs for g in c.RuleData (r)) \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400441 for ll in getattr (r, c.LookupRecord) if ll \
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400442 ), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400443 elif self.Format == 2:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400444 indices = getattr (self, c.ClassDef).intersect (cur_glyphs)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400445 rss = getattr (self, c.RuleSet)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400446 return sum ((s.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs \
447 (s, cur_glyphs=(cur_glyphs if ll.SequenceIndex == 0 else s.glyphs)) \
Behdad Esfahboddd6fc842013-08-06 11:12:49 -0400448 for i in indices if rss[i] \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400449 for r in getattr (rss[i], c.Rule) \
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400450 if r and all (all (cd.intersects_class (s.glyphs, k) for k in klist) \
451 for cd,klist in zip (c.ContextData (self), c.RuleData (r))) \
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400452 for ll in getattr (r, c.LookupRecord) if ll \
453 ), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400454 elif self.Format == 3:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400455 if not all (x.intersect (s.glyphs) for x in c.RuleData (self)):
Behdad Esfahbod00776972013-07-23 15:33:00 -0400456 return []
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400457 return sum ((s.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs \
458 (s, cur_glyphs=(cur_glyphs if ll.SequenceIndex == 0 else s.glyphs)) \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400459 for ll in getattr (self, c.LookupRecord) if ll), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400460 else:
461 assert 0, "unknown format: %s" % self.Format
462
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400463@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ContextPos,
464 fontTools.ttLib.tables.otTables.ChainContextSubst, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400465def subset_glyphs (self, s):
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400466 c = self.__classify_context ()
467
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400468 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400469 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400470 rss = getattr (self, c.RuleSet)
471 rss = [rss[i] for i in indices]
472 for rs in rss:
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400473 if rs:
474 ss = getattr (rs, c.Rule)
475 ss = [r for r in ss \
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400476 if r and all (g in s.glyphs for g in c.RuleData (r))]
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400477 setattr (rs, c.Rule, ss)
478 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400479 # Prune empty subrulesets
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400480 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400481 setattr (self, c.RuleSet, rss)
482 setattr (self, c.RuleSetCount, len (rss))
483 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400484 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400485 if not self.Coverage.subset (s.glyphs):
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400486 return False
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400487 indices = getattr (self, c.ClassDef).subset (self.Coverage.glyphs, remap=False)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400488 rss = getattr (self, c.RuleSet)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400489 rss = [rss[i] for i in indices]
490 ContextData = c.ContextData (self)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400491 klass_maps = [x.subset (s.glyphs, remap=True) for x in ContextData]
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400492 for rs in rss:
493 if rs:
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400494 ss = getattr (rs, c.Rule)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400495 ss = [r for r in ss \
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400496 if r and all (all (k in klass_map for k in klist) \
497 for klass_map,klist in zip (klass_maps, c.RuleData (r)))]
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400498 setattr (rs, c.Rule, ss)
499 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400500
501 # Remap rule classes
502 for r in ss:
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400503 c.SetRuleData (r, [[klass_map.index (k) for k in klist] \
504 for klass_map,klist in zip (klass_maps, c.RuleData (r))])
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400505 # Prune empty subrulesets
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400506 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
507 setattr (self, c.RuleSet, rss)
508 setattr (self, c.RuleSetCount, len (rss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400509 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400510 elif self.Format == 3:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400511 return all (x.subset (s.glyphs) for x in c.RuleData (self))
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400512 else:
513 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400514
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400515@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
516 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400517def subset_lookups (self, lookup_indices):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400518 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400519
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400520 if self.Format in [1, 2]:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400521 for rs in getattr (self, c.RuleSet):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400522 if rs:
523 for r in getattr (rs, c.Rule):
524 if r:
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400525 setattr (r, c.LookupRecord, [ll for ll in getattr (r, c.LookupRecord) if ll \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400526 if ll.LookupListIndex in lookup_indices])
527 for ll in getattr (r, c.LookupRecord):
528 if ll:
529 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400530 elif self.Format == 3:
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400531 setattr (self, c.LookupRecord, [ll for ll in getattr (self, c.LookupRecord) if ll \
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400532 if ll.LookupListIndex in lookup_indices])
533 for ll in getattr (self, c.LookupRecord):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400534 if ll:
535 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400536 else:
537 assert 0, "unknown format: %s" % self.Format
538
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400539@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
540 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400541def collect_lookups (self):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400542 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400543
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400544 if self.Format in [1, 2]:
Behdad Esfahbod27108392013-07-23 16:40:47 -0400545 return [ll.LookupListIndex \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400546 for rs in getattr (self, c.RuleSet) if rs \
547 for r in getattr (rs, c.Rule) if r \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400548 for ll in getattr (r, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400549 elif self.Format == 3:
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400550 return [ll.LookupListIndex \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400551 for ll in getattr (self, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400552 else:
553 assert 0, "unknown format: %s" % self.Format
554
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400555@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400556def closure_glyphs (self, s, cur_glyphs=None):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400557 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400558 return self.ExtSubTable.closure_glyphs (s, cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400559 else:
560 assert 0, "unknown format: %s" % self.Format
561
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400562@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400563def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400564 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400565 return self.ExtSubTable.subset_glyphs (s)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400566 else:
567 assert 0, "unknown format: %s" % self.Format
568
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400569@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
570def subset_lookups (self, lookup_indices):
571 if self.Format == 1:
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400572 return self.ExtSubTable.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400573 else:
574 assert 0, "unknown format: %s" % self.Format
575
576@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
577def collect_lookups (self):
578 if self.Format == 1:
579 return self.ExtSubTable.collect_lookups ()
580 else:
581 assert 0, "unknown format: %s" % self.Format
582
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400583@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400584def closure_glyphs (self, s, cur_glyphs=None):
585 return sum ((st.closure_glyphs (s, cur_glyphs) for st in self.SubTable if st), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400586
587@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400588def subset_glyphs (self, s):
589 self.SubTable = [st for st in self.SubTable if st and st.subset_glyphs (s)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400590 self.SubTableCount = len (self.SubTable)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400591 return bool (self.SubTableCount)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400592
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400593@add_method(fontTools.ttLib.tables.otTables.Lookup)
594def subset_lookups (self, lookup_indices):
595 for s in self.SubTable:
596 s.subset_lookups (lookup_indices)
597
598@add_method(fontTools.ttLib.tables.otTables.Lookup)
599def collect_lookups (self):
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400600 return unique_sorted (sum ((st.collect_lookups () for st in self.SubTable if st), []))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400601
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400602@add_method(fontTools.ttLib.tables.otTables.LookupList)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400603def subset_glyphs (self, s):
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400604 "Returns the indices of nonempty lookups."
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400605 return [i for (i,l) in enumerate (self.Lookup) if l and l.subset_glyphs (s)]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400606
607@add_method(fontTools.ttLib.tables.otTables.LookupList)
608def subset_lookups (self, lookup_indices):
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400609 self.Lookup = [self.Lookup[i] for i in lookup_indices if i < self.LookupCount]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400610 self.LookupCount = len (self.Lookup)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400611 for l in self.Lookup:
612 l.subset_lookups (lookup_indices)
613
614@add_method(fontTools.ttLib.tables.otTables.LookupList)
615def closure_lookups (self, lookup_indices):
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400616 lookup_indices = unique_sorted (lookup_indices)
617 recurse = lookup_indices
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400618 while True:
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400619 recurse_lookups = sum ((self.Lookup[i].collect_lookups () for i in recurse if i < self.LookupCount), [])
620 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 -0400621 if not recurse_lookups:
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400622 return unique_sorted (lookup_indices)
623 recurse_lookups = unique_sorted (recurse_lookups)
624 lookup_indices.extend (recurse_lookups)
625 recurse = recurse_lookups
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400626
627@add_method(fontTools.ttLib.tables.otTables.Feature)
628def subset_lookups (self, lookup_indices):
629 self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices]
630 # Now map them.
631 self.LookupListIndex = [lookup_indices.index (l) for l in self.LookupListIndex]
632 self.LookupCount = len (self.LookupListIndex)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400633 return self.LookupCount
Behdad Esfahbod54660612013-07-21 18:16:55 -0400634
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400635@add_method(fontTools.ttLib.tables.otTables.Feature)
636def collect_lookups (self):
637 return self.LookupListIndex[:]
638
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400639@add_method(fontTools.ttLib.tables.otTables.FeatureList)
640def subset_lookups (self, lookup_indices):
641 "Returns the indices of nonempty features."
642 feature_indices = [i for (i,f) in enumerate (self.FeatureRecord) if f.Feature.subset_lookups (lookup_indices)]
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400643 self.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400644 return feature_indices
645
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400646@add_method(fontTools.ttLib.tables.otTables.FeatureList)
647def collect_lookups (self, feature_indices):
648 return unique_sorted (sum ((self.FeatureRecord[i].Feature.collect_lookups () for i in feature_indices
649 if i < self.FeatureCount), []))
650
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400651@add_method(fontTools.ttLib.tables.otTables.FeatureList)
652def subset_features (self, feature_indices):
653 self.FeatureRecord = [self.FeatureRecord[i] for i in feature_indices]
654 self.FeatureCount = len (self.FeatureRecord)
655 return bool (self.FeatureCount)
656
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400657@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
658def subset_features (self, feature_indices):
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400659 if self.ReqFeatureIndex in feature_indices:
660 self.ReqFeatureIndex = feature_indices.index (self.ReqFeatureIndex)
661 else:
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400662 self.ReqFeatureIndex = 65535
663 self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400664 # Now map them.
665 self.FeatureIndex = [feature_indices.index (f) for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400666 self.FeatureCount = len (self.FeatureIndex)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400667 return bool (self.FeatureCount or self.ReqFeatureIndex != 65535)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400668
669@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
670def collect_features (self):
671 feature_indices = self.FeatureIndex[:]
672 if self.ReqFeatureIndex != 65535:
673 feature_indices.append (self.ReqFeatureIndex)
674 return unique_sorted (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400675
676@add_method(fontTools.ttLib.tables.otTables.Script)
677def subset_features (self, feature_indices):
678 if self.DefaultLangSys and not self.DefaultLangSys.subset_features (feature_indices):
679 self.DefaultLangSys = None
680 self.LangSysRecord = [l for l in self.LangSysRecord if l.LangSys.subset_features (feature_indices)]
681 self.LangSysCount = len (self.LangSysRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400682 return bool (self.LangSysCount or self.DefaultLangSys)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400683
684@add_method(fontTools.ttLib.tables.otTables.Script)
685def collect_features (self):
Behdad Esfahbod2307c8b2013-07-23 11:18:13 -0400686 feature_indices = [l.LangSys.collect_features () for l in self.LangSysRecord]
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400687 if self.DefaultLangSys:
688 feature_indices.append (self.DefaultLangSys.collect_features ())
689 return unique_sorted (sum (feature_indices, []))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400690
691@add_method(fontTools.ttLib.tables.otTables.ScriptList)
692def subset_features (self, feature_indices):
693 self.ScriptRecord = [s for s in self.ScriptRecord if s.Script.subset_features (feature_indices)]
694 self.ScriptCount = len (self.ScriptRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400695 return bool (self.ScriptCount)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400696
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400697@add_method(fontTools.ttLib.tables.otTables.ScriptList)
698def collect_features (self):
699 return unique_sorted (sum ((s.Script.collect_features () for s in self.ScriptRecord), []))
700
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400701@add_method(fontTools.ttLib.getTableClass('GSUB'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400702def closure_glyphs (self, s):
703 s.table = self.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400704 feature_indices = self.table.ScriptList.collect_features ()
705 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400706 orig_glyphs = s.glyphs
707 glyphs = unique_sorted (s.glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400708 while True:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400709 s.glyphs = glyphs
710 additions = (sum ((self.table.LookupList.Lookup[i].closure_glyphs (s) \
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400711 for i in lookup_indices if i < self.table.LookupList.LookupCount), []))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400712 additions = unique_sorted (g for g in additions if g not in glyphs)
713 if not additions:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400714 s.glyphs = orig_glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400715 return glyphs
716 glyphs.extend (additions)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400717 del s.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400718
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400719@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400720def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400721 s.glyphs = s.glyphs_gsubed
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400722 lookup_indices = self.table.LookupList.subset_glyphs (s)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400723 self.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400724 self.prune_lookups ()
725 return True
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400726
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400727@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400728def subset_lookups (self, lookup_indices):
729 "Retrains specified lookups, then removes empty features, language systems, and scripts."
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400730 self.table.LookupList.subset_lookups (lookup_indices)
731 feature_indices = self.table.FeatureList.subset_lookups (lookup_indices)
732 self.table.ScriptList.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400733
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400734@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
735def prune_lookups (self):
736 "Remove unreferenced lookups"
737 feature_indices = self.table.ScriptList.collect_features ()
738 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
739 lookup_indices = self.table.LookupList.closure_lookups (lookup_indices)
740 self.subset_lookups (lookup_indices)
741
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400742@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
743def subset_feature_tags (self, feature_tags):
744 feature_indices = [i for (i,f) in enumerate (self.table.FeatureList.FeatureRecord) if f.FeatureTag in feature_tags]
745 self.table.FeatureList.subset_features (feature_indices)
746 self.table.ScriptList.subset_features (feature_indices)
747
748@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400749def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400750 if options.layout_features and '*' not in options.layout_features:
751 self.subset_feature_tags (options.layout_features)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400752 self.prune_lookups ()
753 return True
754
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400755@add_method(fontTools.ttLib.getTableClass('GDEF'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400756def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400757 glyphs = s.glyphs_gsubed
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400758 table = self.table
759 if table.LigCaretList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400760 indices = table.LigCaretList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400761 table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i] for i in indices]
762 table.LigCaretList.LigGlyphCount = len (table.LigCaretList.LigGlyph)
763 if not table.LigCaretList.LigGlyphCount:
764 table.LigCaretList = None
765 if table.MarkAttachClassDef:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400766 table.MarkAttachClassDef.classDefs = {g:v for g,v in table.MarkAttachClassDef.classDefs.items() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400767 if not table.MarkAttachClassDef.classDefs:
768 table.MarkAttachClassDef = None
769 if table.GlyphClassDef:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400770 table.GlyphClassDef.classDefs = {g:v for g,v in table.GlyphClassDef.classDefs.items() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400771 if not table.GlyphClassDef.classDefs:
772 table.GlyphClassDef = None
773 if table.AttachList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400774 indices = table.AttachList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400775 table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i] for i in indices]
776 table.AttachList.GlyphCount = len (table.AttachList.AttachPoint)
777 if not table.AttachList.GlyphCount:
778 table.AttachList = None
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400779 return bool (table.LigCaretList or table.MarkAttachClassDef or table.GlyphClassDef or table.AttachList)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400780
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400781@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbodd4e33a72013-07-24 18:51:05 -0400782def prune_pre_subset (self, options):
783 # Prune unknown kern table types
784 self.kernTables = [t for t in self.kernTables if hasattr (t, 'kernTable')]
785 return bool (self.kernTables)
786
787@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400788def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400789 glyphs = s.glyphs_gsubed
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400790 for t in self.kernTables:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400791 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 -0400792 self.kernTables = [t for t in self.kernTables if t.kernTable]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400793 return bool (self.kernTables)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400794
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400795@add_method(fontTools.ttLib.getTableClass('hmtx'), fontTools.ttLib.getTableClass('vmtx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400796def subset_glyphs (self, s):
797 self.metrics = {g:v for g,v in self.metrics.items() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400798 return bool (self.metrics)
Behdad Esfahbodc7160442013-07-22 14:29:08 -0400799
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400800@add_method(fontTools.ttLib.getTableClass('hdmx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400801def subset_glyphs (self, s):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400802 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 -0400803 return bool (self.hdmx)
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400804
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400805@add_method(fontTools.ttLib.getTableClass('VORG'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400806def subset_glyphs (self, s):
807 self.VOriginRecords = {g:v for g,v in self.VOriginRecords.items() if g in s.glyphs}
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400808 self.numVertOriginYMetrics = len (self.VOriginRecords)
809 return True # Never drop; has default metrics
810
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400811@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400812def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400813 if not options.glyph_names:
Behdad Esfahbod42648242013-07-23 12:56:06 -0400814 self.formatType = 3.0
815 return True
816
817@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400818def subset_glyphs (self, s):
Behdad Esfahbod42648242013-07-23 12:56:06 -0400819 self.extraNames = [] # This seems to do it
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -0400820 return True
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400821
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400822# Copied from _g_l_y_f.py
823ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes
824ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points
825ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true
826WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0
827NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!)
828MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one
829WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy
830WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11
831WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow
832USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph
833OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts
834SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple)
835UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS)
836
837@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
838def getComponentNamesFast (self, glyfTable):
839 if struct.unpack(">h", self.data[:2])[0] >= 0:
840 return [] # Not composite
841 data = self.data
842 i = 10
843 components = []
844 more = 1
845 while more:
846 flags, glyphID = struct.unpack(">HH", data[i:i+4])
847 i += 4
848 flags = int(flags)
849 components.append (glyfTable.getGlyphName (int (glyphID)))
850
851 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
852 else: i += 2
853 if flags & WE_HAVE_A_SCALE: i += 2
854 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
855 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
856 more = flags & MORE_COMPONENTS
857 return components
858
859@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
860def remapComponentsFast (self, indices):
861 if struct.unpack(">h", self.data[:2])[0] >= 0:
862 return # Not composite
863 data = bytearray (self.data)
864 i = 10
865 more = 1
866 while more:
867 flags = (data[i] << 8) | data[i+1]
868 glyphID = (data[i+2] << 8) | data[i+3]
869 # Remap
870 glyphID = indices.index (glyphID)
871 data[i+2] = glyphID >> 8
872 data[i+3] = glyphID & 0xFF
873 i += 4
874 flags = int(flags)
875
876 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
877 else: i += 2
878 if flags & WE_HAVE_A_SCALE: i += 2
879 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
880 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
881 more = flags & MORE_COMPONENTS
882 self.data = str (data)
883
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400884@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
885def dropInstructionsFast (self):
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400886 numContours = struct.unpack(">h", self.data[:2])[0]
887 data = bytearray (self.data)
888 i = 10
889 if numContours >= 0:
890 i += 2 * numContours # endPtsOfContours
891 instructionLen = (data[i] << 8) | data[i+1]
892 # Zero it
893 data[i] = data [i+1] = 0
894 i += 2
Behdad Esfahbod0fb69882013-07-24 17:25:35 -0400895 if instructionLen:
896 # Splice it out
897 data = data[:i] + data[i+instructionLen:]
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400898 else:
899 more = 1
900 while more:
901 flags = (data[i] << 8) | data[i+1]
902 # Turn instruction flag off
903 flags &= ~WE_HAVE_INSTRUCTIONS
904 data[i+0] = flags >> 8
905 data[i+1] = flags & 0xFF
906 i += 4
907 flags = int(flags)
908
909 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
910 else: i += 2
911 if flags & WE_HAVE_A_SCALE: i += 2
912 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
913 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
914 more = flags & MORE_COMPONENTS
915 # Cut off
916 data = data[:i]
917 if len(data) % 4:
918 # add pad bytes
919 nPadBytes = 4 - (len(data) % 4)
920 for i in range (nPadBytes):
921 data.append (0)
922 self.data = str (data)
923
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400924@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400925def closure_glyphs (self, s):
926 glyphs = unique_sorted (s.glyphs)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400927 decompose = glyphs
928 # I don't know if component glyphs can be composite themselves.
929 # We handle them anyway.
930 while True:
931 components = []
932 for g in decompose:
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400933 if g not in self.glyphs:
Behdad Esfahbodf8c20e42013-07-23 23:13:23 -0400934 continue
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400935 gl = self.glyphs[g]
936 if hasattr (gl, "data"):
937 for c in gl.getComponentNamesFast (self):
938 if c not in glyphs:
939 components.append (c)
940 else:
941 # TTX seems to expand gid0..3 always
942 if gl.isComposite ():
943 for c in gl.components:
944 if c.glyphName not in glyphs:
945 components.append (c.glyphName)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400946 components = [c for c in components if c not in glyphs]
947 if not components:
948 return glyphs
949 decompose = unique_sorted (components)
950 glyphs.extend (components)
951
952@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400953def subset_glyphs (self, s):
954 self.glyphs = {g:v for g,v in self.glyphs.items() if g in s.glyphs}
955 indices = [i for i,g in enumerate (self.glyphOrder) if g in s.glyphs]
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400956 for v in self.glyphs.values ():
957 if hasattr (v, "data"):
958 v.remapComponentsFast (indices)
959 else:
960 pass # No need
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400961 self.glyphOrder = [g for g in self.glyphOrder if g in s.glyphs]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400962 return bool (self.glyphs)
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400963
Behdad Esfahboded98c612013-07-23 12:37:41 -0400964@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400965def prune_post_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400966 if not options.hinting:
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400967 for v in self.glyphs.values ():
968 if hasattr (v, "data"):
969 v.dropInstructionsFast ()
970 else:
971 v.program = fontTools.ttLib.tables.ttProgram.Program()
972 v.program.fromBytecode([])
Behdad Esfahboded98c612013-07-23 12:37:41 -0400973 return True
974
Behdad Esfahbod2b677c82013-07-23 13:37:13 -0400975@add_method(fontTools.ttLib.getTableClass('CFF '))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400976def subset_glyphs (self, s):
Behdad Esfahbod2b677c82013-07-23 13:37:13 -0400977 assert 0, "unimplemented"
978
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400979@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -0400980def closure_glyphs (self, s):
981 tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [1, 10]]
982 extra = []
Behdad Esfahbod98259f22013-07-31 20:16:24 -0400983 for u in s.unicodes_requested:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -0400984 found = False
985 for table in tables:
986 if u in table.cmap:
987 extra.append (table.cmap[u])
988 found = True
989 break
990 if not found:
991 s.log ("No glyph for Unicode value %s; skipping." % u)
992 return extra
993
994@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400995def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400996 if not options.legacy_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400997 # Drop non-Unicode / non-Symbol cmaps
998 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 -0400999 if not options.symbol_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -04001000 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 -04001001 # TODO Only keep one subtable?
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001002 # For now, drop format=0 which can't be subset_glyphs easily?
1003 self.tables = [t for t in self.tables if t.format != 0]
1004 return bool (self.tables)
1005
1006@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001007def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -04001008 s.glyphs = s.glyphs_cmaped
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001009 for t in self.tables:
Behdad Esfahbod9453a362013-07-22 16:21:24 -04001010 # For reasons I don't understand I need this here
1011 # to force decompilation of the cmap format 14.
1012 try:
1013 getattr (t, "asdf")
1014 except AttributeError:
1015 pass
Behdad Esfahbodb13d7902013-07-22 16:01:15 -04001016 if t.format == 14:
Behdad Esfahbod9453a362013-07-22 16:21:24 -04001017 # XXX We drop all the default-UVS mappings (g==None)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001018 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 -04001019 t.uvsDict = {v:l for (v,l) in t.uvsDict.items() if l}
1020 else:
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001021 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 -04001022 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 -04001023 # XXX Convert formats when needed
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001024 return bool (self.tables)
1025
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001026@add_method(fontTools.ttLib.getTableClass('name'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -04001027def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001028 if '*' not in options.name_IDs:
1029 self.names = [n for n in self.names if n.nameID in options.name_IDs]
1030 if not options.name_legacy:
Behdad Esfahbod20faeb02013-07-23 13:19:03 -04001031 self.names = [n for n in self.names if n.platformID == 3 and n.platEncID == 1]
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001032 if '*' not in options.name_languages:
1033 self.names = [n for n in self.names if n.langID in options.name_languages]
Behdad Esfahbod20faeb02013-07-23 13:19:03 -04001034 return True # Retain even if empty
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001035
Behdad Esfahbod8c646f62013-07-22 15:06:23 -04001036
Behdad Esfahbodbc25f162013-07-23 12:56:54 -04001037drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'PCLT', 'LTSH']
Behdad Esfahbod103a12f2013-07-23 15:08:39 -04001038drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill'] # Graphite
Behdad Esfahbod38e852c2013-07-23 16:56:50 -04001039drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL'] # Color
Behdad Esfahboded98c612013-07-23 12:37:41 -04001040no_subset_tables = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2', 'loca', 'name', 'cvt ', 'fpgm', 'prep']
Behdad Esfahbodbc25f162013-07-23 12:56:54 -04001041hinting_tables = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
Behdad Esfahbod29df0462013-07-23 11:05:25 -04001042
Behdad Esfahbod356c42e2013-07-23 12:10:46 -04001043# Based on HarfBuzz shapers
1044layout_features_dict = {
1045 # Default shaper
1046 'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
1047 'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
1048 'vertical': ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
1049 'ltr': ['ltra', 'ltrm'],
1050 'rtl': ['rtla', 'rtlm'],
1051 # Complex shapers
Behdad Esfahbodf36b5a92013-08-04 16:54:46 -04001052 'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3', 'cswh', 'mset'],
Behdad Esfahbod356c42e2013-07-23 12:10:46 -04001053 'hangul': ['ljmo', 'vjmo', 'tjmo'],
1054 'tibetal': ['abvs', 'blws', 'abvm', 'blwm'],
1055 'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half', 'abvf', 'pstf', 'cfar', 'vatu', 'cjct',
1056 'init', 'pres', 'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
1057}
1058layout_features_all = unique_sorted (sum (layout_features_dict.values (), []))
1059
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -04001060# TODO OS/2 ulUnicodeRange / ulCodePageRange?
Behdad Esfahbodf71267b2013-07-23 12:59:13 -04001061# TODO Drop unneeded GSUB/GPOS Script/LangSys entries
Behdad Esfahbod398d3892013-07-23 15:29:40 -04001062# TODO Avoid recursing too much
Behdad Esfahbode94aa0e2013-07-23 13:22:04 -04001063# TODO Text direction considerations
1064# TODO Text script / language considerations
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001065# TODO Drop unknown tables? Using DefaultTable.prune?
Behdad Esfahbod8c4f7cc2013-07-24 17:58:29 -04001066# TODO Drop GPOS Device records if not hinting?
Behdad Esfahbod56ebd042013-07-22 13:02:24 -04001067
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001068
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001069class Subsetter:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001070
1071 class Options:
1072 drop_tables = drop_tables_default
1073 layout_features = layout_features_all
1074 hinting = False
1075 glyph_names = False
1076 legacy_cmap = False
1077 symbol_cmap = False
1078 name_IDs = [1, 2] # Family and Style
1079 name_legacy = False
1080 name_languages = [0x0409] # English
1081 mandatory_glyphs = True # First four for TrueType, .notdef for CFF
1082 recalc_bboxes = False # Slows us down
1083
1084 def __init__ (self, **kwargs):
1085
1086 self.set (**kwargs)
1087
1088 def set (self, **kwargs):
1089 for k,v in kwargs.items ():
1090 if not hasattr (self, k):
1091 raise Exception ("Unknown option '%s'" % k)
1092 setattr (self, k, v)
1093
1094 def parse_opts (self, argv, ignore_unknown=False):
1095 ret = []
1096 opts = {}
1097 for a in argv:
1098 if not a.startswith ('--'):
1099 ret.append (a)
1100 continue
1101 a = a[2:]
1102 i = a.find ('=')
1103 if i == -1:
1104 if a.startswith ("no-"):
1105 k = a[3:]
1106 v = False
1107 else:
1108 k = a
1109 v = True
1110 else:
1111 k = a[:i]
1112 v = a[i+1:]
1113 k = k.replace ('-', '_')
1114 if not hasattr (self, k):
1115 if ignore_unknown:
1116 ret.append (a)
1117 continue
1118 else:
1119 raise Exception ("Unknown option '%s'" % a)
1120
1121 ov = getattr (self, k)
1122 if isinstance (ov, bool):
1123 v = bool (v)
1124 elif isinstance (ov, int):
1125 v = int (v)
1126 elif isinstance (ov, list):
1127 v = v.split (',')
1128 v = [int (x, 0) if x[0] in range (10) else x for x in v]
1129
1130 opts[k] = v
1131 self.set (**opts)
1132
1133 return ret
1134
1135
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001136 def __init__ (self, font=None, options=None, log=None):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001137
1138 if isinstance (font, basestring):
1139 font = fontTools.ttx.TTFont (font)
1140 if not log:
1141 log = Logger()
1142 if not options:
1143 options = Options()
1144
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001145 self.font = font
1146 self.options = options
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001147 self.log = log
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001148 self.unicodes_requested = set ()
1149 self.glyphs_requested = set ()
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001150
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001151 def populate (self, glyphs=[], unicodes=[], text=""):
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001152 self.unicodes_requested.update (unicodes)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001153 if isinstance (text, str):
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001154 text = text.decode ("utf8")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001155 for u in text:
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001156 self.unicodes_requested.add (ord (u))
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001157 self.glyphs_requested.update (glyphs)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001158
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001159 def pre_prune (self):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001160
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001161 for tag in self.font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001162 if tag == 'GlyphOrder': continue
1163
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001164 if tag in self.options.drop_tables or \
1165 (tag in hinting_tables and not self.options.hinting):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001166 self.log (tag, "dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001167 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001168 continue
1169
1170 clazz = fontTools.ttLib.getTableClass(tag)
1171
1172 if hasattr (clazz, 'prune_pre_subset'):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001173 table = self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001174 retain = table.prune_pre_subset (self.options)
1175 self.log.lapse ("prune '%s'" % tag)
1176 if not retain:
1177 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001178 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001179 continue
1180 else:
1181 self.log (tag, "pruned")
1182
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001183 def closure_glyphs (self):
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001184
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001185 self.glyphs = self.glyphs_requested
1186
1187 if 'cmap' in self.font:
1188 extra_glyphs = self.font['cmap'].closure_glyphs (self)
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001189 self.glyph = self.glyphs.copy ()
1190 self.glyphs.update (extra_glyphs)
1191 self.glyphs_cmaped = self.glyphs
1192
1193 if self.options.mandatory_glyphs:
1194 self.glyphs = self.glyphs.copy ()
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001195 if 'glyf' in self.font:
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001196 for i in range (4):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001197 self.glyphs.add (self.font.getGlyphName (i))
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001198 self.log ("Added first four glyphs to subset")
1199 else:
1200 self.glyphs.add ('.notdef')
1201 self.log ("Added .notdef glyph to subset")
1202
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001203 if 'GSUB' in self.font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001204 self.log ("Closing glyph list over 'GSUB': %d glyphs before" % len (self.glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001205 self.log.glyphs (self.glyphs, font=self.font)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001206 self.glyphs = set (self.font['GSUB'].closure_glyphs (self))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001207 self.log ("Closed glyph list over 'GSUB': %d glyphs after" % len (self.glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001208 self.log.glyphs (self.glyphs, font=self.font)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001209 self.log.lapse ("close glyph list over 'GSUB'")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001210 self.glyphs_gsubed = self.glyphs
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001211
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001212 if 'glyf' in self.font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001213 self.log ("Closing glyph list over 'glyf': %d glyphs before" % len (self.glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001214 self.log.glyphs (self.glyphs, font=self.font)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001215 self.glyphs = set (self.font['glyf'].closure_glyphs (self))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001216 self.log ("Closed glyph list over 'glyf': %d glyphs after" % len (self.glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001217 self.log.glyphs (self.glyphs, font=self.font)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001218 self.log.lapse ("close glyph list over 'glyf'")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001219 self.glyphs_glyfed = self.glyphs
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001220
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001221 self.glyphs_all = self.glyphs
1222
1223 self.log ("Retaining %d glyphs: " % len (self.glyphs_all))
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001224
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001225 def subset_glyphs (self):
1226 for tag in self.font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001227 if tag == 'GlyphOrder': continue
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001228 clazz = fontTools.ttLib.getTableClass(tag)
1229
1230 if tag in no_subset_tables:
1231 self.log (tag, "subsetting not needed")
1232 elif hasattr (clazz, 'subset_glyphs'):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001233 table = self.font[tag]
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -04001234 self.glyphs = self.glyphs_all
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001235 retain = table.subset_glyphs (self)
1236 self.log.lapse ("subset '%s'" % tag)
1237 if not retain:
1238 self.log (tag, "subsetted to empty; dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001239 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001240 else:
1241 self.log (tag, "subsetted")
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001242 else:
1243 self.log (tag, "NOT subset; don't know how to subset")
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001244
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001245 glyphOrder = self.font.getGlyphOrder()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001246 glyphOrder = [g for g in glyphOrder if g in self.glyphs_all]
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001247 self.font.setGlyphOrder (glyphOrder)
1248 self.font._buildReverseGlyphOrderDict ()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001249 self.log.lapse ("subset GlyphOrder")
1250
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001251 def post_prune (self):
1252 for tag in self.font.keys():
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001253 if tag == 'GlyphOrder': continue
1254 clazz = fontTools.ttLib.getTableClass(tag)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001255 if hasattr (clazz, 'prune_post_subset'):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001256 table = self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001257 retain = table.prune_post_subset (self.options)
1258 self.log.lapse ("prune '%s'" % tag)
1259 if not retain:
1260 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001261 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001262 else:
1263 self.log (tag, "pruned")
1264
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001265 def subset (self, font):
1266
1267 self.font = font
Behdad Esfahbod756af492013-08-01 12:05:26 -04001268
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001269 self.font.recalcBBoxes = self.options.recalc_bboxes
1270
1271 self.pre_prune ()
1272 self.closure_glyphs ()
1273 self.subset_glyphs ()
1274 self.post_prune ()
1275
Behdad Esfahbod756af492013-08-01 12:05:26 -04001276 del self.font
1277
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001278import sys, time
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001279
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001280class Logger:
1281
1282 def __init__ (self, verbose=False, xml=False, timing=False):
1283 self.verbose = verbose
1284 self.xml = xml
1285 self.timing = timing
1286 self.last_time = self.start_time = time.time ()
1287
1288 def parse_opts (self, argv):
1289 argv = argv[:]
1290 for v in ['verbose', 'xml', 'timing']:
1291 if "--"+v in argv:
1292 setattr (self, v, True)
1293 argv.remove ("--"+v)
1294 return argv
1295
1296 def __call__ (self, *things):
1297 if not self.verbose:
1298 return
1299 print ' '.join (str (x) for x in things)
1300
1301 def lapse (self, *things):
1302 if not self.timing:
1303 return
1304 new_time = time.time ()
1305 print "Took %0.3fs to %s" % (new_time - self.last_time, ' '.join (str (x) for x in things))
1306 self.last_time = new_time
1307
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001308 def glyphs (self, glyphs, glyph_names=True, font=None):
1309 self ("Names: ", sorted (glyphs))
1310 if font:
1311 glyphOrder = font.getGlyphOrder()
1312 self ("Gids : ", sorted (glyphOrder.index (g) for g in glyphs))
1313
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001314 def font (self, font, file=sys.stdout):
1315 if not self.xml:
1316 return
1317 import xmlWriter, sys
1318 writer = xmlWriter.XMLWriter (file)
1319 font.disassembleInstructions = False # Work around ttx bug
1320 for tag in font.keys():
1321 writer.begintag (tag)
1322 writer.newline ()
1323 font[tag].toXML(writer, font)
1324 writer.endtag (tag)
1325 writer.newline ()
1326
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001327def main (args):
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001328
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001329 log = Logger ()
1330 args = log.parse_opts (args)
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001331
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001332 options = Subsetter.Options ()
1333 args = options.parse_opts (args)
1334
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001335 if len (args) < 2:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001336 import sys
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001337 print >>sys.stderr, "usage: pyotlss.py font-file glyph..."
1338 sys.exit (1)
1339
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001340 fontfile = args[0]
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001341 args = args[1:]
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001342
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001343 # TODO Option for ignoreDecompileErrors?
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001344 font = fontTools.ttx.TTFont (fontfile)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001345 s = Subsetter (font=font, options=options, log=log)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001346 log.lapse ("load font")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001347
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001348 # Hack:
1349 #
1350 # If we don't need glyph names, change 'post' class to not try to
1351 # load them. It avoid lots of headache with broken fonts as well
1352 # as loading time.
1353 #
1354 # Ideally ttLib should provide a way to ask it to skip loading
1355 # glyph names. But it currently doesn't provide such a thing.
1356 #
1357 if not options.glyph_names \
Behdad Esfahbod9ae5d282013-08-08 21:18:17 -04001358 and all (any (g.startswith (p) for p in ['gid', 'glyph', 'uni', 'U+']) \
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001359 for g in args):
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001360 post = fontTools.ttLib.getTableClass('post')
1361 saved = post.decode_format_2_0
1362 post.decode_format_2_0 = post.decode_format_3_0
1363 f = font['post']
1364 if f.formatType == 2.0:
1365 f.formatType = 3.0
1366 post.decode_format_2_0 = saved
1367 del post, saved, f
1368
1369 names = font.getGlyphNames()
1370 log.lapse ("loading glyph names")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001371
1372 glyphs = []
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001373 unicodes = []
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001374 for g in args:
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001375 if g in names:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001376 glyphs.append (g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001377 continue
Behdad Esfahbod9ae5d282013-08-08 21:18:17 -04001378 if g.startswith ('uni') or g.startswith ('U+'):
1379 if g.startswith ('uni') and len (g) > 3:
1380 g = g[3:]
1381 elif g.startswith ('U+') and len (g) > 2:
1382 g = g[2:]
1383 u = int (g, 16)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001384 unicodes.append (u)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001385 continue
1386 if g.startswith ('gid') or g.startswith ('glyph'):
1387 if g.startswith ('gid') and len (g) > 3:
1388 g = g[3:]
1389 elif g.startswith ('glyph') and len (g) > 5:
1390 g = g[5:]
1391 try:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001392 glyphs.append (font.getGlyphName (int (g), requireReal=1))
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001393 except ValueError:
1394 raise Exception ("Invalid glyph identifier %s" % g)
1395 continue
1396 raise Exception ("Invalid glyph identifier %s" % g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001397 log.lapse ("compile glyph list")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001398 log ("Unicodes:", unicodes)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001399 log ("Glyphs:", glyphs)
1400
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001401 s.populate (glyphs=glyphs, unicodes=unicodes)
1402 s.subset (font)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -04001403
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001404 font.save (fontfile + '.subset')
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001405 log.lapse ("compile and save font")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001406
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001407 log.last_time = s.log.start_time
1408 log.lapse ("make one with everything (TOTAL TIME)")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001409
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001410 log.font (font)
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001411
1412if __name__ == '__main__':
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001413 import sys
1414 main (sys.argv[1:])