blob: ef3df9ba1562385a9a7aaaa472015f51ce9e96cc [file] [log] [blame]
Behdad Esfahbod54660612013-07-21 18:16:55 -04001#!/usr/bin/python
Behdad Esfahboddb6d2e92013-08-13 12:42:12 -04002#
Behdad Esfahbod54660612013-07-21 18:16:55 -04003# Python OpenType Layout Subsetter
Behdad Esfahboddb6d2e92013-08-13 12:42:12 -04004# Later grown into a full OpenType subsetter...
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04005#
6# Copyright 2013 Google, Inc. All Rights Reserved.
7#
8# Licensed under the Apache License, Version 2.0 (the "License");
9# you may not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS,
16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19#
20# Google Author(s): Behdad Esfahbod
21#
Behdad Esfahbod54660612013-07-21 18:16:55 -040022
Behdad Esfahbodfa3bc5e2013-07-24 14:37:58 -040023# Try running on PyPy
24try:
25 import numpypy
26except ImportError:
27 pass
28
Behdad Esfahbod54660612013-07-21 18:16:55 -040029import fontTools.ttx
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -040030import struct
Behdad Esfahbod54660612013-07-21 18:16:55 -040031
Behdad Esfahbod54660612013-07-21 18:16:55 -040032
Behdad Esfahbod02b92062013-07-21 18:40:59 -040033def add_method (*clazzes):
Behdad Esfahbod54660612013-07-21 18:16:55 -040034 def wrapper(method):
Behdad Esfahbod02b92062013-07-21 18:40:59 -040035 for clazz in clazzes:
Behdad Esfahbodc0d59592013-07-24 14:41:47 -040036 assert clazz.__name__ != 'DefaultTable', 'Oops, table class not found.'
Behdad Esfahbod02b92062013-07-21 18:40:59 -040037 setattr (clazz, method.func_name, method)
Behdad Esfahbod54660612013-07-21 18:16:55 -040038 return wrapper
39
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040040def unique_sorted (l):
Behdad Esfahbod2d9a0962013-07-31 13:33:31 -040041 return sorted (set (l))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040042
Behdad Esfahbod97e17b82013-07-31 15:59:21 -040043def safeEval(data, eval=eval):
44 """A (kindof) safe replacement for eval."""
45 return eval(data, {"__builtins__":{}}, {})
46
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040047
Behdad Esfahbod54660612013-07-21 18:16:55 -040048@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040049def intersect (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -040050 "Returns ascending list of matching coverage values."
51 return [i for (i,g) in enumerate (self.glyphs) if g in glyphs]
52
53@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -040054def intersect_glyphs (self, glyphs):
55 "Returns set of intersecting glyphs."
56 return set (g for g in self.glyphs if g in glyphs)
57
58@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040059def subset (self, glyphs):
Behdad Esfahbodd821ea02013-07-23 10:50:43 -040060 "Returns ascending list of remaining coverage values."
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040061 indices = self.intersect (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -040062 self.glyphs = [g for g in self.glyphs if g in glyphs]
63 return indices
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040064
Behdad Esfahbod14374262013-08-08 22:26:49 -040065@add_method(fontTools.ttLib.tables.otTables.Coverage)
66def remap (self, coverage_map):
67 "Remaps coverage."
68 self.glyphs = [self.glyphs[i] for i in coverage_map]
69
Behdad Esfahbod54660612013-07-21 18:16:55 -040070@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040071def intersect (self, glyphs):
Behdad Esfahbode10803e2013-08-08 21:09:27 -040072 "Returns ascending list of matching class values."
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040073 return unique_sorted (([0] if any (g not in self.classDefs for g in glyphs) else []) + \
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040074 [v for g,v in self.classDefs.iteritems() if g in glyphs])
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040075
76@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -040077def intersect_class (self, glyphs, klass):
78 "Returns set of glyphs matching class."
Behdad Esfahbod0befd6b2013-08-05 22:47:14 -040079 if klass == 0:
Behdad Esfahbod849d25c2013-08-12 19:24:24 -040080 return set (g for g in glyphs if g not in self.classDefs)
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040081 return set (g for g,v in self.classDefs.iteritems() if v == klass and g in glyphs)
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040082
83@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040084def subset (self, glyphs, remap=False):
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040085 "Returns ascending list of remaining classes."
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040086 self.classDefs = {g:v for g,v in self.classDefs.iteritems() if g in glyphs}
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040087 # Note: while class 0 has the special meaning of "not matched", if no glyph will
88 # ever /not match/, we can optimize class 0 out too.
89 indices = unique_sorted (([0] if any (g not in self.classDefs for g in glyphs) else []) + \
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040090 self.classDefs.itervalues())
Behdad Esfahbodde71dca2013-07-24 12:40:54 -040091 if remap:
92 self.remap (indices)
93 return indices
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -040094
95@add_method(fontTools.ttLib.tables.otTables.ClassDef)
96def remap (self, class_map):
97 "Remaps classes."
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040098 self.classDefs = {g:class_map.index (v) for g,v in self.classDefs.iteritems()}
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040099
Behdad Esfahbod54660612013-07-21 18:16:55 -0400100@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400101def closure_glyphs (self, s, cur_glyphs=None):
102 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400103 if self.Format in [1, 2]:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400104 s.glyphs.update (v for g,v in self.mapping.iteritems() if g in cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400105 else:
106 assert 0, "unknown format: %s" % self.Format
107
108@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400109def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400110 if self.Format in [1, 2]:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400111 self.mapping = {g:v for g,v in self.mapping.iteritems() if g in s.glyphs and v in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400112 return bool (self.mapping)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400113 else:
114 assert 0, "unknown format: %s" % self.Format
115
116@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400117def closure_glyphs (self, s, cur_glyphs=None):
118 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400119 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400120 indices = self.Coverage.intersect (cur_glyphs)
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400121 s.glyphs.update (*(self.Sequence[i].Substitute for i in indices))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400122 else:
123 assert 0, "unknown format: %s" % self.Format
124
125@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400126def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400127 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400128 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400129 self.Sequence = [self.Sequence[i] for i in indices]
Behdad Esfahbod14374262013-08-08 22:26:49 -0400130 # Now drop rules generating glyphs we don't want
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400131 indices = [i for i,seq in enumerate (self.Sequence)
Behdad Esfahbod14374262013-08-08 22:26:49 -0400132 if all (sub in s.glyphs for sub in seq.Substitute)]
133 self.Sequence = [self.Sequence[i] for i in indices]
134 self.Coverage.remap (indices)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400135 self.SequenceCount = len (self.Sequence)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400136 return bool (self.SequenceCount)
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.AlternateSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400141def closure_glyphs (self, s, cur_glyphs=None):
142 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400143 if self.Format == 1:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400144 s.glyphs.update (*(vlist for g,vlist in self.alternates.iteritems() if g in cur_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.AlternateSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400149def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400150 if self.Format == 1:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400151 self.alternates = {g:vlist for g,vlist in self.alternates.iteritems()
Behdad Esfahbod14374262013-08-08 22:26:49 -0400152 if g in s.glyphs and all (v in s.glyphs for v in vlist)}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400153 return bool (self.alternates)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400154 else:
155 assert 0, "unknown format: %s" % self.Format
156
157@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400158def closure_glyphs (self, s, cur_glyphs=None):
159 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400160 if self.Format == 1:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400161 s.glyphs.update (*([seq.LigGlyph for seq in seqs if all(c in s.glyphs for c in seq.Component)]
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400162 for g,seqs in self.ligatures.iteritems() if g in cur_glyphs))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400163 else:
164 assert 0, "unknown format: %s" % self.Format
165
166@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400167def subset_glyphs (self, s):
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400168 if self.Format == 1:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400169 self.ligatures = {g:v for g,v in self.ligatures.iteritems() if g in s.glyphs}
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400170 self.ligatures = {g:[seq for seq in seqs
171 if seq.LigGlyph in s.glyphs and
172 all (c in s.glyphs for c in seq.Component)]
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400173 for g,seqs in self.ligatures.iteritems()}
174 self.ligatures = {g:v for g,v in self.ligatures.iteritems() if v}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400175 return bool (self.ligatures)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400176 else:
177 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400178
Behdad Esfahbod54660612013-07-21 18:16:55 -0400179@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400180def closure_glyphs (self, s, cur_glyphs=None):
181 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400182 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400183 indices = self.Coverage.intersect (cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400184 if not indices or \
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400185 not all (c.intersect (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage):
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400186 return
187 s.glyphs.update (self.Substitute[i] for i in indices)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400188 else:
189 assert 0, "unknown format: %s" % self.Format
190
191@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400192def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400193 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400194 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400195 self.Substitute = [self.Substitute[i] for i in indices]
Behdad Esfahbod14374262013-08-08 22:26:49 -0400196 # Now drop rules generating glyphs we don't want
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400197 indices = [i for i,sub in enumerate (self.Substitute)
Behdad Esfahbod14374262013-08-08 22:26:49 -0400198 if sub in s.glyphs]
199 self.Substitute = [self.Substitute[i] for i in indices]
200 self.Coverage.remap (indices)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400201 self.GlyphCount = len (self.Substitute)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400202 return bool (self.GlyphCount and all (c.subset (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400203 else:
204 assert 0, "unknown format: %s" % self.Format
205
206@add_method(fontTools.ttLib.tables.otTables.SinglePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400207def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400208 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400209 return len (self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400210 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400211 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400212 self.Value = [self.Value[i] for i in indices]
213 self.ValueCount = len (self.Value)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400214 return bool (self.ValueCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400215 else:
216 assert 0, "unknown format: %s" % self.Format
217
218@add_method(fontTools.ttLib.tables.otTables.PairPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400219def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400220 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400221 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400222 self.PairSet = [self.PairSet[i] for i in indices]
223 for p in self.PairSet:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400224 p.PairValueRecord = [r for r in p.PairValueRecord if r.SecondGlyph in s.glyphs]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400225 p.PairValueCount = len (p.PairValueRecord)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400226 self.PairSet = [p for p in self.PairSet if p.PairValueCount]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400227 self.PairSetCount = len (self.PairSet)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400228 return bool (self.PairSetCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400229 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400230 class1_map = self.ClassDef1.subset (s.glyphs, remap=True)
231 class2_map = self.ClassDef2.subset (s.glyphs, remap=True)
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -0400232 self.Class1Record = [self.Class1Record[i] for i in class1_map]
233 for c in self.Class1Record:
234 c.Class2Record = [c.Class2Record[i] for i in class2_map]
235 self.Class1Count = len (class1_map)
236 self.Class2Count = len (class2_map)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400237 return bool (self.Class1Count and self.Class2Count and self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400238 else:
239 assert 0, "unknown format: %s" % self.Format
240
241@add_method(fontTools.ttLib.tables.otTables.CursivePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400242def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400243 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400244 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400245 self.EntryExitRecord = [self.EntryExitRecord[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400246 self.EntryExitCount = len (self.EntryExitRecord)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400247 return bool (self.EntryExitCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400248 else:
249 assert 0, "unknown format: %s" % self.Format
250
251@add_method(fontTools.ttLib.tables.otTables.MarkBasePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400252def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400253 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400254 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400255 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
256 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400257 base_indices = self.BaseCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400258 self.BaseArray.BaseRecord = [self.BaseArray.BaseRecord[i] for i in base_indices]
259 self.BaseArray.BaseCount = len (self.BaseArray.BaseRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400260 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400261 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400262 self.ClassCount = len (class_indices)
263 for m in self.MarkArray.MarkRecord:
264 m.Class = class_indices.index (m.Class)
265 for b in self.BaseArray.BaseRecord:
266 b.BaseAnchor = [b.BaseAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400267 return bool (self.ClassCount and self.MarkArray.MarkCount and self.BaseArray.BaseCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400268 else:
269 assert 0, "unknown format: %s" % self.Format
270
271@add_method(fontTools.ttLib.tables.otTables.MarkLigPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400272def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400273 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400274 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400275 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
276 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400277 ligature_indices = self.LigatureCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400278 self.LigatureArray.LigatureAttach = [self.LigatureArray.LigatureAttach[i] for i in ligature_indices]
279 self.LigatureArray.LigatureCount = len (self.LigatureArray.LigatureAttach)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400280 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400281 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400282 self.ClassCount = len (class_indices)
283 for m in self.MarkArray.MarkRecord:
284 m.Class = class_indices.index (m.Class)
285 for l in self.LigatureArray.LigatureAttach:
286 for c in l.ComponentRecord:
287 c.LigatureAnchor = [c.LigatureAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400288 return bool (self.ClassCount and self.MarkArray.MarkCount and self.LigatureArray.LigatureCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400289 else:
290 assert 0, "unknown format: %s" % self.Format
291
292@add_method(fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400293def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400294 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400295 mark1_indices = self.Mark1Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400296 self.Mark1Array.MarkRecord = [self.Mark1Array.MarkRecord[i] for i in mark1_indices]
297 self.Mark1Array.MarkCount = len (self.Mark1Array.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400298 mark2_indices = self.Mark2Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400299 self.Mark2Array.Mark2Record = [self.Mark2Array.Mark2Record[i] for i in mark2_indices]
300 self.Mark2Array.MarkCount = len (self.Mark2Array.Mark2Record)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400301 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400302 class_indices = unique_sorted (v.Class for v in self.Mark1Array.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400303 self.ClassCount = len (class_indices)
304 for m in self.Mark1Array.MarkRecord:
305 m.Class = class_indices.index (m.Class)
306 for b in self.Mark2Array.Mark2Record:
307 b.Mark2Anchor = [b.Mark2Anchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400308 return bool (self.ClassCount and self.Mark1Array.MarkCount and self.Mark2Array.MarkCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400309 else:
310 assert 0, "unknown format: %s" % self.Format
311
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400312@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400313 fontTools.ttLib.tables.otTables.MultipleSubst,
314 fontTools.ttLib.tables.otTables.AlternateSubst,
315 fontTools.ttLib.tables.otTables.LigatureSubst,
316 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
317 fontTools.ttLib.tables.otTables.SinglePos,
318 fontTools.ttLib.tables.otTables.PairPos,
319 fontTools.ttLib.tables.otTables.CursivePos,
320 fontTools.ttLib.tables.otTables.MarkBasePos,
321 fontTools.ttLib.tables.otTables.MarkLigPos,
322 fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400323def subset_lookups (self, lookup_indices):
324 pass
325
326@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400327 fontTools.ttLib.tables.otTables.MultipleSubst,
328 fontTools.ttLib.tables.otTables.AlternateSubst,
329 fontTools.ttLib.tables.otTables.LigatureSubst,
330 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
331 fontTools.ttLib.tables.otTables.SinglePos,
332 fontTools.ttLib.tables.otTables.PairPos,
333 fontTools.ttLib.tables.otTables.CursivePos,
334 fontTools.ttLib.tables.otTables.MarkBasePos,
335 fontTools.ttLib.tables.otTables.MarkLigPos,
336 fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400337def collect_lookups (self):
338 return []
339
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400340@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
341 fontTools.ttLib.tables.otTables.AlternateSubst,
342 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
343def may_have_non_1to1 (self):
344 return False
345
346@add_method(fontTools.ttLib.tables.otTables.MultipleSubst,
347 fontTools.ttLib.tables.otTables.LigatureSubst,
348 fontTools.ttLib.tables.otTables.ContextSubst,
349 fontTools.ttLib.tables.otTables.ChainContextSubst)
350def may_have_non_1to1 (self):
351 return True
352
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400353@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
354 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
355def __classify_context (self):
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400356
357 class ContextHelper:
358 def __init__ (self, klass, Format):
359 if klass.__name__.endswith ('Subst'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400360 Typ = 'Sub'
361 Type = 'Subst'
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400362 else:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400363 Typ = 'Pos'
364 Type = 'Pos'
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400365 if klass.__name__.startswith ('Chain'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400366 Chain = 'Chain'
367 else:
368 Chain = ''
369 ChainTyp = Chain+Typ
370
371 self.Typ = Typ
372 self.Type = Type
373 self.Chain = Chain
374 self.ChainTyp = ChainTyp
375
376 self.LookupRecord = Type+'LookupRecord'
377
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400378 if Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400379 Coverage = lambda r: r.Coverage
380 ChainCoverage = lambda r: r.Coverage
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400381 ContextData = lambda r: (None,)
382 ChainContextData = lambda r: (None, None, None)
383 RuleData = lambda r: (r.Input,)
384 ChainRuleData = lambda r: (r.Backtrack, r.Input, r.LookAhead)
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400385 SetRuleData = None
386 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400387 elif Format == 2:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400388 Coverage = lambda r: r.Coverage
389 ChainCoverage = lambda r: r.Coverage
Behdad Esfahbode3f20732013-07-24 11:26:43 -0400390 ContextData = lambda r: (r.ClassDef,)
391 ChainContextData = lambda r: (r.LookAheadClassDef, r.InputClassDef, r.BacktrackClassDef)
392 RuleData = lambda r: (r.Class,)
393 ChainRuleData = lambda r: (r.LookAhead, r.Input, r.Backtrack)
394 def SetRuleData (r, d): (r.Class,) = d
395 def ChainSetRuleData (r, d): (r.LookAhead, r.Input, r.Backtrack) = d
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400396 elif Format == 3:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400397 Coverage = lambda r: r.Coverage[0]
398 ChainCoverage = lambda r: r.InputCoverage[0]
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400399 ContextData = None
400 ChainContextData = None
401 RuleData = lambda r: r.Coverage
402 ChainRuleData = lambda r: r.LookAheadCoverage + r.InputCoverage + r.BacktrackCoverage
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400403 SetRuleData = None
404 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400405 else:
406 assert 0, "unknown format: %s" % Format
407
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400408 if Chain:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400409 self.Coverage = ChainCoverage
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400410 self.ContextData = ChainContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400411 self.RuleData = ChainRuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400412 self.SetRuleData = ChainSetRuleData
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400413 else:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400414 self.Coverage = Coverage
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400415 self.ContextData = ContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400416 self.RuleData = RuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400417 self.SetRuleData = SetRuleData
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400418
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400419 if Format == 1:
420 self.Rule = ChainTyp+'Rule'
421 self.RuleCount = ChainTyp+'RuleCount'
422 self.RuleSet = ChainTyp+'RuleSet'
423 self.RuleSetCount = ChainTyp+'RuleSetCount'
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400424 self.Intersect = lambda glyphs, ContextData, RuleData: [RuleData] if RuleData in glyphs else []
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400425 elif Format == 2:
426 self.Rule = ChainTyp+'ClassRule'
427 self.RuleCount = ChainTyp+'ClassRuleCount'
428 self.RuleSet = ChainTyp+'ClassSet'
429 self.RuleSetCount = ChainTyp+'ClassSetCount'
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400430 self.Intersect = lambda glyphs, ContextData, RuleData: ContextData.intersect_class (glyphs, RuleData)
Behdad Esfahbod89987002013-07-23 23:07:42 -0400431
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400432 self.ClassDef = 'InputClassDef' if Chain else 'ClassDef'
Behdad Esfahbod27108392013-07-23 16:40:47 -0400433
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400434 if self.Format not in [1, 2, 3]:
435 return None # Don't shoot the messenger; let it go
436 if not hasattr (self.__class__, "__ContextHelpers"):
437 self.__class__.__ContextHelpers = {}
438 if self.Format not in self.__class__.__ContextHelpers:
439 self.__class__.__ContextHelpers[self.Format] = ContextHelper (self.__class__, self.Format)
440 return self.__class__.__ContextHelpers[self.Format]
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400441
Behdad Esfahbodf2b6d9c2013-07-23 17:31:54 -0400442@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400443def closure_glyphs (self, s, cur_glyphs=None):
444 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400445 c = self.__classify_context ()
446
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400447 indices = c.Coverage (self).intersect (s.glyphs)
448 if not indices:
449 return []
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400450 cur_glyphs = c.Coverage (self).intersect_glyphs (s.glyphs);
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400451
Behdad Esfahbod00776972013-07-23 15:33:00 -0400452 if self.Format == 1:
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400453 ContextData = c.ContextData (self)
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400454 rss = getattr (self, c.RuleSet)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400455 for i in indices:
456 if not rss[i]: continue
457 for r in getattr (rss[i], c.Rule):
458 if not r: continue
459 if all (all (c.Intersect (s.glyphs, cd, k) for k in klist)
460 for cd,klist in zip (ContextData, c.RuleData (r))):
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400461 chaos = False
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400462 for ll in getattr (r, c.LookupRecord):
463 if not ll: continue
464 seqi = ll.SequenceIndex
465 if seqi == 0:
466 pos_glyphs = set (c.Coverage (self).glyphs[i])
467 else:
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400468 if chaos:
469 pos_glyphs = s.glyphs
470 else:
471 pos_glyphs = set (r.Input[seqi - 1])
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400472 lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400473 chaos = chaos or lookup.may_have_non_1to1 ()
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400474 lookup.closure_glyphs (s, cur_glyphs=pos_glyphs)
Behdad Esfahbod00776972013-07-23 15:33:00 -0400475 elif self.Format == 2:
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400476 ClassDef = getattr (self, c.ClassDef)
477 indices = ClassDef.intersect (cur_glyphs)
478 ContextData = c.ContextData (self)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400479 rss = getattr (self, c.RuleSet)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400480 for i in indices:
481 if not rss[i]: continue
482 for r in getattr (rss[i], c.Rule):
483 if not r: continue
484 if all (all (c.Intersect (s.glyphs, cd, k) for k in klist)
485 for cd,klist in zip (ContextData, c.RuleData (r))):
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400486 chaos = False
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400487 for ll in getattr (r, c.LookupRecord):
488 if not ll: continue
489 seqi = ll.SequenceIndex
490 if seqi == 0:
491 pos_glyphs = ClassDef.intersect_class (cur_glyphs, i)
492 else:
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400493 if chaos:
494 pos_glyphs = s.glyphs
495 else:
496 pos_glyphs = ClassDef.intersect_class (s.glyphs, r.Input[seqi - 1])
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400497 lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400498 chaos = chaos or lookup.may_have_non_1to1 ()
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400499 lookup.closure_glyphs (s, cur_glyphs=pos_glyphs)
Behdad Esfahbod00776972013-07-23 15:33:00 -0400500 elif self.Format == 3:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400501 if not all (x.intersect (s.glyphs) for x in c.RuleData (self)):
Behdad Esfahbod00776972013-07-23 15:33:00 -0400502 return []
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400503 r = self
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400504 chaos = False
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400505 for ll in getattr (r, c.LookupRecord):
506 if not ll: continue
507 seqi = ll.SequenceIndex
508 if seqi == 0:
509 pos_glyphs = cur_glyphs
510 else:
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400511 if chaos:
512 pos_glyphs = s.glyphs
513 else:
514 pos_glyphs = r.InputCoverage[seqi].intersect_glyphs (s.glyphs)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400515 lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400516 chaos = chaos or lookup.may_have_non_1to1 ()
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400517 lookup.closure_glyphs (s, cur_glyphs=pos_glyphs)
Behdad Esfahbod00776972013-07-23 15:33:00 -0400518 else:
519 assert 0, "unknown format: %s" % self.Format
520
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400521@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ContextPos,
522 fontTools.ttLib.tables.otTables.ChainContextSubst, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400523def subset_glyphs (self, s):
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400524 c = self.__classify_context ()
525
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400526 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400527 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400528 rss = getattr (self, c.RuleSet)
529 rss = [rss[i] for i in indices]
530 for rs in rss:
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400531 if not rs: continue
532 ss = getattr (rs, c.Rule)
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400533 ss = [r for r in ss
534 if r and all (all (g in s.glyphs for g in glist)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400535 for glist in c.RuleData (r))]
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400536 setattr (rs, c.Rule, ss)
537 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400538 # Prune empty subrulesets
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400539 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400540 setattr (self, c.RuleSet, rss)
541 setattr (self, c.RuleSetCount, len (rss))
542 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400543 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400544 if not self.Coverage.subset (s.glyphs):
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400545 return False
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400546 indices = getattr (self, c.ClassDef).subset (self.Coverage.glyphs, remap=False)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400547 rss = getattr (self, c.RuleSet)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400548 rss = [rss[i] for i in indices]
549 ContextData = c.ContextData (self)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400550 klass_maps = [x.subset (s.glyphs, remap=True) for x in ContextData]
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400551 for rs in rss:
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400552 if not rs: continue
553 ss = getattr (rs, c.Rule)
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400554 ss = [r for r in ss
555 if r and all (all (k in klass_map for k in klist)
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400556 for klass_map,klist in zip (klass_maps, c.RuleData (r)))]
557 setattr (rs, c.Rule, ss)
558 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400559
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400560 # Remap rule classes
561 for r in ss:
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400562 c.SetRuleData (r, [[klass_map.index (k) for k in klist]
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400563 for klass_map,klist in zip (klass_maps, c.RuleData (r))])
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400564 # Prune empty subrulesets
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400565 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
566 setattr (self, c.RuleSet, rss)
567 setattr (self, c.RuleSetCount, len (rss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400568 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400569 elif self.Format == 3:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400570 return all (x.subset (s.glyphs) for x in c.RuleData (self))
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400571 else:
572 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400573
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400574@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
575 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400576def subset_lookups (self, lookup_indices):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400577 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400578
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400579 if self.Format in [1, 2]:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400580 for rs in getattr (self, c.RuleSet):
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400581 if not rs: continue
582 for r in getattr (rs, c.Rule):
583 if not r: continue
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400584 setattr (r, c.LookupRecord, [ll for ll in getattr (r, c.LookupRecord) if ll
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400585 if ll.LookupListIndex in lookup_indices])
586 for ll in getattr (r, c.LookupRecord):
587 if not ll: continue
588 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400589 elif self.Format == 3:
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400590 setattr (self, c.LookupRecord, [ll for ll in getattr (self, c.LookupRecord) if ll
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400591 if ll.LookupListIndex in lookup_indices])
592 for ll in getattr (self, c.LookupRecord):
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400593 if not ll: continue
594 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400595 else:
596 assert 0, "unknown format: %s" % self.Format
597
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400598@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
599 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400600def collect_lookups (self):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400601 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400602
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400603 if self.Format in [1, 2]:
Behdad Esfahbod27108392013-07-23 16:40:47 -0400604 return [ll.LookupListIndex \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400605 for rs in getattr (self, c.RuleSet) if rs \
606 for r in getattr (rs, c.Rule) if r \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400607 for ll in getattr (r, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400608 elif self.Format == 3:
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400609 return [ll.LookupListIndex \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400610 for ll in getattr (self, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400611 else:
612 assert 0, "unknown format: %s" % self.Format
613
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400614@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400615def closure_glyphs (self, s, cur_glyphs=None):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400616 if self.Format == 1:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400617 self.ExtSubTable.closure_glyphs (s, cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400618 else:
619 assert 0, "unknown format: %s" % self.Format
620
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400621@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
622def may_have_non_1to1 (self):
623 if self.Format == 1:
624 return self.ExtSubTable.may_have_non_1to1 ()
625 else:
626 assert 0, "unknown format: %s" % self.Format
627
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400628@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400629def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400630 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400631 return self.ExtSubTable.subset_glyphs (s)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400632 else:
633 assert 0, "unknown format: %s" % self.Format
634
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400635@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
636def subset_lookups (self, lookup_indices):
637 if self.Format == 1:
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400638 return self.ExtSubTable.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400639 else:
640 assert 0, "unknown format: %s" % self.Format
641
642@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
643def collect_lookups (self):
644 if self.Format == 1:
645 return self.ExtSubTable.collect_lookups ()
646 else:
647 assert 0, "unknown format: %s" % self.Format
648
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400649@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400650def closure_glyphs (self, s, cur_glyphs=None):
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400651 for st in self.SubTable:
652 if not st: continue
653 st.closure_glyphs (s, cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400654
655@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400656def subset_glyphs (self, s):
657 self.SubTable = [st for st in self.SubTable if st and st.subset_glyphs (s)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400658 self.SubTableCount = len (self.SubTable)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400659 return bool (self.SubTableCount)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400660
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400661@add_method(fontTools.ttLib.tables.otTables.Lookup)
662def subset_lookups (self, lookup_indices):
663 for s in self.SubTable:
664 s.subset_lookups (lookup_indices)
665
666@add_method(fontTools.ttLib.tables.otTables.Lookup)
667def collect_lookups (self):
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400668 return unique_sorted (sum ((st.collect_lookups () for st in self.SubTable if st), []))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400669
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400670@add_method(fontTools.ttLib.tables.otTables.Lookup)
671def may_have_non_1to1 (self):
672 return any (st.may_have_non_1to1 () for st in self.SubTable if st)
673
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400674@add_method(fontTools.ttLib.tables.otTables.LookupList)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400675def subset_glyphs (self, s):
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400676 "Returns the indices of nonempty lookups."
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400677 return [i for (i,l) in enumerate (self.Lookup) if l and l.subset_glyphs (s)]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400678
679@add_method(fontTools.ttLib.tables.otTables.LookupList)
680def subset_lookups (self, lookup_indices):
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400681 self.Lookup = [self.Lookup[i] for i in lookup_indices if i < self.LookupCount]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400682 self.LookupCount = len (self.Lookup)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400683 for l in self.Lookup:
684 l.subset_lookups (lookup_indices)
685
686@add_method(fontTools.ttLib.tables.otTables.LookupList)
687def closure_lookups (self, lookup_indices):
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400688 lookup_indices = unique_sorted (lookup_indices)
689 recurse = lookup_indices
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400690 while True:
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400691 recurse_lookups = sum ((self.Lookup[i].collect_lookups () for i in recurse if i < self.LookupCount), [])
692 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 -0400693 if not recurse_lookups:
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400694 return unique_sorted (lookup_indices)
695 recurse_lookups = unique_sorted (recurse_lookups)
696 lookup_indices.extend (recurse_lookups)
697 recurse = recurse_lookups
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400698
699@add_method(fontTools.ttLib.tables.otTables.Feature)
700def subset_lookups (self, lookup_indices):
701 self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices]
702 # Now map them.
703 self.LookupListIndex = [lookup_indices.index (l) for l in self.LookupListIndex]
704 self.LookupCount = len (self.LookupListIndex)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400705 return self.LookupCount
Behdad Esfahbod54660612013-07-21 18:16:55 -0400706
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400707@add_method(fontTools.ttLib.tables.otTables.Feature)
708def collect_lookups (self):
709 return self.LookupListIndex[:]
710
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400711@add_method(fontTools.ttLib.tables.otTables.FeatureList)
712def subset_lookups (self, lookup_indices):
713 "Returns the indices of nonempty features."
714 feature_indices = [i for (i,f) in enumerate (self.FeatureRecord) if f.Feature.subset_lookups (lookup_indices)]
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400715 self.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400716 return feature_indices
717
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400718@add_method(fontTools.ttLib.tables.otTables.FeatureList)
719def collect_lookups (self, feature_indices):
720 return unique_sorted (sum ((self.FeatureRecord[i].Feature.collect_lookups () for i in feature_indices
721 if i < self.FeatureCount), []))
722
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400723@add_method(fontTools.ttLib.tables.otTables.FeatureList)
724def subset_features (self, feature_indices):
725 self.FeatureRecord = [self.FeatureRecord[i] for i in feature_indices]
726 self.FeatureCount = len (self.FeatureRecord)
727 return bool (self.FeatureCount)
728
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400729@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
730def subset_features (self, feature_indices):
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400731 if self.ReqFeatureIndex in feature_indices:
732 self.ReqFeatureIndex = feature_indices.index (self.ReqFeatureIndex)
733 else:
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400734 self.ReqFeatureIndex = 65535
735 self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400736 # Now map them.
737 self.FeatureIndex = [feature_indices.index (f) for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400738 self.FeatureCount = len (self.FeatureIndex)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400739 return bool (self.FeatureCount or self.ReqFeatureIndex != 65535)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400740
741@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
742def collect_features (self):
743 feature_indices = self.FeatureIndex[:]
744 if self.ReqFeatureIndex != 65535:
745 feature_indices.append (self.ReqFeatureIndex)
746 return unique_sorted (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400747
748@add_method(fontTools.ttLib.tables.otTables.Script)
749def subset_features (self, feature_indices):
750 if self.DefaultLangSys and not self.DefaultLangSys.subset_features (feature_indices):
751 self.DefaultLangSys = None
752 self.LangSysRecord = [l for l in self.LangSysRecord if l.LangSys.subset_features (feature_indices)]
753 self.LangSysCount = len (self.LangSysRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400754 return bool (self.LangSysCount or self.DefaultLangSys)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400755
756@add_method(fontTools.ttLib.tables.otTables.Script)
757def collect_features (self):
Behdad Esfahbod2307c8b2013-07-23 11:18:13 -0400758 feature_indices = [l.LangSys.collect_features () for l in self.LangSysRecord]
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400759 if self.DefaultLangSys:
760 feature_indices.append (self.DefaultLangSys.collect_features ())
761 return unique_sorted (sum (feature_indices, []))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400762
763@add_method(fontTools.ttLib.tables.otTables.ScriptList)
764def subset_features (self, feature_indices):
765 self.ScriptRecord = [s for s in self.ScriptRecord if s.Script.subset_features (feature_indices)]
766 self.ScriptCount = len (self.ScriptRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400767 return bool (self.ScriptCount)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400768
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400769@add_method(fontTools.ttLib.tables.otTables.ScriptList)
770def collect_features (self):
771 return unique_sorted (sum ((s.Script.collect_features () for s in self.ScriptRecord), []))
772
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400773@add_method(fontTools.ttLib.getTableClass('GSUB'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400774def closure_glyphs (self, s):
775 s.table = self.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400776 feature_indices = self.table.ScriptList.collect_features ()
777 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400778 while True:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400779 orig_glyphs = s.glyphs.copy ()
780 for i in lookup_indices:
781 if i >= self.table.LookupList.LookupCount: continue
782 if not self.table.LookupList.Lookup[i]: continue
783 self.table.LookupList.Lookup[i].closure_glyphs (s)
784 if orig_glyphs == s.glyphs:
785 break
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400786 del s.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400787
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400788@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400789def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400790 s.glyphs = s.glyphs_gsubed
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400791 lookup_indices = self.table.LookupList.subset_glyphs (s)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400792 self.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400793 self.prune_lookups ()
794 return True
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400795
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400796@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400797def subset_lookups (self, lookup_indices):
798 "Retrains specified lookups, then removes empty features, language systems, and scripts."
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400799 self.table.LookupList.subset_lookups (lookup_indices)
800 feature_indices = self.table.FeatureList.subset_lookups (lookup_indices)
801 self.table.ScriptList.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400802
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400803@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
804def prune_lookups (self):
805 "Remove unreferenced lookups"
806 feature_indices = self.table.ScriptList.collect_features ()
807 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
808 lookup_indices = self.table.LookupList.closure_lookups (lookup_indices)
809 self.subset_lookups (lookup_indices)
810
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400811@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
812def subset_feature_tags (self, feature_tags):
813 feature_indices = [i for (i,f) in enumerate (self.table.FeatureList.FeatureRecord) if f.FeatureTag in feature_tags]
814 self.table.FeatureList.subset_features (feature_indices)
815 self.table.ScriptList.subset_features (feature_indices)
816
817@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400818def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400819 if options.layout_features and '*' not in options.layout_features:
820 self.subset_feature_tags (options.layout_features)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400821 self.prune_lookups ()
822 return True
823
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400824@add_method(fontTools.ttLib.getTableClass('GDEF'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400825def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400826 glyphs = s.glyphs_gsubed
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400827 table = self.table
828 if table.LigCaretList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400829 indices = table.LigCaretList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400830 table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i] for i in indices]
831 table.LigCaretList.LigGlyphCount = len (table.LigCaretList.LigGlyph)
832 if not table.LigCaretList.LigGlyphCount:
833 table.LigCaretList = None
834 if table.MarkAttachClassDef:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400835 table.MarkAttachClassDef.classDefs = {g:v for g,v in table.MarkAttachClassDef.classDefs.iteritems() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400836 if not table.MarkAttachClassDef.classDefs:
837 table.MarkAttachClassDef = None
838 if table.GlyphClassDef:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400839 table.GlyphClassDef.classDefs = {g:v for g,v in table.GlyphClassDef.classDefs.iteritems() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400840 if not table.GlyphClassDef.classDefs:
841 table.GlyphClassDef = None
842 if table.AttachList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400843 indices = table.AttachList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400844 table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i] for i in indices]
845 table.AttachList.GlyphCount = len (table.AttachList.AttachPoint)
846 if not table.AttachList.GlyphCount:
847 table.AttachList = None
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400848 return bool (table.LigCaretList or table.MarkAttachClassDef or table.GlyphClassDef or table.AttachList)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400849
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400850@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbodd4e33a72013-07-24 18:51:05 -0400851def prune_pre_subset (self, options):
852 # Prune unknown kern table types
853 self.kernTables = [t for t in self.kernTables if hasattr (t, 'kernTable')]
854 return bool (self.kernTables)
855
856@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400857def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400858 glyphs = s.glyphs_gsubed
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400859 for t in self.kernTables:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400860 t.kernTable = {(a,b):v for ((a,b),v) in t.kernTable.iteritems() if a in glyphs and b in glyphs}
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400861 self.kernTables = [t for t in self.kernTables if t.kernTable]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400862 return bool (self.kernTables)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400863
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400864@add_method(fontTools.ttLib.getTableClass('hmtx'), fontTools.ttLib.getTableClass('vmtx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400865def subset_glyphs (self, s):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400866 self.metrics = {g:v for g,v in self.metrics.iteritems() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400867 return bool (self.metrics)
Behdad Esfahbodc7160442013-07-22 14:29:08 -0400868
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400869@add_method(fontTools.ttLib.getTableClass('hdmx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400870def subset_glyphs (self, s):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400871 self.hdmx = {sz:{g:v for g,v in l.iteritems() if g in s.glyphs} for (sz,l) in self.hdmx.iteritems()}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400872 return bool (self.hdmx)
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400873
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400874@add_method(fontTools.ttLib.getTableClass('VORG'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400875def subset_glyphs (self, s):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400876 self.VOriginRecords = {g:v for g,v in self.VOriginRecords.iteritems() if g in s.glyphs}
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400877 self.numVertOriginYMetrics = len (self.VOriginRecords)
878 return True # Never drop; has default metrics
879
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400880@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400881def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400882 if not options.glyph_names:
Behdad Esfahbod42648242013-07-23 12:56:06 -0400883 self.formatType = 3.0
884 return True
885
886@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400887def subset_glyphs (self, s):
Behdad Esfahbod42648242013-07-23 12:56:06 -0400888 self.extraNames = [] # This seems to do it
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -0400889 return True
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400890
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400891# Copied from _g_l_y_f.py
892ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes
893ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points
894ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true
895WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0
896NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!)
897MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one
898WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy
899WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11
900WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow
901USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph
902OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts
903SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple)
904UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS)
905
906@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
907def getComponentNamesFast (self, glyfTable):
908 if struct.unpack(">h", self.data[:2])[0] >= 0:
909 return [] # Not composite
910 data = self.data
911 i = 10
912 components = []
913 more = 1
914 while more:
915 flags, glyphID = struct.unpack(">HH", data[i:i+4])
916 i += 4
917 flags = int(flags)
918 components.append (glyfTable.getGlyphName (int (glyphID)))
919
920 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
921 else: i += 2
922 if flags & WE_HAVE_A_SCALE: i += 2
923 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
924 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
925 more = flags & MORE_COMPONENTS
926 return components
927
928@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
929def remapComponentsFast (self, indices):
930 if struct.unpack(">h", self.data[:2])[0] >= 0:
931 return # Not composite
932 data = bytearray (self.data)
933 i = 10
934 more = 1
935 while more:
936 flags = (data[i] << 8) | data[i+1]
937 glyphID = (data[i+2] << 8) | data[i+3]
938 # Remap
939 glyphID = indices.index (glyphID)
940 data[i+2] = glyphID >> 8
941 data[i+3] = glyphID & 0xFF
942 i += 4
943 flags = int(flags)
944
945 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
946 else: i += 2
947 if flags & WE_HAVE_A_SCALE: i += 2
948 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
949 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
950 more = flags & MORE_COMPONENTS
951 self.data = str (data)
952
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400953@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
954def dropInstructionsFast (self):
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400955 numContours = struct.unpack(">h", self.data[:2])[0]
956 data = bytearray (self.data)
957 i = 10
958 if numContours >= 0:
959 i += 2 * numContours # endPtsOfContours
960 instructionLen = (data[i] << 8) | data[i+1]
961 # Zero it
962 data[i] = data [i+1] = 0
963 i += 2
Behdad Esfahbod0fb69882013-07-24 17:25:35 -0400964 if instructionLen:
965 # Splice it out
966 data = data[:i] + data[i+instructionLen:]
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400967 else:
968 more = 1
969 while more:
970 flags = (data[i] << 8) | data[i+1]
971 # Turn instruction flag off
972 flags &= ~WE_HAVE_INSTRUCTIONS
973 data[i+0] = flags >> 8
974 data[i+1] = flags & 0xFF
975 i += 4
976 flags = int(flags)
977
978 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
979 else: i += 2
980 if flags & WE_HAVE_A_SCALE: i += 2
981 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
982 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
983 more = flags & MORE_COMPONENTS
984 # Cut off
985 data = data[:i]
986 if len(data) % 4:
987 # add pad bytes
988 nPadBytes = 4 - (len(data) % 4)
989 for i in range (nPadBytes):
990 data.append (0)
991 self.data = str (data)
992
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400993@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400994def closure_glyphs (self, s):
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400995 decompose = s.glyphs
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400996 # I don't know if component glyphs can be composite themselves.
997 # We handle them anyway.
998 while True:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400999 components = set ()
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001000 for g in decompose:
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001001 if g not in self.glyphs:
Behdad Esfahbodf8c20e42013-07-23 23:13:23 -04001002 continue
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001003 gl = self.glyphs[g]
1004 if hasattr (gl, "data"):
1005 for c in gl.getComponentNamesFast (self):
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001006 if c not in s.glyphs:
1007 components.add (c)
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001008 else:
1009 # TTX seems to expand gid0..3 always
1010 if gl.isComposite ():
1011 for c in gl.components:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001012 if c.glyphName not in s.glyphs:
1013 components.add (c.glyphName)
1014 components = set (c for c in components if c not in s.glyphs)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001015 if not components:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001016 break
1017 decompose = components
1018 s.glyphs.update (components)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001019
1020@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001021def subset_glyphs (self, s):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001022 self.glyphs = {g:v for g,v in self.glyphs.iteritems() if g in s.glyphs}
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001023 indices = [i for i,g in enumerate (self.glyphOrder) if g in s.glyphs]
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001024 for v in self.glyphs.itervalues():
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001025 if hasattr (v, "data"):
1026 v.remapComponentsFast (indices)
1027 else:
1028 pass # No need
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001029 self.glyphOrder = [g for g in self.glyphOrder if g in s.glyphs]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -04001030 return bool (self.glyphs)
Behdad Esfahbod861d9152013-07-22 16:47:24 -04001031
Behdad Esfahboded98c612013-07-23 12:37:41 -04001032@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -04001033def prune_post_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001034 if not options.hinting:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001035 for v in self.glyphs.itervalues():
Behdad Esfahbod6ec88542013-07-24 16:52:47 -04001036 if hasattr (v, "data"):
1037 v.dropInstructionsFast ()
1038 else:
1039 v.program = fontTools.ttLib.tables.ttProgram.Program()
1040 v.program.fromBytecode([])
Behdad Esfahboded98c612013-07-23 12:37:41 -04001041 return True
1042
Behdad Esfahbod2b677c82013-07-23 13:37:13 -04001043@add_method(fontTools.ttLib.getTableClass('CFF '))
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001044def prune_pre_subset (self, s):
Behdad Esfahbod4e721862013-08-13 16:24:45 -04001045 cff = self.cff
1046 # CFF table should have one font only
1047 cff.fontNames = cff.fontNames[:1]
1048 return bool (cff.fontNames)
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001049
1050@add_method(fontTools.ttLib.getTableClass('CFF '))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001051def subset_glyphs (self, s):
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001052 cff = self.cff
1053 for fontname in cff.keys():
1054 font = cff[fontname]
1055 cs = font.CharStrings
1056 if cs.charStringsAreIndexed:
1057 indices = [i for i,g in enumerate (font.charset) if g in s.glyphs]
1058 # Load all glyphs
1059 for g in font.charset:
1060 if g not in s.glyphs: continue
1061 cs.getItemAndSelector (g)
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001062 csi = cs.charStringsIndex
1063 csi.items = [csi.items[i] for i in indices]
1064 csi.offsets = [] # Don't need it; loaded all glyphs
Behdad Esfahbod31ebebe2013-08-13 16:02:33 -04001065 if hasattr (font, "FDSelect"):
Behdad Esfahbod8e3b8862013-08-13 16:02:18 -04001066 sel = font.FDSelect
1067 sel.format = None
1068 sel.gidArray = [font.FDSelect.gidArray[i] for i in indices]
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001069 cs.charStrings = {g:indices.index (v) for g,v in cs.charStrings.iteritems() if g in s.glyphs}
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001070 else:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001071 cs.charStrings = {g:v for g,v in cs.charStrings.iteritems() if g in s.glyphs}
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001072 font.charset = [g for g in font.charset if g in s.glyphs]
1073 font.numGlyphs = len (font.charset)
Behdad Esfahbod409286a2013-08-13 15:57:33 -04001074 return any (cff[fontname].numGlyphs for fontname in cff.keys())
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001075
1076@add_method(fontTools.ttLib.getTableClass('glyf'))
1077def prune_post_subset (self, options):
1078 if not options.hinting:
1079 pass # Drop hints
1080 return True
Behdad Esfahbod2b677c82013-07-23 13:37:13 -04001081
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001082@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001083def closure_glyphs (self, s):
1084 tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [1, 10]]
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001085 for u in s.unicodes_requested:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001086 found = False
1087 for table in tables:
1088 if u in table.cmap:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001089 s.glyphs.add (table.cmap[u])
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001090 found = True
1091 break
1092 if not found:
1093 s.log ("No glyph for Unicode value %s; skipping." % u)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001094
1095@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001096def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001097 if not options.legacy_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -04001098 # Drop non-Unicode / non-Symbol cmaps
1099 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 -04001100 if not options.symbol_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -04001101 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 -04001102 # TODO Only keep one subtable?
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001103 # For now, drop format=0 which can't be subset_glyphs easily?
1104 self.tables = [t for t in self.tables if t.format != 0]
1105 return bool (self.tables)
1106
1107@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001108def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -04001109 s.glyphs = s.glyphs_cmaped
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001110 for t in self.tables:
Behdad Esfahbod9453a362013-07-22 16:21:24 -04001111 # For reasons I don't understand I need this here
1112 # to force decompilation of the cmap format 14.
1113 try:
1114 getattr (t, "asdf")
1115 except AttributeError:
1116 pass
Behdad Esfahbodb13d7902013-07-22 16:01:15 -04001117 if t.format == 14:
Behdad Esfahbod9453a362013-07-22 16:21:24 -04001118 # XXX We drop all the default-UVS mappings (g==None)
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001119 t.uvsDict = {v:[(u,g) for (u,g) in l if g in s.glyphs] for (v,l) in t.uvsDict.iteritems()}
1120 t.uvsDict = {v:l for (v,l) in t.uvsDict.iteritems() if l}
Behdad Esfahbodb13d7902013-07-22 16:01:15 -04001121 else:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001122 t.cmap = {u:g for (u,g) in t.cmap.iteritems() if g in s.glyphs_requested or u in s.unicodes_requested}
Behdad Esfahbodb13d7902013-07-22 16:01:15 -04001123 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 -04001124 # XXX Convert formats when needed
Behdad Esfahbod2ac36302013-08-08 23:49:00 -04001125 # In particular, if we have a format=12 without non-BMP
1126 # characters, either drop format=12 one or convert it
1127 # to format=4 if there's not one.
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001128 return bool (self.tables)
1129
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001130@add_method(fontTools.ttLib.getTableClass('name'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -04001131def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001132 if '*' not in options.name_IDs:
1133 self.names = [n for n in self.names if n.nameID in options.name_IDs]
1134 if not options.name_legacy:
Behdad Esfahbod20faeb02013-07-23 13:19:03 -04001135 self.names = [n for n in self.names if n.platformID == 3 and n.platEncID == 1]
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001136 if '*' not in options.name_languages:
1137 self.names = [n for n in self.names if n.langID in options.name_languages]
Behdad Esfahbod20faeb02013-07-23 13:19:03 -04001138 return True # Retain even if empty
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001139
Behdad Esfahbod8c646f62013-07-22 15:06:23 -04001140
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -04001141# TODO OS/2 ulUnicodeRange / ulCodePageRange?
Behdad Esfahbodf71267b2013-07-23 12:59:13 -04001142# TODO Drop unneeded GSUB/GPOS Script/LangSys entries
Behdad Esfahbod398d3892013-07-23 15:29:40 -04001143# TODO Avoid recursing too much
Behdad Esfahbode94aa0e2013-07-23 13:22:04 -04001144# TODO Text direction considerations
1145# TODO Text script / language considerations
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001146# TODO Drop unknown tables? Using DefaultTable.prune?
Behdad Esfahbod8c4f7cc2013-07-24 17:58:29 -04001147# TODO Drop GPOS Device records if not hinting?
Behdad Esfahbod93e26362013-08-09 14:22:48 -04001148# TODO Move font name loading hack to Subsetter?
Behdad Esfahbod56ebd042013-07-22 13:02:24 -04001149
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001150
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001151class Subsetter:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001152
1153 class Options:
Behdad Esfahbod26d9ee72013-08-13 16:55:01 -04001154
1155 class UnknownOptionError (Exception):
1156 pass
1157
Behdad Esfahbod9eeeb4e2013-08-13 16:58:50 -04001158 drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'PCLT', 'LTSH']
1159 drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill'] # Graphite
1160 drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL'] # Color
1161 no_subset_tables_default = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2', 'loca', 'name', 'cvt ', 'fpgm', 'prep']
1162 hinting_tables_default = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
1163
1164 # Based on HarfBuzz shapers
1165 layout_features_groups = {
1166 # Default shaper
1167 'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
1168 'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
1169 'vertical': ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
1170 'ltr': ['ltra', 'ltrm'],
1171 'rtl': ['rtla', 'rtlm'],
1172 # Complex shapers
1173 'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3', 'cswh', 'mset'],
1174 'hangul': ['ljmo', 'vjmo', 'tjmo'],
1175 'tibetal': ['abvs', 'blws', 'abvm', 'blwm'],
1176 'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half', 'abvf', 'pstf', 'cfar', 'vatu', 'cjct',
1177 'init', 'pres', 'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
1178 }
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001179 layout_features_default = unique_sorted (sum (layout_features_groups.itervalues(), []))
Behdad Esfahbod9eeeb4e2013-08-13 16:58:50 -04001180
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001181 drop_tables = drop_tables_default
Behdad Esfahbode6fc8ca2013-08-13 12:25:31 -04001182 no_subset_tables = no_subset_tables_default
1183 hinting_tables = hinting_tables_default
Behdad Esfahbod9eeeb4e2013-08-13 16:58:50 -04001184 layout_features = layout_features_default
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001185 hinting = False
1186 glyph_names = False
1187 legacy_cmap = False
1188 symbol_cmap = False
1189 name_IDs = [1, 2] # Family and Style
1190 name_legacy = False
1191 name_languages = [0x0409] # English
1192 mandatory_glyphs = True # First four for TrueType, .notdef for CFF
1193 recalc_bboxes = False # Slows us down
1194
1195 def __init__ (self, **kwargs):
1196
1197 self.set (**kwargs)
1198
1199 def set (self, **kwargs):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001200 for k,v in kwargs.iteritems():
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001201 if not hasattr (self, k):
Behdad Esfahbod26d9ee72013-08-13 16:55:01 -04001202 raise self.UnknownOptionError ("Unknown option '%s'" % k)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001203 setattr (self, k, v)
1204
1205 def parse_opts (self, argv, ignore_unknown=False):
1206 ret = []
1207 opts = {}
1208 for a in argv:
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001209 orig_a = a
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001210 if not a.startswith ('--'):
1211 ret.append (a)
1212 continue
1213 a = a[2:]
1214 i = a.find ('=')
1215 if i == -1:
1216 if a.startswith ("no-"):
1217 k = a[3:]
1218 v = False
1219 else:
1220 k = a
1221 v = True
1222 else:
1223 k = a[:i]
1224 v = a[i+1:]
1225 k = k.replace ('-', '_')
1226 if not hasattr (self, k):
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001227 if ignore_unknown == True or k in ignore_unknown:
1228 ret.append (orig_a)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001229 continue
1230 else:
Behdad Esfahbod26d9ee72013-08-13 16:55:01 -04001231 raise self.UnknownOptionError ("Unknown option '%s'" % a)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001232
1233 ov = getattr (self, k)
1234 if isinstance (ov, bool):
1235 v = bool (v)
1236 elif isinstance (ov, int):
1237 v = int (v)
1238 elif isinstance (ov, list):
1239 v = v.split (',')
1240 v = [int (x, 0) if x[0] in range (10) else x for x in v]
1241
1242 opts[k] = v
1243 self.set (**opts)
1244
1245 return ret
1246
1247
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001248 def __init__ (self, options=None, log=None):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001249
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001250 if not log:
1251 log = Logger()
1252 if not options:
1253 options = Options()
1254
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001255 self.options = options
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001256 self.log = log
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001257 self.unicodes_requested = set ()
1258 self.glyphs_requested = set ()
Behdad Esfahboda7d22432013-08-13 12:47:48 -04001259 self.glyphs = set ()
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001260
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001261 def populate (self, glyphs=[], unicodes=[], text=""):
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001262 self.unicodes_requested.update (unicodes)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001263 if isinstance (text, str):
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001264 text = text.decode ("utf8")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001265 for u in text:
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001266 self.unicodes_requested.add (ord (u))
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001267 self.glyphs_requested.update (glyphs)
Behdad Esfahboda7d22432013-08-13 12:47:48 -04001268 self.glyphs.update (glyphs)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001269
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001270 def pre_prune (self, font):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001271
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001272 for tag in font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001273 if tag == 'GlyphOrder': continue
1274
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001275 if tag in self.options.drop_tables or \
Behdad Esfahbode6fc8ca2013-08-13 12:25:31 -04001276 (tag in self.options.hinting_tables and not self.options.hinting):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001277 self.log (tag, "dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001278 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001279 continue
1280
1281 clazz = fontTools.ttLib.getTableClass(tag)
1282
1283 if hasattr (clazz, 'prune_pre_subset'):
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001284 table = font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001285 retain = table.prune_pre_subset (self.options)
1286 self.log.lapse ("prune '%s'" % tag)
1287 if not retain:
1288 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001289 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001290 continue
1291 else:
1292 self.log (tag, "pruned")
1293
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001294 def closure_glyphs (self, font):
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001295
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001296 self.glyphs = self.glyphs_requested.copy ()
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001297
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001298 if 'cmap' in font:
1299 font['cmap'].closure_glyphs (self)
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001300 self.glyphs_cmaped = self.glyphs
1301
1302 if self.options.mandatory_glyphs:
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001303 if 'glyf' in font:
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001304 for i in range (4):
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001305 self.glyphs.add (font.getGlyphName (i))
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001306 self.log ("Added first four glyphs to subset")
1307 else:
1308 self.glyphs.add ('.notdef')
1309 self.log ("Added .notdef glyph to subset")
1310
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001311 if 'GSUB' in font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001312 self.log ("Closing glyph list over 'GSUB': %d glyphs before" % len (self.glyphs))
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001313 self.log.glyphs (self.glyphs, font=font)
1314 font['GSUB'].closure_glyphs (self)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001315 self.log ("Closed glyph list over 'GSUB': %d glyphs after" % len (self.glyphs))
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001316 self.log.glyphs (self.glyphs, font=font)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001317 self.log.lapse ("close glyph list over 'GSUB'")
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001318 self.glyphs_gsubed = self.glyphs.copy ()
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001319
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001320 if 'glyf' in font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001321 self.log ("Closing glyph list over 'glyf': %d glyphs before" % len (self.glyphs))
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001322 self.log.glyphs (self.glyphs, font=font)
1323 font['glyf'].closure_glyphs (self)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001324 self.log ("Closed glyph list over 'glyf': %d glyphs after" % len (self.glyphs))
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001325 self.log.glyphs (self.glyphs, font=font)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001326 self.log.lapse ("close glyph list over 'glyf'")
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001327 self.glyphs_glyfed = self.glyphs.copy ()
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001328
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001329 self.glyphs_all = self.glyphs.copy ()
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001330
1331 self.log ("Retaining %d glyphs: " % len (self.glyphs_all))
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001332
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001333 def subset_glyphs (self, font):
1334 for tag in font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001335 if tag == 'GlyphOrder': continue
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001336 clazz = fontTools.ttLib.getTableClass(tag)
1337
Behdad Esfahbode6fc8ca2013-08-13 12:25:31 -04001338 if tag in self.options.no_subset_tables:
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001339 self.log (tag, "subsetting not needed")
1340 elif hasattr (clazz, 'subset_glyphs'):
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001341 table = font[tag]
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -04001342 self.glyphs = self.glyphs_all
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001343 retain = table.subset_glyphs (self)
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001344 self.glyphs = self.glyphs_all
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001345 self.log.lapse ("subset '%s'" % tag)
1346 if not retain:
1347 self.log (tag, "subsetted to empty; dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001348 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001349 else:
1350 self.log (tag, "subsetted")
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001351 else:
Behdad Esfahbode6fc8ca2013-08-13 12:25:31 -04001352 self.log (tag, "NOT subset; don't know how to subset; dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001353 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001354
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001355 glyphOrder = font.getGlyphOrder()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001356 glyphOrder = [g for g in glyphOrder if g in self.glyphs_all]
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001357 font.setGlyphOrder (glyphOrder)
1358 font._buildReverseGlyphOrderDict ()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001359 self.log.lapse ("subset GlyphOrder")
1360
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001361 def post_prune (self, font):
1362 for tag in font.keys():
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001363 if tag == 'GlyphOrder': continue
1364 clazz = fontTools.ttLib.getTableClass(tag)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001365 if hasattr (clazz, 'prune_post_subset'):
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001366 table = font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001367 retain = table.prune_post_subset (self.options)
1368 self.log.lapse ("prune '%s'" % tag)
1369 if not retain:
1370 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001371 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001372 else:
1373 self.log (tag, "pruned")
1374
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001375 def subset (self, font):
Behdad Esfahbod756af492013-08-01 12:05:26 -04001376
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001377 font.recalcBBoxes = self.options.recalc_bboxes
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001378
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001379 self.pre_prune (font)
1380 self.closure_glyphs (font)
1381 self.subset_glyphs (font)
1382 self.post_prune (font)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001383
Behdad Esfahbod756af492013-08-01 12:05:26 -04001384
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001385import sys, time
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001386
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001387class Logger:
1388
1389 def __init__ (self, verbose=False, xml=False, timing=False):
1390 self.verbose = verbose
1391 self.xml = xml
1392 self.timing = timing
1393 self.last_time = self.start_time = time.time ()
1394
1395 def parse_opts (self, argv):
1396 argv = argv[:]
1397 for v in ['verbose', 'xml', 'timing']:
1398 if "--"+v in argv:
1399 setattr (self, v, True)
1400 argv.remove ("--"+v)
1401 return argv
1402
1403 def __call__ (self, *things):
1404 if not self.verbose:
1405 return
1406 print ' '.join (str (x) for x in things)
1407
1408 def lapse (self, *things):
1409 if not self.timing:
1410 return
1411 new_time = time.time ()
1412 print "Took %0.3fs to %s" % (new_time - self.last_time, ' '.join (str (x) for x in things))
1413 self.last_time = new_time
1414
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001415 def glyphs (self, glyphs, glyph_names=True, font=None):
1416 self ("Names: ", sorted (glyphs))
1417 if font:
Behdad Esfahboddb6d2e92013-08-13 12:42:12 -04001418 reverseGlyphMap = font.getReverseGlyphMap ()
1419 self ("Gids : ", sorted (reverseGlyphMap[g] for g in glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001420
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001421 def font (self, font, file=sys.stdout):
1422 if not self.xml:
1423 return
Behdad Esfahbod9a49ead2013-08-13 16:51:59 -04001424 import xmlWriter
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001425 writer = xmlWriter.XMLWriter (file)
1426 font.disassembleInstructions = False # Work around ttx bug
1427 for tag in font.keys():
1428 writer.begintag (tag)
1429 writer.newline ()
1430 font[tag].toXML(writer, font)
1431 writer.endtag (tag)
1432 writer.newline ()
1433
Behdad Esfahbodf6b668e2013-08-13 12:20:59 -04001434
1435def load_font (fontfile, dont_load_glyph_names=False):
1436
1437 # TODO Option for ignoreDecompileErrors?
1438
1439 font = fontTools.ttx.TTFont (fontfile)
1440
1441 # Hack:
1442 #
1443 # If we don't need glyph names, change 'post' class to not try to
1444 # load them. It avoid lots of headache with broken fonts as well
1445 # as loading time.
1446 #
1447 # Ideally ttLib should provide a way to ask it to skip loading
1448 # glyph names. But it currently doesn't provide such a thing.
1449 #
1450 if dont_load_glyph_names:
1451 post = fontTools.ttLib.getTableClass('post')
1452 saved = post.decode_format_2_0
1453 post.decode_format_2_0 = post.decode_format_3_0
1454 f = font['post']
1455 if f.formatType == 2.0:
1456 f.formatType = 3.0
1457 post.decode_format_2_0 = saved
1458
1459 return font
1460
1461
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001462def main (args):
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001463
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001464 log = Logger ()
1465 args = log.parse_opts (args)
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001466
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001467 options = Subsetter.Options ()
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001468 args = options.parse_opts (args, ignore_unknown=['text'])
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001469
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001470 if len (args) < 2:
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001471 print >>sys.stderr, "usage: pyotlss.py font-file glyph..."
1472 sys.exit (1)
1473
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001474 fontfile = args[0]
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001475 args = args[1:]
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001476
Behdad Esfahbodf6b668e2013-08-13 12:20:59 -04001477 dont_load_glyph_names = not options.glyph_names and \
1478 all (any (g.startswith (p) \
1479 for p in ['gid', 'glyph', 'uni', 'U+']) \
1480 for g in args)
1481
1482 font = load_font (fontfile, dont_load_glyph_names=dont_load_glyph_names)
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001483 subsetter = Subsetter (options=options, log=log)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001484 log.lapse ("load font")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001485
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001486 names = font.getGlyphNames()
1487 log.lapse ("loading glyph names")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001488
1489 glyphs = []
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001490 unicodes = []
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001491 text = ""
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001492 for g in args:
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001493 if g in names:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001494 glyphs.append (g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001495 continue
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001496 if g.startswith ('--text='):
1497 text += g[7:]
1498 continue
Behdad Esfahbod9ae5d282013-08-08 21:18:17 -04001499 if g.startswith ('uni') or g.startswith ('U+'):
1500 if g.startswith ('uni') and len (g) > 3:
1501 g = g[3:]
1502 elif g.startswith ('U+') and len (g) > 2:
1503 g = g[2:]
1504 u = int (g, 16)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001505 unicodes.append (u)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001506 continue
1507 if g.startswith ('gid') or g.startswith ('glyph'):
1508 if g.startswith ('gid') and len (g) > 3:
1509 g = g[3:]
1510 elif g.startswith ('glyph') and len (g) > 5:
1511 g = g[5:]
1512 try:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001513 glyphs.append (font.getGlyphName (int (g), requireReal=1))
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001514 except ValueError:
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001515 raise Exception ("Invalid glyph identifier: %s" % g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001516 continue
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001517 raise Exception ("Invalid glyph identifier: %s" % g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001518 log.lapse ("compile glyph list")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001519 log ("Unicodes:", unicodes)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001520 log ("Glyphs:", glyphs)
1521
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001522 subsetter.populate (glyphs=glyphs, unicodes=unicodes, text=text)
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001523 subsetter.subset (font)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -04001524
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001525 font.save (fontfile + '.subset')
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001526 log.lapse ("compile and save font")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001527
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001528 log.last_time = log.start_time
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001529 log.lapse ("make one with everything (TOTAL TIME)")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001530
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001531 log.font (font)
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001532
1533if __name__ == '__main__':
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001534 main (sys.argv[1:])