blob: c2ec595e0824cc21a8db03011e5790d53b8ea3ab [file] [log] [blame]
Behdad Esfahbod54660612013-07-21 18:16:55 -04001#!/usr/bin/python
2
3# Python OpenType Layout Subsetter
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04004#
5# Copyright 2013 Google, Inc. All Rights Reserved.
6#
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18#
19# Google Author(s): Behdad Esfahbod
20#
Behdad Esfahbod54660612013-07-21 18:16:55 -040021
Behdad Esfahbodfa3bc5e2013-07-24 14:37:58 -040022# Try running on PyPy
23try:
24 import numpypy
25except ImportError:
26 pass
27
Behdad Esfahbod54660612013-07-21 18:16:55 -040028import fontTools.ttx
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -040029import struct
Behdad Esfahbod54660612013-07-21 18:16:55 -040030
Behdad Esfahbod54660612013-07-21 18:16:55 -040031
Behdad Esfahbod02b92062013-07-21 18:40:59 -040032def add_method (*clazzes):
Behdad Esfahbod54660612013-07-21 18:16:55 -040033 def wrapper(method):
Behdad Esfahbod02b92062013-07-21 18:40:59 -040034 for clazz in clazzes:
Behdad Esfahbodc0d59592013-07-24 14:41:47 -040035 assert clazz.__name__ != 'DefaultTable', 'Oops, table class not found.'
Behdad Esfahbod02b92062013-07-21 18:40:59 -040036 setattr (clazz, method.func_name, method)
Behdad Esfahbod54660612013-07-21 18:16:55 -040037 return wrapper
38
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040039def unique_sorted (l):
Behdad Esfahbod2d9a0962013-07-31 13:33:31 -040040 return sorted (set (l))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040041
Behdad Esfahbod97e17b82013-07-31 15:59:21 -040042def safeEval(data, eval=eval):
43 """A (kindof) safe replacement for eval."""
44 return eval(data, {"__builtins__":{}}, {})
45
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040046
Behdad Esfahbod54660612013-07-21 18:16:55 -040047@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040048def intersect (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -040049 "Returns ascending list of matching coverage values."
50 return [i for (i,g) in enumerate (self.glyphs) if g in glyphs]
51
52@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040053def subset (self, glyphs):
Behdad Esfahbodd821ea02013-07-23 10:50:43 -040054 "Returns ascending list of remaining coverage values."
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040055 indices = self.intersect (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -040056 self.glyphs = [g for g in self.glyphs if g in glyphs]
57 return indices
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040058
Behdad Esfahbod54660612013-07-21 18:16:55 -040059@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040060def intersect (self, glyphs):
Behdad Esfahbode10803e2013-08-08 21:09:27 -040061 "Returns ascending list of matching class values."
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040062 return unique_sorted (([0] if any (g not in self.classDefs for g in glyphs) else []) + \
Behdad Esfahbode10803e2013-08-08 21:09:27 -040063 [v for g,v in self.classDefs.items() if g in glyphs])
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040064
65@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040066def intersects_class (self, glyphs, klass):
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040067 "Returns true if any of glyphs has requested class."
Behdad Esfahbode10803e2013-08-08 21:09:27 -040068 assert isinstance (klass, int)
Behdad Esfahbod0befd6b2013-08-05 22:47:14 -040069 if klass == 0:
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040070 if any (g not in self.classDefs for g in glyphs):
Behdad Esfahbod0befd6b2013-08-05 22:47:14 -040071 return True
72 # Fall through
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040073 return any (g in glyphs for g,v in self.classDefs.items() if v == klass)
74
75@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040076def subset (self, glyphs, remap=False):
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040077 "Returns ascending list of remaining classes."
Behdad Esfahbod54660612013-07-21 18:16:55 -040078 self.classDefs = {g:v for g,v in self.classDefs.items() if g in glyphs}
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040079 # Note: while class 0 has the special meaning of "not matched", if no glyph will
80 # ever /not match/, we can optimize class 0 out too.
81 indices = unique_sorted (([0] if any (g not in self.classDefs for g in glyphs) else []) + \
82 self.classDefs.values ())
Behdad Esfahbodde71dca2013-07-24 12:40:54 -040083 if remap:
84 self.remap (indices)
85 return indices
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -040086
87@add_method(fontTools.ttLib.tables.otTables.ClassDef)
88def remap (self, class_map):
89 "Remaps classes."
90 self.classDefs = {g:class_map.index (v) for g,v in self.classDefs.items()}
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040091
Behdad Esfahbod54660612013-07-21 18:16:55 -040092@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -040093def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -040094 if self.Format in [1, 2]:
Behdad Esfahbod254442b2013-07-31 14:20:13 -040095 return [v for g,v in self.mapping.items() if g in s.glyphs]
Behdad Esfahbod610b0552013-07-23 14:52:18 -040096 else:
97 assert 0, "unknown format: %s" % self.Format
98
99@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400100def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400101 if self.Format in [1, 2]:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400102 self.mapping = {g:v for g,v in self.mapping.items() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400103 return bool (self.mapping)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400104 else:
105 assert 0, "unknown format: %s" % self.Format
106
107@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400108def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400109 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400110 indices = self.Coverage.intersect (s.glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400111 return sum ((self.Sequence[i].Substitute for i in indices), [])
112 else:
113 assert 0, "unknown format: %s" % self.Format
114
115@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400116def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400117 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400118 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400119 self.Sequence = [self.Sequence[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400120 self.SequenceCount = len (self.Sequence)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400121 return bool (self.SequenceCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400122 else:
123 assert 0, "unknown format: %s" % self.Format
124
125@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400126def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400127 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400128 return sum ((v for g,v in self.alternates.items() if g in s.glyphs), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400129 else:
130 assert 0, "unknown format: %s" % self.Format
131
132@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400133def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400134 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400135 self.alternates = {g:v for g,v in self.alternates.items() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400136 return bool (self.alternates)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400137 else:
138 assert 0, "unknown format: %s" % self.Format
139
140@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400141def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400142 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400143 return sum (([seq.LigGlyph for seq in seqs if all(c in s.glyphs for c in seq.Component)]
144 for g,seqs in self.ligatures.items() if g in s.glyphs), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400145 else:
146 assert 0, "unknown format: %s" % self.Format
147
148@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400149def subset_glyphs (self, s):
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400150 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400151 self.ligatures = {g:v for g,v in self.ligatures.items() if g in s.glyphs}
152 self.ligatures = {g:[seq for seq in seqs if all(c in s.glyphs for c in seq.Component)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400153 for g,seqs in self.ligatures.items()}
154 self.ligatures = {g:v for g,v in self.ligatures.items() if v}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400155 return bool (self.ligatures)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400156 else:
157 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400158
Behdad Esfahbod54660612013-07-21 18:16:55 -0400159@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400160def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400161 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400162 indices = self.Coverage.intersect (s.glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400163 if not indices or \
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400164 not all (c.intersect (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400165 return []
166 return [self.Substitute[i] for i in indices]
167 else:
168 assert 0, "unknown format: %s" % self.Format
169
170@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400171def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400172 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400173 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400174 self.Substitute = [self.Substitute[i] for i in indices]
175 self.GlyphCount = len (self.Substitute)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400176 return bool (self.GlyphCount and all (c.subset (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400177 else:
178 assert 0, "unknown format: %s" % self.Format
179
180@add_method(fontTools.ttLib.tables.otTables.SinglePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400181def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400182 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400183 return len (self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400184 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400185 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400186 self.Value = [self.Value[i] for i in indices]
187 self.ValueCount = len (self.Value)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400188 return bool (self.ValueCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400189 else:
190 assert 0, "unknown format: %s" % self.Format
191
192@add_method(fontTools.ttLib.tables.otTables.PairPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400193def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400194 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400195 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400196 self.PairSet = [self.PairSet[i] for i in indices]
197 for p in self.PairSet:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400198 p.PairValueRecord = [r for r in p.PairValueRecord if r.SecondGlyph in s.glyphs]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400199 p.PairValueCount = len (p.PairValueRecord)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400200 self.PairSet = [p for p in self.PairSet if p.PairValueCount]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400201 self.PairSetCount = len (self.PairSet)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400202 return bool (self.PairSetCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400203 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400204 class1_map = self.ClassDef1.subset (s.glyphs, remap=True)
205 class2_map = self.ClassDef2.subset (s.glyphs, remap=True)
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -0400206 self.Class1Record = [self.Class1Record[i] for i in class1_map]
207 for c in self.Class1Record:
208 c.Class2Record = [c.Class2Record[i] for i in class2_map]
209 self.Class1Count = len (class1_map)
210 self.Class2Count = len (class2_map)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400211 return bool (self.Class1Count and self.Class2Count and self.Coverage.subset (s.glyphs))
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.CursivePos)
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.EntryExitRecord = [self.EntryExitRecord[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400220 self.EntryExitCount = len (self.EntryExitRecord)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400221 return bool (self.EntryExitCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400222 else:
223 assert 0, "unknown format: %s" % self.Format
224
225@add_method(fontTools.ttLib.tables.otTables.MarkBasePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400226def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400227 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400228 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400229 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
230 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400231 base_indices = self.BaseCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400232 self.BaseArray.BaseRecord = [self.BaseArray.BaseRecord[i] for i in base_indices]
233 self.BaseArray.BaseCount = len (self.BaseArray.BaseRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400234 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400235 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400236 self.ClassCount = len (class_indices)
237 for m in self.MarkArray.MarkRecord:
238 m.Class = class_indices.index (m.Class)
239 for b in self.BaseArray.BaseRecord:
240 b.BaseAnchor = [b.BaseAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400241 return bool (self.ClassCount and self.MarkArray.MarkCount and self.BaseArray.BaseCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400242 else:
243 assert 0, "unknown format: %s" % self.Format
244
245@add_method(fontTools.ttLib.tables.otTables.MarkLigPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400246def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400247 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400248 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400249 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
250 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400251 ligature_indices = self.LigatureCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400252 self.LigatureArray.LigatureAttach = [self.LigatureArray.LigatureAttach[i] for i in ligature_indices]
253 self.LigatureArray.LigatureCount = len (self.LigatureArray.LigatureAttach)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400254 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400255 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400256 self.ClassCount = len (class_indices)
257 for m in self.MarkArray.MarkRecord:
258 m.Class = class_indices.index (m.Class)
259 for l in self.LigatureArray.LigatureAttach:
260 for c in l.ComponentRecord:
261 c.LigatureAnchor = [c.LigatureAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400262 return bool (self.ClassCount and self.MarkArray.MarkCount and self.LigatureArray.LigatureCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400263 else:
264 assert 0, "unknown format: %s" % self.Format
265
266@add_method(fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400267def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400268 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400269 mark1_indices = self.Mark1Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400270 self.Mark1Array.MarkRecord = [self.Mark1Array.MarkRecord[i] for i in mark1_indices]
271 self.Mark1Array.MarkCount = len (self.Mark1Array.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400272 mark2_indices = self.Mark2Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400273 self.Mark2Array.Mark2Record = [self.Mark2Array.Mark2Record[i] for i in mark2_indices]
274 self.Mark2Array.MarkCount = len (self.Mark2Array.Mark2Record)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400275 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400276 class_indices = unique_sorted (v.Class for v in self.Mark1Array.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400277 self.ClassCount = len (class_indices)
278 for m in self.Mark1Array.MarkRecord:
279 m.Class = class_indices.index (m.Class)
280 for b in self.Mark2Array.Mark2Record:
281 b.Mark2Anchor = [b.Mark2Anchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400282 return bool (self.ClassCount and self.Mark1Array.MarkCount and self.Mark2Array.MarkCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400283 else:
284 assert 0, "unknown format: %s" % self.Format
285
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400286@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
287 fontTools.ttLib.tables.otTables.MultipleSubst,
288 fontTools.ttLib.tables.otTables.AlternateSubst,
289 fontTools.ttLib.tables.otTables.LigatureSubst,
290 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
291 fontTools.ttLib.tables.otTables.SinglePos,
292 fontTools.ttLib.tables.otTables.PairPos,
293 fontTools.ttLib.tables.otTables.CursivePos,
294 fontTools.ttLib.tables.otTables.MarkBasePos,
295 fontTools.ttLib.tables.otTables.MarkLigPos,
296 fontTools.ttLib.tables.otTables.MarkMarkPos)
297def subset_lookups (self, lookup_indices):
298 pass
299
300@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
301 fontTools.ttLib.tables.otTables.MultipleSubst,
302 fontTools.ttLib.tables.otTables.AlternateSubst,
303 fontTools.ttLib.tables.otTables.LigatureSubst,
304 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
305 fontTools.ttLib.tables.otTables.SinglePos,
306 fontTools.ttLib.tables.otTables.PairPos,
307 fontTools.ttLib.tables.otTables.CursivePos,
308 fontTools.ttLib.tables.otTables.MarkBasePos,
309 fontTools.ttLib.tables.otTables.MarkLigPos,
310 fontTools.ttLib.tables.otTables.MarkMarkPos)
311def collect_lookups (self):
312 return []
313
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400314@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
315 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
316def __classify_context (self):
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400317
318 class ContextHelper:
319 def __init__ (self, klass, Format):
320 if klass.__name__.endswith ('Subst'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400321 Typ = 'Sub'
322 Type = 'Subst'
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400323 else:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400324 Typ = 'Pos'
325 Type = 'Pos'
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400326 if klass.__name__.startswith ('Chain'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400327 Chain = 'Chain'
328 else:
329 Chain = ''
330 ChainTyp = Chain+Typ
331
332 self.Typ = Typ
333 self.Type = Type
334 self.Chain = Chain
335 self.ChainTyp = ChainTyp
336
337 self.LookupRecord = Type+'LookupRecord'
338
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400339 if Format == 1:
340 ContextData = None
341 ChainContextData = None
342 RuleData = lambda r: r.Input
343 ChainRuleData = lambda r: r.Backtrack + r.Input + r.LookAhead
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400344 SetRuleData = None
345 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400346 elif Format == 2:
Behdad Esfahbode3f20732013-07-24 11:26:43 -0400347 ContextData = lambda r: (r.ClassDef,)
348 ChainContextData = lambda r: (r.LookAheadClassDef, r.InputClassDef, r.BacktrackClassDef)
349 RuleData = lambda r: (r.Class,)
350 ChainRuleData = lambda r: (r.LookAhead, r.Input, r.Backtrack)
351 def SetRuleData (r, d): (r.Class,) = d
352 def ChainSetRuleData (r, d): (r.LookAhead, r.Input, r.Backtrack) = d
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400353 elif Format == 3:
354 ContextData = None
355 ChainContextData = None
356 RuleData = lambda r: r.Coverage
357 ChainRuleData = lambda r: r.LookAheadCoverage + r.InputCoverage + r.BacktrackCoverage
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400358 SetRuleData = None
359 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400360 else:
361 assert 0, "unknown format: %s" % Format
362
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400363 if Chain:
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400364 self.ContextData = ChainContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400365 self.RuleData = ChainRuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400366 self.SetRuleData = ChainSetRuleData
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400367 else:
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400368 self.ContextData = ContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400369 self.RuleData = RuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400370 self.SetRuleData = SetRuleData
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400371
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400372 if Format == 1:
373 self.Rule = ChainTyp+'Rule'
374 self.RuleCount = ChainTyp+'RuleCount'
375 self.RuleSet = ChainTyp+'RuleSet'
376 self.RuleSetCount = ChainTyp+'RuleSetCount'
377 elif Format == 2:
378 self.Rule = ChainTyp+'ClassRule'
379 self.RuleCount = ChainTyp+'ClassRuleCount'
380 self.RuleSet = ChainTyp+'ClassSet'
381 self.RuleSetCount = ChainTyp+'ClassSetCount'
Behdad Esfahbod89987002013-07-23 23:07:42 -0400382
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400383 self.ClassDef = 'InputClassDef' if Chain else 'ClassDef'
Behdad Esfahbod27108392013-07-23 16:40:47 -0400384
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400385 if self.Format not in [1, 2, 3]:
386 return None # Don't shoot the messenger; let it go
387 if not hasattr (self.__class__, "__ContextHelpers"):
388 self.__class__.__ContextHelpers = {}
389 if self.Format not in self.__class__.__ContextHelpers:
390 self.__class__.__ContextHelpers[self.Format] = ContextHelper (self.__class__, self.Format)
391 return self.__class__.__ContextHelpers[self.Format]
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400392
Behdad Esfahbodf2b6d9c2013-07-23 17:31:54 -0400393@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400394def closure_glyphs (self, s):
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400395 c = self.__classify_context ()
396
Behdad Esfahbod00776972013-07-23 15:33:00 -0400397 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400398 indices = self.Coverage.intersect (s.glyphs)
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400399 rss = getattr (self, c.RuleSet)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400400 return sum ((s.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs (s) \
Behdad Esfahboddd6fc842013-08-06 11:12:49 -0400401 for i in indices if rss[i] \
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400402 for r in getattr (rss[i], c.Rule) \
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400403 if r and all (g in s.glyphs for g in c.RuleData (r)) \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400404 for ll in getattr (r, c.LookupRecord) if ll \
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400405 ), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400406 elif self.Format == 2:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400407 if not self.Coverage.intersect (s.glyphs):
Behdad Esfahbod31084302013-07-23 22:22:38 -0400408 return []
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400409 # XXX Intersect glyphs with coverage before going further
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400410 indices = getattr (self, c.ClassDef).intersect (s.glyphs)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400411 rss = getattr (self, c.RuleSet)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400412 return sum ((s.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs (s) \
Behdad Esfahboddd6fc842013-08-06 11:12:49 -0400413 for i in indices if rss[i] \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400414 for r in getattr (rss[i], c.Rule) \
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400415 if r and all (all (cd.intersects_class (s.glyphs, k) for k in klist) \
416 for cd,klist in zip (c.ContextData (self), c.RuleData (r))) \
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400417 for ll in getattr (r, c.LookupRecord) if ll \
418 ), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400419 elif self.Format == 3:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400420 if not all (x.intersect (s.glyphs) for x in c.RuleData (self)):
Behdad Esfahbod00776972013-07-23 15:33:00 -0400421 return []
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400422 return sum ((s.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs (s) \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400423 for ll in getattr (self, c.LookupRecord) if ll), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400424 else:
425 assert 0, "unknown format: %s" % self.Format
426
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400427@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ContextPos,
428 fontTools.ttLib.tables.otTables.ChainContextSubst, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400429def subset_glyphs (self, s):
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400430 c = self.__classify_context ()
431
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400432 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400433 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400434 rss = getattr (self, c.RuleSet)
435 rss = [rss[i] for i in indices]
436 for rs in rss:
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400437 if rs:
438 ss = getattr (rs, c.Rule)
439 ss = [r for r in ss \
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400440 if r and all (g in s.glyphs for g in c.RuleData (r))]
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400441 setattr (rs, c.Rule, ss)
442 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400443 # Prune empty subrulesets
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400444 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400445 setattr (self, c.RuleSet, rss)
446 setattr (self, c.RuleSetCount, len (rss))
447 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400448 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400449 if not self.Coverage.subset (s.glyphs):
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400450 return False
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400451 # XXX Intersect glyphs with coverage before going further
452 indices = getattr (self, c.ClassDef).subset (s.glyphs, remap=False)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400453 rss = getattr (self, c.RuleSet)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400454 rss = [rss[i] for i in indices]
455 ContextData = c.ContextData (self)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400456 klass_maps = [x.subset (s.glyphs, remap=True) for x in ContextData]
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400457 for rs in rss:
458 if rs:
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400459 ss = getattr (rs, c.Rule)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400460 ss = [r for r in ss \
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400461 if r and all (all (k in klass_map for k in klist) \
462 for klass_map,klist in zip (klass_maps, c.RuleData (r)))]
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400463 setattr (rs, c.Rule, ss)
464 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400465
466 # Remap rule classes
467 for r in ss:
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400468 c.SetRuleData (r, [[klass_map.index (k) for k in klist] \
469 for klass_map,klist in zip (klass_maps, c.RuleData (r))])
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400470 # Prune empty subrulesets
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400471 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
472 setattr (self, c.RuleSet, rss)
473 setattr (self, c.RuleSetCount, len (rss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400474 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400475 elif self.Format == 3:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400476 return all (x.subset (s.glyphs) for x in c.RuleData (self))
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400477 else:
478 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400479
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400480@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
481 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400482def subset_lookups (self, lookup_indices):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400483 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400484
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400485 if self.Format in [1, 2]:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400486 for rs in getattr (self, c.RuleSet):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400487 if rs:
488 for r in getattr (rs, c.Rule):
489 if r:
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400490 setattr (r, c.LookupRecord, [ll for ll in getattr (r, c.LookupRecord) if ll \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400491 if ll.LookupListIndex in lookup_indices])
492 for ll in getattr (r, c.LookupRecord):
493 if ll:
494 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400495 elif self.Format == 3:
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400496 setattr (self, c.LookupRecord, [ll for ll in getattr (self, c.LookupRecord) if ll \
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400497 if ll.LookupListIndex in lookup_indices])
498 for ll in getattr (self, c.LookupRecord):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400499 if ll:
500 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400501 else:
502 assert 0, "unknown format: %s" % self.Format
503
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400504@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
505 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400506def collect_lookups (self):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400507 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400508
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400509 if self.Format in [1, 2]:
Behdad Esfahbod27108392013-07-23 16:40:47 -0400510 return [ll.LookupListIndex \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400511 for rs in getattr (self, c.RuleSet) if rs \
512 for r in getattr (rs, c.Rule) if r \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400513 for ll in getattr (r, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400514 elif self.Format == 3:
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400515 return [ll.LookupListIndex \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400516 for ll in getattr (self, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400517 else:
518 assert 0, "unknown format: %s" % self.Format
519
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400520@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400521def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400522 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400523 return self.ExtSubTable.closure_glyphs (s)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400524 else:
525 assert 0, "unknown format: %s" % self.Format
526
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400527@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400528def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400529 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400530 return self.ExtSubTable.subset_glyphs (s)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400531 else:
532 assert 0, "unknown format: %s" % self.Format
533
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400534@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
535def subset_lookups (self, lookup_indices):
536 if self.Format == 1:
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400537 return self.ExtSubTable.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400538 else:
539 assert 0, "unknown format: %s" % self.Format
540
541@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
542def collect_lookups (self):
543 if self.Format == 1:
544 return self.ExtSubTable.collect_lookups ()
545 else:
546 assert 0, "unknown format: %s" % self.Format
547
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400548@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400549def closure_glyphs (self, s):
550 return sum ((st.closure_glyphs (s) for st in self.SubTable if st), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400551
552@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400553def subset_glyphs (self, s):
554 self.SubTable = [st for st in self.SubTable if st and st.subset_glyphs (s)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400555 self.SubTableCount = len (self.SubTable)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400556 return bool (self.SubTableCount)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400557
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400558@add_method(fontTools.ttLib.tables.otTables.Lookup)
559def subset_lookups (self, lookup_indices):
560 for s in self.SubTable:
561 s.subset_lookups (lookup_indices)
562
563@add_method(fontTools.ttLib.tables.otTables.Lookup)
564def collect_lookups (self):
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400565 return unique_sorted (sum ((st.collect_lookups () for st in self.SubTable if st), []))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400566
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400567@add_method(fontTools.ttLib.tables.otTables.LookupList)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400568def subset_glyphs (self, s):
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400569 "Returns the indices of nonempty lookups."
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400570 return [i for (i,l) in enumerate (self.Lookup) if l and l.subset_glyphs (s)]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400571
572@add_method(fontTools.ttLib.tables.otTables.LookupList)
573def subset_lookups (self, lookup_indices):
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400574 self.Lookup = [self.Lookup[i] for i in lookup_indices if i < self.LookupCount]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400575 self.LookupCount = len (self.Lookup)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400576 for l in self.Lookup:
577 l.subset_lookups (lookup_indices)
578
579@add_method(fontTools.ttLib.tables.otTables.LookupList)
580def closure_lookups (self, lookup_indices):
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400581 lookup_indices = unique_sorted (lookup_indices)
582 recurse = lookup_indices
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400583 while True:
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400584 recurse_lookups = sum ((self.Lookup[i].collect_lookups () for i in recurse if i < self.LookupCount), [])
585 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 -0400586 if not recurse_lookups:
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400587 return unique_sorted (lookup_indices)
588 recurse_lookups = unique_sorted (recurse_lookups)
589 lookup_indices.extend (recurse_lookups)
590 recurse = recurse_lookups
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400591
592@add_method(fontTools.ttLib.tables.otTables.Feature)
593def subset_lookups (self, lookup_indices):
594 self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices]
595 # Now map them.
596 self.LookupListIndex = [lookup_indices.index (l) for l in self.LookupListIndex]
597 self.LookupCount = len (self.LookupListIndex)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400598 return self.LookupCount
Behdad Esfahbod54660612013-07-21 18:16:55 -0400599
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400600@add_method(fontTools.ttLib.tables.otTables.Feature)
601def collect_lookups (self):
602 return self.LookupListIndex[:]
603
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400604@add_method(fontTools.ttLib.tables.otTables.FeatureList)
605def subset_lookups (self, lookup_indices):
606 "Returns the indices of nonempty features."
607 feature_indices = [i for (i,f) in enumerate (self.FeatureRecord) if f.Feature.subset_lookups (lookup_indices)]
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400608 self.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400609 return feature_indices
610
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400611@add_method(fontTools.ttLib.tables.otTables.FeatureList)
612def collect_lookups (self, feature_indices):
613 return unique_sorted (sum ((self.FeatureRecord[i].Feature.collect_lookups () for i in feature_indices
614 if i < self.FeatureCount), []))
615
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400616@add_method(fontTools.ttLib.tables.otTables.FeatureList)
617def subset_features (self, feature_indices):
618 self.FeatureRecord = [self.FeatureRecord[i] for i in feature_indices]
619 self.FeatureCount = len (self.FeatureRecord)
620 return bool (self.FeatureCount)
621
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400622@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
623def subset_features (self, feature_indices):
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400624 if self.ReqFeatureIndex in feature_indices:
625 self.ReqFeatureIndex = feature_indices.index (self.ReqFeatureIndex)
626 else:
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400627 self.ReqFeatureIndex = 65535
628 self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400629 # Now map them.
630 self.FeatureIndex = [feature_indices.index (f) for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400631 self.FeatureCount = len (self.FeatureIndex)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400632 return bool (self.FeatureCount or self.ReqFeatureIndex != 65535)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400633
634@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
635def collect_features (self):
636 feature_indices = self.FeatureIndex[:]
637 if self.ReqFeatureIndex != 65535:
638 feature_indices.append (self.ReqFeatureIndex)
639 return unique_sorted (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400640
641@add_method(fontTools.ttLib.tables.otTables.Script)
642def subset_features (self, feature_indices):
643 if self.DefaultLangSys and not self.DefaultLangSys.subset_features (feature_indices):
644 self.DefaultLangSys = None
645 self.LangSysRecord = [l for l in self.LangSysRecord if l.LangSys.subset_features (feature_indices)]
646 self.LangSysCount = len (self.LangSysRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400647 return bool (self.LangSysCount or self.DefaultLangSys)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400648
649@add_method(fontTools.ttLib.tables.otTables.Script)
650def collect_features (self):
Behdad Esfahbod2307c8b2013-07-23 11:18:13 -0400651 feature_indices = [l.LangSys.collect_features () for l in self.LangSysRecord]
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400652 if self.DefaultLangSys:
653 feature_indices.append (self.DefaultLangSys.collect_features ())
654 return unique_sorted (sum (feature_indices, []))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400655
656@add_method(fontTools.ttLib.tables.otTables.ScriptList)
657def subset_features (self, feature_indices):
658 self.ScriptRecord = [s for s in self.ScriptRecord if s.Script.subset_features (feature_indices)]
659 self.ScriptCount = len (self.ScriptRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400660 return bool (self.ScriptCount)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400661
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400662@add_method(fontTools.ttLib.tables.otTables.ScriptList)
663def collect_features (self):
664 return unique_sorted (sum ((s.Script.collect_features () for s in self.ScriptRecord), []))
665
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400666@add_method(fontTools.ttLib.getTableClass('GSUB'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400667def closure_glyphs (self, s):
668 s.table = self.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400669 feature_indices = self.table.ScriptList.collect_features ()
670 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400671 orig_glyphs = s.glyphs
672 glyphs = unique_sorted (s.glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400673 while True:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400674 s.glyphs = glyphs
675 additions = (sum ((self.table.LookupList.Lookup[i].closure_glyphs (s) \
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400676 for i in lookup_indices if i < self.table.LookupList.LookupCount), []))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400677 additions = unique_sorted (g for g in additions if g not in glyphs)
678 if not additions:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400679 s.glyphs = orig_glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400680 return glyphs
681 glyphs.extend (additions)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400682 del s.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400683
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400684@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400685def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400686 s.glyphs = s.glyphs_gsubed
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400687 lookup_indices = self.table.LookupList.subset_glyphs (s)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400688 self.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400689 self.prune_lookups ()
690 return True
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400691
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400692@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400693def subset_lookups (self, lookup_indices):
694 "Retrains specified lookups, then removes empty features, language systems, and scripts."
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400695 self.table.LookupList.subset_lookups (lookup_indices)
696 feature_indices = self.table.FeatureList.subset_lookups (lookup_indices)
697 self.table.ScriptList.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400698
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400699@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
700def prune_lookups (self):
701 "Remove unreferenced lookups"
702 feature_indices = self.table.ScriptList.collect_features ()
703 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
704 lookup_indices = self.table.LookupList.closure_lookups (lookup_indices)
705 self.subset_lookups (lookup_indices)
706
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400707@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
708def subset_feature_tags (self, feature_tags):
709 feature_indices = [i for (i,f) in enumerate (self.table.FeatureList.FeatureRecord) if f.FeatureTag in feature_tags]
710 self.table.FeatureList.subset_features (feature_indices)
711 self.table.ScriptList.subset_features (feature_indices)
712
713@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400714def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400715 if options.layout_features and '*' not in options.layout_features:
716 self.subset_feature_tags (options.layout_features)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400717 self.prune_lookups ()
718 return True
719
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400720@add_method(fontTools.ttLib.getTableClass('GDEF'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400721def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400722 glyphs = s.glyphs_gsubed
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400723 table = self.table
724 if table.LigCaretList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400725 indices = table.LigCaretList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400726 table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i] for i in indices]
727 table.LigCaretList.LigGlyphCount = len (table.LigCaretList.LigGlyph)
728 if not table.LigCaretList.LigGlyphCount:
729 table.LigCaretList = None
730 if table.MarkAttachClassDef:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400731 table.MarkAttachClassDef.classDefs = {g:v for g,v in table.MarkAttachClassDef.classDefs.items() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400732 if not table.MarkAttachClassDef.classDefs:
733 table.MarkAttachClassDef = None
734 if table.GlyphClassDef:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400735 table.GlyphClassDef.classDefs = {g:v for g,v in table.GlyphClassDef.classDefs.items() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400736 if not table.GlyphClassDef.classDefs:
737 table.GlyphClassDef = None
738 if table.AttachList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400739 indices = table.AttachList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400740 table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i] for i in indices]
741 table.AttachList.GlyphCount = len (table.AttachList.AttachPoint)
742 if not table.AttachList.GlyphCount:
743 table.AttachList = None
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400744 return bool (table.LigCaretList or table.MarkAttachClassDef or table.GlyphClassDef or table.AttachList)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400745
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400746@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbodd4e33a72013-07-24 18:51:05 -0400747def prune_pre_subset (self, options):
748 # Prune unknown kern table types
749 self.kernTables = [t for t in self.kernTables if hasattr (t, 'kernTable')]
750 return bool (self.kernTables)
751
752@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400753def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400754 glyphs = s.glyphs_gsubed
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400755 for t in self.kernTables:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400756 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 -0400757 self.kernTables = [t for t in self.kernTables if t.kernTable]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400758 return bool (self.kernTables)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400759
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400760@add_method(fontTools.ttLib.getTableClass('hmtx'), fontTools.ttLib.getTableClass('vmtx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400761def subset_glyphs (self, s):
762 self.metrics = {g:v for g,v in self.metrics.items() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400763 return bool (self.metrics)
Behdad Esfahbodc7160442013-07-22 14:29:08 -0400764
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400765@add_method(fontTools.ttLib.getTableClass('hdmx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400766def subset_glyphs (self, s):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400767 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 -0400768 return bool (self.hdmx)
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400769
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400770@add_method(fontTools.ttLib.getTableClass('VORG'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400771def subset_glyphs (self, s):
772 self.VOriginRecords = {g:v for g,v in self.VOriginRecords.items() if g in s.glyphs}
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400773 self.numVertOriginYMetrics = len (self.VOriginRecords)
774 return True # Never drop; has default metrics
775
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400776@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400777def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400778 if not options.glyph_names:
Behdad Esfahbod42648242013-07-23 12:56:06 -0400779 self.formatType = 3.0
780 return True
781
782@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400783def subset_glyphs (self, s):
Behdad Esfahbod42648242013-07-23 12:56:06 -0400784 self.extraNames = [] # This seems to do it
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -0400785 return True
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400786
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400787# Copied from _g_l_y_f.py
788ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes
789ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points
790ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true
791WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0
792NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!)
793MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one
794WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy
795WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11
796WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow
797USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph
798OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts
799SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple)
800UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS)
801
802@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
803def getComponentNamesFast (self, glyfTable):
804 if struct.unpack(">h", self.data[:2])[0] >= 0:
805 return [] # Not composite
806 data = self.data
807 i = 10
808 components = []
809 more = 1
810 while more:
811 flags, glyphID = struct.unpack(">HH", data[i:i+4])
812 i += 4
813 flags = int(flags)
814 components.append (glyfTable.getGlyphName (int (glyphID)))
815
816 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
817 else: i += 2
818 if flags & WE_HAVE_A_SCALE: i += 2
819 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
820 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
821 more = flags & MORE_COMPONENTS
822 return components
823
824@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
825def remapComponentsFast (self, indices):
826 if struct.unpack(">h", self.data[:2])[0] >= 0:
827 return # Not composite
828 data = bytearray (self.data)
829 i = 10
830 more = 1
831 while more:
832 flags = (data[i] << 8) | data[i+1]
833 glyphID = (data[i+2] << 8) | data[i+3]
834 # Remap
835 glyphID = indices.index (glyphID)
836 data[i+2] = glyphID >> 8
837 data[i+3] = glyphID & 0xFF
838 i += 4
839 flags = int(flags)
840
841 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
842 else: i += 2
843 if flags & WE_HAVE_A_SCALE: i += 2
844 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
845 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
846 more = flags & MORE_COMPONENTS
847 self.data = str (data)
848
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400849@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
850def dropInstructionsFast (self):
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400851 numContours = struct.unpack(">h", self.data[:2])[0]
852 data = bytearray (self.data)
853 i = 10
854 if numContours >= 0:
855 i += 2 * numContours # endPtsOfContours
856 instructionLen = (data[i] << 8) | data[i+1]
857 # Zero it
858 data[i] = data [i+1] = 0
859 i += 2
Behdad Esfahbod0fb69882013-07-24 17:25:35 -0400860 if instructionLen:
861 # Splice it out
862 data = data[:i] + data[i+instructionLen:]
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400863 else:
864 more = 1
865 while more:
866 flags = (data[i] << 8) | data[i+1]
867 # Turn instruction flag off
868 flags &= ~WE_HAVE_INSTRUCTIONS
869 data[i+0] = flags >> 8
870 data[i+1] = flags & 0xFF
871 i += 4
872 flags = int(flags)
873
874 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
875 else: i += 2
876 if flags & WE_HAVE_A_SCALE: i += 2
877 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
878 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
879 more = flags & MORE_COMPONENTS
880 # Cut off
881 data = data[:i]
882 if len(data) % 4:
883 # add pad bytes
884 nPadBytes = 4 - (len(data) % 4)
885 for i in range (nPadBytes):
886 data.append (0)
887 self.data = str (data)
888
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400889@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400890def closure_glyphs (self, s):
891 glyphs = unique_sorted (s.glyphs)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400892 decompose = glyphs
893 # I don't know if component glyphs can be composite themselves.
894 # We handle them anyway.
895 while True:
896 components = []
897 for g in decompose:
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400898 if g not in self.glyphs:
Behdad Esfahbodf8c20e42013-07-23 23:13:23 -0400899 continue
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400900 gl = self.glyphs[g]
901 if hasattr (gl, "data"):
902 for c in gl.getComponentNamesFast (self):
903 if c not in glyphs:
904 components.append (c)
905 else:
906 # TTX seems to expand gid0..3 always
907 if gl.isComposite ():
908 for c in gl.components:
909 if c.glyphName not in glyphs:
910 components.append (c.glyphName)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400911 components = [c for c in components if c not in glyphs]
912 if not components:
913 return glyphs
914 decompose = unique_sorted (components)
915 glyphs.extend (components)
916
917@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400918def subset_glyphs (self, s):
919 self.glyphs = {g:v for g,v in self.glyphs.items() if g in s.glyphs}
920 indices = [i for i,g in enumerate (self.glyphOrder) if g in s.glyphs]
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400921 for v in self.glyphs.values ():
922 if hasattr (v, "data"):
923 v.remapComponentsFast (indices)
924 else:
925 pass # No need
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400926 self.glyphOrder = [g for g in self.glyphOrder if g in s.glyphs]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400927 return bool (self.glyphs)
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400928
Behdad Esfahboded98c612013-07-23 12:37:41 -0400929@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400930def prune_post_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400931 if not options.hinting:
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400932 for v in self.glyphs.values ():
933 if hasattr (v, "data"):
934 v.dropInstructionsFast ()
935 else:
936 v.program = fontTools.ttLib.tables.ttProgram.Program()
937 v.program.fromBytecode([])
Behdad Esfahboded98c612013-07-23 12:37:41 -0400938 return True
939
Behdad Esfahbod2b677c82013-07-23 13:37:13 -0400940@add_method(fontTools.ttLib.getTableClass('CFF '))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400941def subset_glyphs (self, s):
Behdad Esfahbod2b677c82013-07-23 13:37:13 -0400942 assert 0, "unimplemented"
943
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400944@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -0400945def closure_glyphs (self, s):
946 tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [1, 10]]
947 extra = []
Behdad Esfahbod98259f22013-07-31 20:16:24 -0400948 for u in s.unicodes_requested:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -0400949 found = False
950 for table in tables:
951 if u in table.cmap:
952 extra.append (table.cmap[u])
953 found = True
954 break
955 if not found:
956 s.log ("No glyph for Unicode value %s; skipping." % u)
957 return extra
958
959@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400960def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400961 if not options.legacy_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400962 # Drop non-Unicode / non-Symbol cmaps
963 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 -0400964 if not options.symbol_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400965 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 -0400966 # TODO Only keep one subtable?
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400967 # For now, drop format=0 which can't be subset_glyphs easily?
968 self.tables = [t for t in self.tables if t.format != 0]
969 return bool (self.tables)
970
971@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400972def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400973 s.glyphs = s.glyphs_cmaped
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400974 for t in self.tables:
Behdad Esfahbod9453a362013-07-22 16:21:24 -0400975 # For reasons I don't understand I need this here
976 # to force decompilation of the cmap format 14.
977 try:
978 getattr (t, "asdf")
979 except AttributeError:
980 pass
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400981 if t.format == 14:
Behdad Esfahbod9453a362013-07-22 16:21:24 -0400982 # XXX We drop all the default-UVS mappings (g==None)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400983 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 -0400984 t.uvsDict = {v:l for (v,l) in t.uvsDict.items() if l}
985 else:
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -0400986 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 -0400987 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 -0400988 # XXX Convert formats when needed
Behdad Esfahbod61addb42013-07-23 11:03:49 -0400989 return bool (self.tables)
990
Behdad Esfahbod61addb42013-07-23 11:03:49 -0400991@add_method(fontTools.ttLib.getTableClass('name'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400992def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400993 if '*' not in options.name_IDs:
994 self.names = [n for n in self.names if n.nameID in options.name_IDs]
995 if not options.name_legacy:
Behdad Esfahbod20faeb02013-07-23 13:19:03 -0400996 self.names = [n for n in self.names if n.platformID == 3 and n.platEncID == 1]
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400997 if '*' not in options.name_languages:
998 self.names = [n for n in self.names if n.langID in options.name_languages]
Behdad Esfahbod20faeb02013-07-23 13:19:03 -0400999 return True # Retain even if empty
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001000
Behdad Esfahbod8c646f62013-07-22 15:06:23 -04001001
Behdad Esfahbodbc25f162013-07-23 12:56:54 -04001002drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'PCLT', 'LTSH']
Behdad Esfahbod103a12f2013-07-23 15:08:39 -04001003drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill'] # Graphite
Behdad Esfahbod38e852c2013-07-23 16:56:50 -04001004drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL'] # Color
Behdad Esfahboded98c612013-07-23 12:37:41 -04001005no_subset_tables = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2', 'loca', 'name', 'cvt ', 'fpgm', 'prep']
Behdad Esfahbodbc25f162013-07-23 12:56:54 -04001006hinting_tables = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
Behdad Esfahbod29df0462013-07-23 11:05:25 -04001007
Behdad Esfahbod356c42e2013-07-23 12:10:46 -04001008# Based on HarfBuzz shapers
1009layout_features_dict = {
1010 # Default shaper
1011 'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
1012 'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
1013 'vertical': ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
1014 'ltr': ['ltra', 'ltrm'],
1015 'rtl': ['rtla', 'rtlm'],
1016 # Complex shapers
Behdad Esfahbodf36b5a92013-08-04 16:54:46 -04001017 'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3', 'cswh', 'mset'],
Behdad Esfahbod356c42e2013-07-23 12:10:46 -04001018 'hangul': ['ljmo', 'vjmo', 'tjmo'],
1019 'tibetal': ['abvs', 'blws', 'abvm', 'blwm'],
1020 'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half', 'abvf', 'pstf', 'cfar', 'vatu', 'cjct',
1021 'init', 'pres', 'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
1022}
1023layout_features_all = unique_sorted (sum (layout_features_dict.values (), []))
1024
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -04001025# TODO OS/2 ulUnicodeRange / ulCodePageRange?
Behdad Esfahbodf71267b2013-07-23 12:59:13 -04001026# TODO Drop unneeded GSUB/GPOS Script/LangSys entries
Behdad Esfahbod398d3892013-07-23 15:29:40 -04001027# TODO Avoid recursing too much
Behdad Esfahbode94aa0e2013-07-23 13:22:04 -04001028# TODO Text direction considerations
1029# TODO Text script / language considerations
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001030# TODO Drop unknown tables? Using DefaultTable.prune?
Behdad Esfahbod8c4f7cc2013-07-24 17:58:29 -04001031# TODO Drop GPOS Device records if not hinting?
Behdad Esfahbod56ebd042013-07-22 13:02:24 -04001032
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001033
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001034class Subsetter:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001035
1036 class Options:
1037 drop_tables = drop_tables_default
1038 layout_features = layout_features_all
1039 hinting = False
1040 glyph_names = False
1041 legacy_cmap = False
1042 symbol_cmap = False
1043 name_IDs = [1, 2] # Family and Style
1044 name_legacy = False
1045 name_languages = [0x0409] # English
1046 mandatory_glyphs = True # First four for TrueType, .notdef for CFF
1047 recalc_bboxes = False # Slows us down
1048
1049 def __init__ (self, **kwargs):
1050
1051 self.set (**kwargs)
1052
1053 def set (self, **kwargs):
1054 for k,v in kwargs.items ():
1055 if not hasattr (self, k):
1056 raise Exception ("Unknown option '%s'" % k)
1057 setattr (self, k, v)
1058
1059 def parse_opts (self, argv, ignore_unknown=False):
1060 ret = []
1061 opts = {}
1062 for a in argv:
1063 if not a.startswith ('--'):
1064 ret.append (a)
1065 continue
1066 a = a[2:]
1067 i = a.find ('=')
1068 if i == -1:
1069 if a.startswith ("no-"):
1070 k = a[3:]
1071 v = False
1072 else:
1073 k = a
1074 v = True
1075 else:
1076 k = a[:i]
1077 v = a[i+1:]
1078 k = k.replace ('-', '_')
1079 if not hasattr (self, k):
1080 if ignore_unknown:
1081 ret.append (a)
1082 continue
1083 else:
1084 raise Exception ("Unknown option '%s'" % a)
1085
1086 ov = getattr (self, k)
1087 if isinstance (ov, bool):
1088 v = bool (v)
1089 elif isinstance (ov, int):
1090 v = int (v)
1091 elif isinstance (ov, list):
1092 v = v.split (',')
1093 v = [int (x, 0) if x[0] in range (10) else x for x in v]
1094
1095 opts[k] = v
1096 self.set (**opts)
1097
1098 return ret
1099
1100
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001101 def __init__ (self, font=None, options=None, log=None):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001102
1103 if isinstance (font, basestring):
1104 font = fontTools.ttx.TTFont (font)
1105 if not log:
1106 log = Logger()
1107 if not options:
1108 options = Options()
1109
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001110 self.font = font
1111 self.options = options
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001112 self.log = log
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001113 self.unicodes_requested = set ()
1114 self.glyphs_requested = set ()
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001115
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001116 def populate (self, glyphs=[], unicodes=[], text=""):
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001117 self.unicodes_requested.update (unicodes)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001118 if isinstance (text, str):
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001119 text = text.decode ("utf8")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001120 for u in text:
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001121 self.unicodes_requested.add (ord (u))
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001122 self.glyphs_requested.update (glyphs)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001123
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001124 def pre_prune (self):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001125
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001126 for tag in self.font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001127 if tag == 'GlyphOrder': continue
1128
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001129 if tag in self.options.drop_tables or \
1130 (tag in hinting_tables and not self.options.hinting):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001131 self.log (tag, "dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001132 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001133 continue
1134
1135 clazz = fontTools.ttLib.getTableClass(tag)
1136
1137 if hasattr (clazz, 'prune_pre_subset'):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001138 table = self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001139 retain = table.prune_pre_subset (self.options)
1140 self.log.lapse ("prune '%s'" % tag)
1141 if not retain:
1142 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001143 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001144 continue
1145 else:
1146 self.log (tag, "pruned")
1147
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001148 def closure_glyphs (self):
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001149
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001150 self.glyphs = self.glyphs_requested
1151
1152 if 'cmap' in self.font:
1153 extra_glyphs = self.font['cmap'].closure_glyphs (self)
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001154 self.glyph = self.glyphs.copy ()
1155 self.glyphs.update (extra_glyphs)
1156 self.glyphs_cmaped = self.glyphs
1157
1158 if self.options.mandatory_glyphs:
1159 self.glyphs = self.glyphs.copy ()
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001160 if 'glyf' in self.font:
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001161 for i in range (4):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001162 self.glyphs.add (self.font.getGlyphName (i))
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001163 self.log ("Added first four glyphs to subset")
1164 else:
1165 self.glyphs.add ('.notdef')
1166 self.log ("Added .notdef glyph to subset")
1167
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001168 if 'GSUB' in self.font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001169 self.log ("Closing glyph list over 'GSUB': %d glyphs before" % len (self.glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001170 self.log.glyphs (self.glyphs, font=self.font)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001171 self.glyphs = set (self.font['GSUB'].closure_glyphs (self))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001172 self.log ("Closed glyph list over 'GSUB': %d glyphs after" % len (self.glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001173 self.log.glyphs (self.glyphs, font=self.font)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001174 self.log.lapse ("close glyph list over 'GSUB'")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001175 self.glyphs_gsubed = self.glyphs
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001176
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001177 if 'glyf' in self.font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001178 self.log ("Closing glyph list over 'glyf': %d glyphs before" % len (self.glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001179 self.log.glyphs (self.glyphs, font=self.font)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001180 self.glyphs = set (self.font['glyf'].closure_glyphs (self))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001181 self.log ("Closed glyph list over 'glyf': %d glyphs after" % len (self.glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001182 self.log.glyphs (self.glyphs, font=self.font)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001183 self.log.lapse ("close glyph list over 'glyf'")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001184 self.glyphs_glyfed = self.glyphs
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001185
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001186 self.glyphs_all = self.glyphs
1187
1188 self.log ("Retaining %d glyphs: " % len (self.glyphs_all))
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001189
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001190 def subset_glyphs (self):
1191 for tag in self.font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001192 if tag == 'GlyphOrder': continue
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001193 clazz = fontTools.ttLib.getTableClass(tag)
1194
1195 if tag in no_subset_tables:
1196 self.log (tag, "subsetting not needed")
1197 elif hasattr (clazz, 'subset_glyphs'):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001198 table = self.font[tag]
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -04001199 self.glyphs = self.glyphs_all
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001200 retain = table.subset_glyphs (self)
1201 self.log.lapse ("subset '%s'" % tag)
1202 if not retain:
1203 self.log (tag, "subsetted to empty; dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001204 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001205 else:
1206 self.log (tag, "subsetted")
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001207 else:
1208 self.log (tag, "NOT subset; don't know how to subset")
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001209
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001210 glyphOrder = self.font.getGlyphOrder()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001211 glyphOrder = [g for g in glyphOrder if g in self.glyphs_all]
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001212 self.font.setGlyphOrder (glyphOrder)
1213 self.font._buildReverseGlyphOrderDict ()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001214 self.log.lapse ("subset GlyphOrder")
1215
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001216 def post_prune (self):
1217 for tag in self.font.keys():
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001218 if tag == 'GlyphOrder': continue
1219 clazz = fontTools.ttLib.getTableClass(tag)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001220 if hasattr (clazz, 'prune_post_subset'):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001221 table = self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001222 retain = table.prune_post_subset (self.options)
1223 self.log.lapse ("prune '%s'" % tag)
1224 if not retain:
1225 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001226 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001227 else:
1228 self.log (tag, "pruned")
1229
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001230 def subset (self, font):
1231
1232 self.font = font
Behdad Esfahbod756af492013-08-01 12:05:26 -04001233
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001234 self.font.recalcBBoxes = self.options.recalc_bboxes
1235
1236 self.pre_prune ()
1237 self.closure_glyphs ()
1238 self.subset_glyphs ()
1239 self.post_prune ()
1240
Behdad Esfahbod756af492013-08-01 12:05:26 -04001241 del self.font
1242
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001243import sys, time
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001244
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001245class Logger:
1246
1247 def __init__ (self, verbose=False, xml=False, timing=False):
1248 self.verbose = verbose
1249 self.xml = xml
1250 self.timing = timing
1251 self.last_time = self.start_time = time.time ()
1252
1253 def parse_opts (self, argv):
1254 argv = argv[:]
1255 for v in ['verbose', 'xml', 'timing']:
1256 if "--"+v in argv:
1257 setattr (self, v, True)
1258 argv.remove ("--"+v)
1259 return argv
1260
1261 def __call__ (self, *things):
1262 if not self.verbose:
1263 return
1264 print ' '.join (str (x) for x in things)
1265
1266 def lapse (self, *things):
1267 if not self.timing:
1268 return
1269 new_time = time.time ()
1270 print "Took %0.3fs to %s" % (new_time - self.last_time, ' '.join (str (x) for x in things))
1271 self.last_time = new_time
1272
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001273 def glyphs (self, glyphs, glyph_names=True, font=None):
1274 self ("Names: ", sorted (glyphs))
1275 if font:
1276 glyphOrder = font.getGlyphOrder()
1277 self ("Gids : ", sorted (glyphOrder.index (g) for g in glyphs))
1278
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001279 def font (self, font, file=sys.stdout):
1280 if not self.xml:
1281 return
1282 import xmlWriter, sys
1283 writer = xmlWriter.XMLWriter (file)
1284 font.disassembleInstructions = False # Work around ttx bug
1285 for tag in font.keys():
1286 writer.begintag (tag)
1287 writer.newline ()
1288 font[tag].toXML(writer, font)
1289 writer.endtag (tag)
1290 writer.newline ()
1291
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001292def main (args):
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001293
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001294 log = Logger ()
1295 args = log.parse_opts (args)
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001296
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001297 options = Subsetter.Options ()
1298 args = options.parse_opts (args)
1299
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001300 if len (args) < 2:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001301 import sys
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001302 print >>sys.stderr, "usage: pyotlss.py font-file glyph..."
1303 sys.exit (1)
1304
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001305 fontfile = args[0]
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001306 args = args[1:]
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001307
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001308 # TODO Option for ignoreDecompileErrors?
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001309 font = fontTools.ttx.TTFont (fontfile)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001310 s = Subsetter (font=font, options=options, log=log)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001311 log.lapse ("load font")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001312
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001313 # Hack:
1314 #
1315 # If we don't need glyph names, change 'post' class to not try to
1316 # load them. It avoid lots of headache with broken fonts as well
1317 # as loading time.
1318 #
1319 # Ideally ttLib should provide a way to ask it to skip loading
1320 # glyph names. But it currently doesn't provide such a thing.
1321 #
1322 if not options.glyph_names \
Behdad Esfahbod9ae5d282013-08-08 21:18:17 -04001323 and all (any (g.startswith (p) for p in ['gid', 'glyph', 'uni', 'U+']) \
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001324 for g in args):
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001325 post = fontTools.ttLib.getTableClass('post')
1326 saved = post.decode_format_2_0
1327 post.decode_format_2_0 = post.decode_format_3_0
1328 f = font['post']
1329 if f.formatType == 2.0:
1330 f.formatType = 3.0
1331 post.decode_format_2_0 = saved
1332 del post, saved, f
1333
1334 names = font.getGlyphNames()
1335 log.lapse ("loading glyph names")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001336
1337 glyphs = []
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001338 unicodes = []
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001339 for g in args:
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001340 if g in names:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001341 glyphs.append (g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001342 continue
Behdad Esfahbod9ae5d282013-08-08 21:18:17 -04001343 if g.startswith ('uni') or g.startswith ('U+'):
1344 if g.startswith ('uni') and len (g) > 3:
1345 g = g[3:]
1346 elif g.startswith ('U+') and len (g) > 2:
1347 g = g[2:]
1348 u = int (g, 16)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001349 unicodes.append (u)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001350 continue
1351 if g.startswith ('gid') or g.startswith ('glyph'):
1352 if g.startswith ('gid') and len (g) > 3:
1353 g = g[3:]
1354 elif g.startswith ('glyph') and len (g) > 5:
1355 g = g[5:]
1356 try:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001357 glyphs.append (font.getGlyphName (int (g), requireReal=1))
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001358 except ValueError:
1359 raise Exception ("Invalid glyph identifier %s" % g)
1360 continue
1361 raise Exception ("Invalid glyph identifier %s" % g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001362 log.lapse ("compile glyph list")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001363 log ("Unicodes:", unicodes)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001364 log ("Glyphs:", glyphs)
1365
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001366 s.populate (glyphs=glyphs, unicodes=unicodes)
1367 s.subset (font)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -04001368
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001369 font.save (fontfile + '.subset')
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001370 log.lapse ("compile and save font")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001371
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001372 log.last_time = s.log.start_time
1373 log.lapse ("make one with everything (TOTAL TIME)")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001374
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001375 log.font (font)
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001376
1377if __name__ == '__main__':
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001378 import sys
1379 main (sys.argv[1:])