blob: 6e8ade412826fc7db00bae6a5234cc6bd723e5b3 [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 Esfahbodfc912be2013-08-13 19:21:17 -040034 """A decorator-returning function to add a new method to one or
35 more classes."""
Behdad Esfahbodbff33d22013-08-13 19:11:01 -040036 def wrapper (method):
Behdad Esfahbod02b92062013-07-21 18:40:59 -040037 for clazz in clazzes:
Behdad Esfahbodc0d59592013-07-24 14:41:47 -040038 assert clazz.__name__ != 'DefaultTable', 'Oops, table class not found.'
Behdad Esfahbod02b92062013-07-21 18:40:59 -040039 setattr (clazz, method.func_name, method)
Behdad Esfahbodbff33d22013-08-13 19:11:01 -040040 return None
Behdad Esfahbod54660612013-07-21 18:16:55 -040041 return wrapper
42
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040043def unique_sorted (l):
Behdad Esfahbod2d9a0962013-07-31 13:33:31 -040044 return sorted (set (l))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040045
46
Behdad Esfahbod54660612013-07-21 18:16:55 -040047@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040048def intersect (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -040049 "Returns ascending list of matching coverage values."
50 return [i for (i,g) in enumerate (self.glyphs) if g in glyphs]
51
52@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -040053def intersect_glyphs (self, glyphs):
54 "Returns set of intersecting glyphs."
55 return set (g for g in self.glyphs if g in glyphs)
56
57@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040058def subset (self, glyphs):
Behdad Esfahbodd821ea02013-07-23 10:50:43 -040059 "Returns ascending list of remaining coverage values."
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040060 indices = self.intersect (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -040061 self.glyphs = [g for g in self.glyphs if g in glyphs]
62 return indices
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040063
Behdad Esfahbod14374262013-08-08 22:26:49 -040064@add_method(fontTools.ttLib.tables.otTables.Coverage)
65def remap (self, coverage_map):
66 "Remaps coverage."
67 self.glyphs = [self.glyphs[i] for i in coverage_map]
68
Behdad Esfahbod54660612013-07-21 18:16:55 -040069@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040070def intersect (self, glyphs):
Behdad Esfahbode10803e2013-08-08 21:09:27 -040071 "Returns ascending list of matching class values."
Behdad Esfahbodfc912be2013-08-13 19:21:17 -040072 return unique_sorted (([0] if any (g not in self.classDefs for g in glyphs) else []) +
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040073 [v for g,v in self.classDefs.iteritems() if g in glyphs])
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040074
75@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -040076def intersect_class (self, glyphs, klass):
77 "Returns set of glyphs matching class."
Behdad Esfahbod0befd6b2013-08-05 22:47:14 -040078 if klass == 0:
Behdad Esfahbod849d25c2013-08-12 19:24:24 -040079 return set (g for g in glyphs if g not in self.classDefs)
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040080 return set (g for g,v in self.classDefs.iteritems() if v == klass and g in glyphs)
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040081
82@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040083def subset (self, glyphs, remap=False):
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040084 "Returns ascending list of remaining classes."
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040085 self.classDefs = {g:v for g,v in self.classDefs.iteritems() if g in glyphs}
Behdad Esfahboda1e0f132013-08-08 21:12:45 -040086 # Note: while class 0 has the special meaning of "not matched", if no glyph will
87 # ever /not match/, we can optimize class 0 out too.
Behdad Esfahbodfc912be2013-08-13 19:21:17 -040088 indices = unique_sorted (([0] if any (g not in self.classDefs for g in glyphs) else []) +
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040089 self.classDefs.itervalues())
Behdad Esfahbodde71dca2013-07-24 12:40:54 -040090 if remap:
91 self.remap (indices)
92 return indices
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -040093
94@add_method(fontTools.ttLib.tables.otTables.ClassDef)
95def remap (self, class_map):
96 "Remaps classes."
Behdad Esfahboddc0c4832013-08-13 18:50:36 -040097 self.classDefs = {g:class_map.index (v) for g,v in self.classDefs.iteritems()}
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040098
Behdad Esfahbod54660612013-07-21 18:16:55 -040099@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400100def closure_glyphs (self, s, cur_glyphs=None):
101 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400102 if self.Format in [1, 2]:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400103 s.glyphs.update (v for g,v in self.mapping.iteritems() if g in cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400104 else:
105 assert 0, "unknown format: %s" % self.Format
106
107@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400108def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400109 if self.Format in [1, 2]:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400110 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 -0400111 return bool (self.mapping)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400112 else:
113 assert 0, "unknown format: %s" % self.Format
114
115@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400116def closure_glyphs (self, s, cur_glyphs=None):
117 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400118 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400119 indices = self.Coverage.intersect (cur_glyphs)
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400120 s.glyphs.update (*(self.Sequence[i].Substitute for i in indices))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400121 else:
122 assert 0, "unknown format: %s" % self.Format
123
124@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400125def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400126 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400127 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400128 self.Sequence = [self.Sequence[i] for i in indices]
Behdad Esfahbod14374262013-08-08 22:26:49 -0400129 # Now drop rules generating glyphs we don't want
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400130 indices = [i for i,seq in enumerate (self.Sequence)
Behdad Esfahbod14374262013-08-08 22:26:49 -0400131 if all (sub in s.glyphs for sub in seq.Substitute)]
132 self.Sequence = [self.Sequence[i] for i in indices]
133 self.Coverage.remap (indices)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400134 self.SequenceCount = len (self.Sequence)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400135 return bool (self.SequenceCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400136 else:
137 assert 0, "unknown format: %s" % self.Format
138
139@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400140def closure_glyphs (self, s, cur_glyphs=None):
141 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400142 if self.Format == 1:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400143 s.glyphs.update (*(vlist for g,vlist in self.alternates.iteritems() if g in cur_glyphs))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400144 else:
145 assert 0, "unknown format: %s" % self.Format
146
147@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400148def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400149 if self.Format == 1:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400150 self.alternates = {g:vlist for g,vlist in self.alternates.iteritems()
Behdad Esfahbod14374262013-08-08 22:26:49 -0400151 if g in s.glyphs and all (v in s.glyphs for v in vlist)}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400152 return bool (self.alternates)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400153 else:
154 assert 0, "unknown format: %s" % self.Format
155
156@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400157def closure_glyphs (self, s, cur_glyphs=None):
158 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400159 if self.Format == 1:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400160 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 -0400161 for g,seqs in self.ligatures.iteritems() if g in cur_glyphs))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400162 else:
163 assert 0, "unknown format: %s" % self.Format
164
165@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400166def subset_glyphs (self, s):
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400167 if self.Format == 1:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400168 self.ligatures = {g:v for g,v in self.ligatures.iteritems() if g in s.glyphs}
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400169 self.ligatures = {g:[seq for seq in seqs
170 if seq.LigGlyph in s.glyphs and
171 all (c in s.glyphs for c in seq.Component)]
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400172 for g,seqs in self.ligatures.iteritems()}
173 self.ligatures = {g:v for g,v in self.ligatures.iteritems() if v}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400174 return bool (self.ligatures)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400175 else:
176 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400177
Behdad Esfahbod54660612013-07-21 18:16:55 -0400178@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400179def closure_glyphs (self, s, cur_glyphs=None):
180 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400181 if self.Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400182 indices = self.Coverage.intersect (cur_glyphs)
Behdad Esfahbodfc912be2013-08-13 19:21:17 -0400183 if (not indices or
184 not all (c.intersect (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage)):
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400185 return
186 s.glyphs.update (self.Substitute[i] for i in indices)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400187 else:
188 assert 0, "unknown format: %s" % self.Format
189
190@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400191def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400192 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400193 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400194 self.Substitute = [self.Substitute[i] for i in indices]
Behdad Esfahbod14374262013-08-08 22:26:49 -0400195 # Now drop rules generating glyphs we don't want
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400196 indices = [i for i,sub in enumerate (self.Substitute)
Behdad Esfahbod14374262013-08-08 22:26:49 -0400197 if sub in s.glyphs]
198 self.Substitute = [self.Substitute[i] for i in indices]
199 self.Coverage.remap (indices)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400200 self.GlyphCount = len (self.Substitute)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400201 return bool (self.GlyphCount and all (c.subset (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400202 else:
203 assert 0, "unknown format: %s" % self.Format
204
205@add_method(fontTools.ttLib.tables.otTables.SinglePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400206def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400207 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400208 return len (self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400209 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400210 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400211 self.Value = [self.Value[i] for i in indices]
212 self.ValueCount = len (self.Value)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400213 return bool (self.ValueCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400214 else:
215 assert 0, "unknown format: %s" % self.Format
216
217@add_method(fontTools.ttLib.tables.otTables.PairPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400218def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400219 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400220 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400221 self.PairSet = [self.PairSet[i] for i in indices]
222 for p in self.PairSet:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400223 p.PairValueRecord = [r for r in p.PairValueRecord if r.SecondGlyph in s.glyphs]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400224 p.PairValueCount = len (p.PairValueRecord)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400225 self.PairSet = [p for p in self.PairSet if p.PairValueCount]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400226 self.PairSetCount = len (self.PairSet)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400227 return bool (self.PairSetCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400228 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400229 class1_map = self.ClassDef1.subset (s.glyphs, remap=True)
230 class2_map = self.ClassDef2.subset (s.glyphs, remap=True)
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -0400231 self.Class1Record = [self.Class1Record[i] for i in class1_map]
232 for c in self.Class1Record:
233 c.Class2Record = [c.Class2Record[i] for i in class2_map]
234 self.Class1Count = len (class1_map)
235 self.Class2Count = len (class2_map)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400236 return bool (self.Class1Count and self.Class2Count and self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400237 else:
238 assert 0, "unknown format: %s" % self.Format
239
240@add_method(fontTools.ttLib.tables.otTables.CursivePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400241def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400242 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400243 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400244 self.EntryExitRecord = [self.EntryExitRecord[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400245 self.EntryExitCount = len (self.EntryExitRecord)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400246 return bool (self.EntryExitCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400247 else:
248 assert 0, "unknown format: %s" % self.Format
249
250@add_method(fontTools.ttLib.tables.otTables.MarkBasePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400251def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400252 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400253 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400254 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
255 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400256 base_indices = self.BaseCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400257 self.BaseArray.BaseRecord = [self.BaseArray.BaseRecord[i] for i in base_indices]
258 self.BaseArray.BaseCount = len (self.BaseArray.BaseRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400259 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400260 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400261 self.ClassCount = len (class_indices)
262 for m in self.MarkArray.MarkRecord:
263 m.Class = class_indices.index (m.Class)
264 for b in self.BaseArray.BaseRecord:
265 b.BaseAnchor = [b.BaseAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400266 return bool (self.ClassCount and self.MarkArray.MarkCount and self.BaseArray.BaseCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400267 else:
268 assert 0, "unknown format: %s" % self.Format
269
270@add_method(fontTools.ttLib.tables.otTables.MarkLigPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400271def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400272 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400273 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400274 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
275 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400276 ligature_indices = self.LigatureCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400277 self.LigatureArray.LigatureAttach = [self.LigatureArray.LigatureAttach[i] for i in ligature_indices]
278 self.LigatureArray.LigatureCount = len (self.LigatureArray.LigatureAttach)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400279 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400280 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400281 self.ClassCount = len (class_indices)
282 for m in self.MarkArray.MarkRecord:
283 m.Class = class_indices.index (m.Class)
284 for l in self.LigatureArray.LigatureAttach:
285 for c in l.ComponentRecord:
286 c.LigatureAnchor = [c.LigatureAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400287 return bool (self.ClassCount and self.MarkArray.MarkCount and self.LigatureArray.LigatureCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400288 else:
289 assert 0, "unknown format: %s" % self.Format
290
291@add_method(fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400292def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400293 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400294 mark1_indices = self.Mark1Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400295 self.Mark1Array.MarkRecord = [self.Mark1Array.MarkRecord[i] for i in mark1_indices]
296 self.Mark1Array.MarkCount = len (self.Mark1Array.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400297 mark2_indices = self.Mark2Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400298 self.Mark2Array.Mark2Record = [self.Mark2Array.Mark2Record[i] for i in mark2_indices]
299 self.Mark2Array.MarkCount = len (self.Mark2Array.Mark2Record)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400300 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400301 class_indices = unique_sorted (v.Class for v in self.Mark1Array.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400302 self.ClassCount = len (class_indices)
303 for m in self.Mark1Array.MarkRecord:
304 m.Class = class_indices.index (m.Class)
305 for b in self.Mark2Array.Mark2Record:
306 b.Mark2Anchor = [b.Mark2Anchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400307 return bool (self.ClassCount and self.Mark1Array.MarkCount and self.Mark2Array.MarkCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400308 else:
309 assert 0, "unknown format: %s" % self.Format
310
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400311@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400312 fontTools.ttLib.tables.otTables.MultipleSubst,
313 fontTools.ttLib.tables.otTables.AlternateSubst,
314 fontTools.ttLib.tables.otTables.LigatureSubst,
315 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
316 fontTools.ttLib.tables.otTables.SinglePos,
317 fontTools.ttLib.tables.otTables.PairPos,
318 fontTools.ttLib.tables.otTables.CursivePos,
319 fontTools.ttLib.tables.otTables.MarkBasePos,
320 fontTools.ttLib.tables.otTables.MarkLigPos,
321 fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400322def subset_lookups (self, lookup_indices):
323 pass
324
325@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400326 fontTools.ttLib.tables.otTables.MultipleSubst,
327 fontTools.ttLib.tables.otTables.AlternateSubst,
328 fontTools.ttLib.tables.otTables.LigatureSubst,
329 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
330 fontTools.ttLib.tables.otTables.SinglePos,
331 fontTools.ttLib.tables.otTables.PairPos,
332 fontTools.ttLib.tables.otTables.CursivePos,
333 fontTools.ttLib.tables.otTables.MarkBasePos,
334 fontTools.ttLib.tables.otTables.MarkLigPos,
335 fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400336def collect_lookups (self):
337 return []
338
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400339@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
340 fontTools.ttLib.tables.otTables.AlternateSubst,
341 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
342def may_have_non_1to1 (self):
343 return False
344
345@add_method(fontTools.ttLib.tables.otTables.MultipleSubst,
346 fontTools.ttLib.tables.otTables.LigatureSubst,
347 fontTools.ttLib.tables.otTables.ContextSubst,
348 fontTools.ttLib.tables.otTables.ChainContextSubst)
349def may_have_non_1to1 (self):
350 return True
351
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400352@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
353 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
354def __classify_context (self):
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400355
356 class ContextHelper:
357 def __init__ (self, klass, Format):
358 if klass.__name__.endswith ('Subst'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400359 Typ = 'Sub'
360 Type = 'Subst'
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400361 else:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400362 Typ = 'Pos'
363 Type = 'Pos'
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400364 if klass.__name__.startswith ('Chain'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400365 Chain = 'Chain'
366 else:
367 Chain = ''
368 ChainTyp = Chain+Typ
369
370 self.Typ = Typ
371 self.Type = Type
372 self.Chain = Chain
373 self.ChainTyp = ChainTyp
374
375 self.LookupRecord = Type+'LookupRecord'
376
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400377 if Format == 1:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400378 Coverage = lambda r: r.Coverage
379 ChainCoverage = lambda r: r.Coverage
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400380 ContextData = lambda r: (None,)
381 ChainContextData = lambda r: (None, None, None)
382 RuleData = lambda r: (r.Input,)
383 ChainRuleData = lambda r: (r.Backtrack, r.Input, r.LookAhead)
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400384 SetRuleData = None
385 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400386 elif Format == 2:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400387 Coverage = lambda r: r.Coverage
388 ChainCoverage = lambda r: r.Coverage
Behdad Esfahbode3f20732013-07-24 11:26:43 -0400389 ContextData = lambda r: (r.ClassDef,)
390 ChainContextData = lambda r: (r.LookAheadClassDef, r.InputClassDef, r.BacktrackClassDef)
391 RuleData = lambda r: (r.Class,)
392 ChainRuleData = lambda r: (r.LookAhead, r.Input, r.Backtrack)
393 def SetRuleData (r, d): (r.Class,) = d
394 def ChainSetRuleData (r, d): (r.LookAhead, r.Input, r.Backtrack) = d
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400395 elif Format == 3:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400396 Coverage = lambda r: r.Coverage[0]
397 ChainCoverage = lambda r: r.InputCoverage[0]
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400398 ContextData = None
399 ChainContextData = None
400 RuleData = lambda r: r.Coverage
401 ChainRuleData = lambda r: r.LookAheadCoverage + r.InputCoverage + r.BacktrackCoverage
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400402 SetRuleData = None
403 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400404 else:
405 assert 0, "unknown format: %s" % Format
406
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400407 if Chain:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400408 self.Coverage = ChainCoverage
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400409 self.ContextData = ChainContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400410 self.RuleData = ChainRuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400411 self.SetRuleData = ChainSetRuleData
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400412 else:
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400413 self.Coverage = Coverage
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400414 self.ContextData = ContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400415 self.RuleData = RuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400416 self.SetRuleData = SetRuleData
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400417
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400418 if Format == 1:
419 self.Rule = ChainTyp+'Rule'
420 self.RuleCount = ChainTyp+'RuleCount'
421 self.RuleSet = ChainTyp+'RuleSet'
422 self.RuleSetCount = ChainTyp+'RuleSetCount'
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400423 self.Intersect = lambda glyphs, ContextData, RuleData: [RuleData] if RuleData in glyphs else []
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400424 elif Format == 2:
425 self.Rule = ChainTyp+'ClassRule'
426 self.RuleCount = ChainTyp+'ClassRuleCount'
427 self.RuleSet = ChainTyp+'ClassSet'
428 self.RuleSetCount = ChainTyp+'ClassSetCount'
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400429 self.Intersect = lambda glyphs, ContextData, RuleData: ContextData.intersect_class (glyphs, RuleData)
Behdad Esfahbod89987002013-07-23 23:07:42 -0400430
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400431 self.ClassDef = 'InputClassDef' if Chain else 'ClassDef'
Behdad Esfahbod27108392013-07-23 16:40:47 -0400432
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400433 if self.Format not in [1, 2, 3]:
434 return None # Don't shoot the messenger; let it go
435 if not hasattr (self.__class__, "__ContextHelpers"):
436 self.__class__.__ContextHelpers = {}
437 if self.Format not in self.__class__.__ContextHelpers:
438 self.__class__.__ContextHelpers[self.Format] = ContextHelper (self.__class__, self.Format)
439 return self.__class__.__ContextHelpers[self.Format]
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400440
Behdad Esfahbodf2b6d9c2013-07-23 17:31:54 -0400441@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400442def closure_glyphs (self, s, cur_glyphs=None):
443 if cur_glyphs == None: cur_glyphs = s.glyphs
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400444 c = self.__classify_context ()
445
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400446 indices = c.Coverage (self).intersect (s.glyphs)
447 if not indices:
448 return []
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400449 cur_glyphs = c.Coverage (self).intersect_glyphs (s.glyphs);
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400450
Behdad Esfahbod00776972013-07-23 15:33:00 -0400451 if self.Format == 1:
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400452 ContextData = c.ContextData (self)
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400453 rss = getattr (self, c.RuleSet)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400454 for i in indices:
455 if not rss[i]: continue
456 for r in getattr (rss[i], c.Rule):
457 if not r: continue
458 if all (all (c.Intersect (s.glyphs, cd, k) for k in klist)
459 for cd,klist in zip (ContextData, c.RuleData (r))):
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400460 chaos = False
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400461 for ll in getattr (r, c.LookupRecord):
462 if not ll: continue
463 seqi = ll.SequenceIndex
464 if seqi == 0:
465 pos_glyphs = set (c.Coverage (self).glyphs[i])
466 else:
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400467 if chaos:
468 pos_glyphs = s.glyphs
469 else:
470 pos_glyphs = set (r.Input[seqi - 1])
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400471 lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400472 chaos = chaos or lookup.may_have_non_1to1 ()
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400473 lookup.closure_glyphs (s, cur_glyphs=pos_glyphs)
Behdad Esfahbod00776972013-07-23 15:33:00 -0400474 elif self.Format == 2:
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400475 ClassDef = getattr (self, c.ClassDef)
476 indices = ClassDef.intersect (cur_glyphs)
477 ContextData = c.ContextData (self)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400478 rss = getattr (self, c.RuleSet)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400479 for i in indices:
480 if not rss[i]: continue
481 for r in getattr (rss[i], c.Rule):
482 if not r: continue
483 if all (all (c.Intersect (s.glyphs, cd, k) for k in klist)
484 for cd,klist in zip (ContextData, c.RuleData (r))):
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400485 chaos = False
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400486 for ll in getattr (r, c.LookupRecord):
487 if not ll: continue
488 seqi = ll.SequenceIndex
489 if seqi == 0:
490 pos_glyphs = ClassDef.intersect_class (cur_glyphs, i)
491 else:
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400492 if chaos:
493 pos_glyphs = s.glyphs
494 else:
495 pos_glyphs = ClassDef.intersect_class (s.glyphs, r.Input[seqi - 1])
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400496 lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400497 chaos = chaos or lookup.may_have_non_1to1 ()
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400498 lookup.closure_glyphs (s, cur_glyphs=pos_glyphs)
Behdad Esfahbod00776972013-07-23 15:33:00 -0400499 elif self.Format == 3:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400500 if not all (x.intersect (s.glyphs) for x in c.RuleData (self)):
Behdad Esfahbod00776972013-07-23 15:33:00 -0400501 return []
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400502 r = self
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400503 chaos = False
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400504 for ll in getattr (r, c.LookupRecord):
505 if not ll: continue
506 seqi = ll.SequenceIndex
507 if seqi == 0:
508 pos_glyphs = cur_glyphs
509 else:
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400510 if chaos:
511 pos_glyphs = s.glyphs
512 else:
513 pos_glyphs = r.InputCoverage[seqi].intersect_glyphs (s.glyphs)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400514 lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400515 chaos = chaos or lookup.may_have_non_1to1 ()
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400516 lookup.closure_glyphs (s, cur_glyphs=pos_glyphs)
Behdad Esfahbod00776972013-07-23 15:33:00 -0400517 else:
518 assert 0, "unknown format: %s" % self.Format
519
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400520@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ContextPos,
521 fontTools.ttLib.tables.otTables.ChainContextSubst, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400522def subset_glyphs (self, s):
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400523 c = self.__classify_context ()
524
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400525 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400526 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400527 rss = getattr (self, c.RuleSet)
528 rss = [rss[i] for i in indices]
529 for rs in rss:
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400530 if not rs: continue
531 ss = getattr (rs, c.Rule)
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400532 ss = [r for r in ss
533 if r and all (all (g in s.glyphs for g in glist)
Behdad Esfahbod849d25c2013-08-12 19:24:24 -0400534 for glist in c.RuleData (r))]
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400535 setattr (rs, c.Rule, ss)
536 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400537 # Prune empty subrulesets
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400538 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400539 setattr (self, c.RuleSet, rss)
540 setattr (self, c.RuleSetCount, len (rss))
541 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400542 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400543 if not self.Coverage.subset (s.glyphs):
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400544 return False
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400545 indices = getattr (self, c.ClassDef).subset (self.Coverage.glyphs, remap=False)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400546 rss = getattr (self, c.RuleSet)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400547 rss = [rss[i] for i in indices]
548 ContextData = c.ContextData (self)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400549 klass_maps = [x.subset (s.glyphs, remap=True) for x in ContextData]
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400550 for rs in rss:
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400551 if not rs: continue
552 ss = getattr (rs, c.Rule)
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400553 ss = [r for r in ss
554 if r and all (all (k in klass_map for k in klist)
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400555 for klass_map,klist in zip (klass_maps, c.RuleData (r)))]
556 setattr (rs, c.Rule, ss)
557 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400558
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400559 # Remap rule classes
560 for r in ss:
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400561 c.SetRuleData (r, [[klass_map.index (k) for k in klist]
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400562 for klass_map,klist in zip (klass_maps, c.RuleData (r))])
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400563 # Prune empty subrulesets
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400564 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
565 setattr (self, c.RuleSet, rss)
566 setattr (self, c.RuleSetCount, len (rss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400567 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400568 elif self.Format == 3:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400569 return all (x.subset (s.glyphs) for x in c.RuleData (self))
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400570 else:
571 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400572
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400573@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
574 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400575def subset_lookups (self, lookup_indices):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400576 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400577
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400578 if self.Format in [1, 2]:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400579 for rs in getattr (self, c.RuleSet):
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400580 if not rs: continue
581 for r in getattr (rs, c.Rule):
582 if not r: continue
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400583 setattr (r, c.LookupRecord, [ll for ll in getattr (r, c.LookupRecord) if ll
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400584 if ll.LookupListIndex in lookup_indices])
585 for ll in getattr (r, c.LookupRecord):
586 if not ll: continue
587 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400588 elif self.Format == 3:
Behdad Esfahbod50cff382013-08-13 18:40:36 -0400589 setattr (self, c.LookupRecord, [ll for ll in getattr (self, c.LookupRecord) if ll
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400590 if ll.LookupListIndex in lookup_indices])
591 for ll in getattr (self, c.LookupRecord):
Behdad Esfahbod6c11b892013-08-12 15:41:30 -0400592 if not ll: continue
593 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400594 else:
595 assert 0, "unknown format: %s" % self.Format
596
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400597@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
598 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400599def collect_lookups (self):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400600 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400601
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400602 if self.Format in [1, 2]:
Behdad Esfahbodfc912be2013-08-13 19:21:17 -0400603 return [ll.LookupListIndex
604 for rs in getattr (self, c.RuleSet) if rs
605 for r in getattr (rs, c.Rule) if r
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400606 for ll in getattr (r, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400607 elif self.Format == 3:
Behdad Esfahbodfc912be2013-08-13 19:21:17 -0400608 return [ll.LookupListIndex
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400609 for ll in getattr (self, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400610 else:
611 assert 0, "unknown format: %s" % self.Format
612
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400613@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400614def closure_glyphs (self, s, cur_glyphs=None):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400615 if self.Format == 1:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400616 self.ExtSubTable.closure_glyphs (s, cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400617 else:
618 assert 0, "unknown format: %s" % self.Format
619
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400620@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
621def may_have_non_1to1 (self):
622 if self.Format == 1:
623 return self.ExtSubTable.may_have_non_1to1 ()
624 else:
625 assert 0, "unknown format: %s" % self.Format
626
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400627@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400628def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400629 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400630 return self.ExtSubTable.subset_glyphs (s)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400631 else:
632 assert 0, "unknown format: %s" % self.Format
633
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400634@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
635def subset_lookups (self, lookup_indices):
636 if self.Format == 1:
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400637 return self.ExtSubTable.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400638 else:
639 assert 0, "unknown format: %s" % self.Format
640
641@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
642def collect_lookups (self):
643 if self.Format == 1:
644 return self.ExtSubTable.collect_lookups ()
645 else:
646 assert 0, "unknown format: %s" % self.Format
647
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400648@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod1d4fa132013-08-08 22:59:32 -0400649def closure_glyphs (self, s, cur_glyphs=None):
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400650 for st in self.SubTable:
651 if not st: continue
652 st.closure_glyphs (s, cur_glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400653
654@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400655def subset_glyphs (self, s):
656 self.SubTable = [st for st in self.SubTable if st and st.subset_glyphs (s)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400657 self.SubTableCount = len (self.SubTable)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400658 return bool (self.SubTableCount)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400659
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400660@add_method(fontTools.ttLib.tables.otTables.Lookup)
661def subset_lookups (self, lookup_indices):
662 for s in self.SubTable:
663 s.subset_lookups (lookup_indices)
664
665@add_method(fontTools.ttLib.tables.otTables.Lookup)
666def collect_lookups (self):
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400667 return unique_sorted (sum ((st.collect_lookups () for st in self.SubTable if st), []))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400668
Behdad Esfahbodaeacc152013-08-12 20:24:33 -0400669@add_method(fontTools.ttLib.tables.otTables.Lookup)
670def may_have_non_1to1 (self):
671 return any (st.may_have_non_1to1 () for st in self.SubTable if st)
672
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400673@add_method(fontTools.ttLib.tables.otTables.LookupList)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400674def subset_glyphs (self, s):
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400675 "Returns the indices of nonempty lookups."
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400676 return [i for (i,l) in enumerate (self.Lookup) if l and l.subset_glyphs (s)]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400677
678@add_method(fontTools.ttLib.tables.otTables.LookupList)
679def subset_lookups (self, lookup_indices):
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400680 self.Lookup = [self.Lookup[i] for i in lookup_indices if i < self.LookupCount]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400681 self.LookupCount = len (self.Lookup)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400682 for l in self.Lookup:
683 l.subset_lookups (lookup_indices)
684
685@add_method(fontTools.ttLib.tables.otTables.LookupList)
686def closure_lookups (self, lookup_indices):
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400687 lookup_indices = unique_sorted (lookup_indices)
688 recurse = lookup_indices
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400689 while True:
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400690 recurse_lookups = sum ((self.Lookup[i].collect_lookups () for i in recurse if i < self.LookupCount), [])
691 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 -0400692 if not recurse_lookups:
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400693 return unique_sorted (lookup_indices)
694 recurse_lookups = unique_sorted (recurse_lookups)
695 lookup_indices.extend (recurse_lookups)
696 recurse = recurse_lookups
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400697
698@add_method(fontTools.ttLib.tables.otTables.Feature)
699def subset_lookups (self, lookup_indices):
700 self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices]
701 # Now map them.
702 self.LookupListIndex = [lookup_indices.index (l) for l in self.LookupListIndex]
703 self.LookupCount = len (self.LookupListIndex)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400704 return self.LookupCount
Behdad Esfahbod54660612013-07-21 18:16:55 -0400705
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400706@add_method(fontTools.ttLib.tables.otTables.Feature)
707def collect_lookups (self):
708 return self.LookupListIndex[:]
709
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400710@add_method(fontTools.ttLib.tables.otTables.FeatureList)
711def subset_lookups (self, lookup_indices):
712 "Returns the indices of nonempty features."
713 feature_indices = [i for (i,f) in enumerate (self.FeatureRecord) if f.Feature.subset_lookups (lookup_indices)]
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400714 self.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400715 return feature_indices
716
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400717@add_method(fontTools.ttLib.tables.otTables.FeatureList)
718def collect_lookups (self, feature_indices):
719 return unique_sorted (sum ((self.FeatureRecord[i].Feature.collect_lookups () for i in feature_indices
720 if i < self.FeatureCount), []))
721
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400722@add_method(fontTools.ttLib.tables.otTables.FeatureList)
723def subset_features (self, feature_indices):
724 self.FeatureRecord = [self.FeatureRecord[i] for i in feature_indices]
725 self.FeatureCount = len (self.FeatureRecord)
726 return bool (self.FeatureCount)
727
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400728@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
729def subset_features (self, feature_indices):
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400730 if self.ReqFeatureIndex in feature_indices:
731 self.ReqFeatureIndex = feature_indices.index (self.ReqFeatureIndex)
732 else:
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400733 self.ReqFeatureIndex = 65535
734 self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400735 # Now map them.
736 self.FeatureIndex = [feature_indices.index (f) for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400737 self.FeatureCount = len (self.FeatureIndex)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400738 return bool (self.FeatureCount or self.ReqFeatureIndex != 65535)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400739
740@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
741def collect_features (self):
742 feature_indices = self.FeatureIndex[:]
743 if self.ReqFeatureIndex != 65535:
744 feature_indices.append (self.ReqFeatureIndex)
745 return unique_sorted (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400746
747@add_method(fontTools.ttLib.tables.otTables.Script)
748def subset_features (self, feature_indices):
749 if self.DefaultLangSys and not self.DefaultLangSys.subset_features (feature_indices):
750 self.DefaultLangSys = None
751 self.LangSysRecord = [l for l in self.LangSysRecord if l.LangSys.subset_features (feature_indices)]
752 self.LangSysCount = len (self.LangSysRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400753 return bool (self.LangSysCount or self.DefaultLangSys)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400754
755@add_method(fontTools.ttLib.tables.otTables.Script)
756def collect_features (self):
Behdad Esfahbod2307c8b2013-07-23 11:18:13 -0400757 feature_indices = [l.LangSys.collect_features () for l in self.LangSysRecord]
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400758 if self.DefaultLangSys:
759 feature_indices.append (self.DefaultLangSys.collect_features ())
760 return unique_sorted (sum (feature_indices, []))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400761
762@add_method(fontTools.ttLib.tables.otTables.ScriptList)
763def subset_features (self, feature_indices):
764 self.ScriptRecord = [s for s in self.ScriptRecord if s.Script.subset_features (feature_indices)]
765 self.ScriptCount = len (self.ScriptRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400766 return bool (self.ScriptCount)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400767
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400768@add_method(fontTools.ttLib.tables.otTables.ScriptList)
769def collect_features (self):
770 return unique_sorted (sum ((s.Script.collect_features () for s in self.ScriptRecord), []))
771
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400772@add_method(fontTools.ttLib.getTableClass('GSUB'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400773def closure_glyphs (self, s):
774 s.table = self.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400775 feature_indices = self.table.ScriptList.collect_features ()
776 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400777 while True:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400778 orig_glyphs = s.glyphs.copy ()
779 for i in lookup_indices:
780 if i >= self.table.LookupList.LookupCount: continue
781 if not self.table.LookupList.Lookup[i]: continue
782 self.table.LookupList.Lookup[i].closure_glyphs (s)
783 if orig_glyphs == s.glyphs:
784 break
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400785 del s.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400786
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400787@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400788def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400789 s.glyphs = s.glyphs_gsubed
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400790 lookup_indices = self.table.LookupList.subset_glyphs (s)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400791 self.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400792 self.prune_lookups ()
793 return True
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400794
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400795@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400796def subset_lookups (self, lookup_indices):
797 "Retrains specified lookups, then removes empty features, language systems, and scripts."
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400798 self.table.LookupList.subset_lookups (lookup_indices)
799 feature_indices = self.table.FeatureList.subset_lookups (lookup_indices)
800 self.table.ScriptList.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400801
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400802@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
803def prune_lookups (self):
804 "Remove unreferenced lookups"
805 feature_indices = self.table.ScriptList.collect_features ()
806 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
807 lookup_indices = self.table.LookupList.closure_lookups (lookup_indices)
808 self.subset_lookups (lookup_indices)
809
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400810@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
811def subset_feature_tags (self, feature_tags):
812 feature_indices = [i for (i,f) in enumerate (self.table.FeatureList.FeatureRecord) if f.FeatureTag in feature_tags]
813 self.table.FeatureList.subset_features (feature_indices)
814 self.table.ScriptList.subset_features (feature_indices)
815
816@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400817def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400818 if options.layout_features and '*' not in options.layout_features:
819 self.subset_feature_tags (options.layout_features)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400820 self.prune_lookups ()
821 return True
822
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400823@add_method(fontTools.ttLib.getTableClass('GDEF'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400824def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400825 glyphs = s.glyphs_gsubed
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400826 table = self.table
827 if table.LigCaretList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400828 indices = table.LigCaretList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400829 table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i] for i in indices]
830 table.LigCaretList.LigGlyphCount = len (table.LigCaretList.LigGlyph)
831 if not table.LigCaretList.LigGlyphCount:
832 table.LigCaretList = None
833 if table.MarkAttachClassDef:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400834 table.MarkAttachClassDef.classDefs = {g:v for g,v in table.MarkAttachClassDef.classDefs.iteritems() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400835 if not table.MarkAttachClassDef.classDefs:
836 table.MarkAttachClassDef = None
837 if table.GlyphClassDef:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400838 table.GlyphClassDef.classDefs = {g:v for g,v in table.GlyphClassDef.classDefs.iteritems() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400839 if not table.GlyphClassDef.classDefs:
840 table.GlyphClassDef = None
841 if table.AttachList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400842 indices = table.AttachList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400843 table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i] for i in indices]
844 table.AttachList.GlyphCount = len (table.AttachList.AttachPoint)
845 if not table.AttachList.GlyphCount:
846 table.AttachList = None
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400847 return bool (table.LigCaretList or table.MarkAttachClassDef or table.GlyphClassDef or table.AttachList)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400848
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400849@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbodd4e33a72013-07-24 18:51:05 -0400850def prune_pre_subset (self, options):
851 # Prune unknown kern table types
852 self.kernTables = [t for t in self.kernTables if hasattr (t, 'kernTable')]
853 return bool (self.kernTables)
854
855@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400856def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400857 glyphs = s.glyphs_gsubed
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400858 for t in self.kernTables:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400859 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 -0400860 self.kernTables = [t for t in self.kernTables if t.kernTable]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400861 return bool (self.kernTables)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400862
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400863@add_method(fontTools.ttLib.getTableClass('hmtx'), fontTools.ttLib.getTableClass('vmtx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400864def subset_glyphs (self, s):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400865 self.metrics = {g:v for g,v in self.metrics.iteritems() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400866 return bool (self.metrics)
Behdad Esfahbodc7160442013-07-22 14:29:08 -0400867
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400868@add_method(fontTools.ttLib.getTableClass('hdmx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400869def subset_glyphs (self, s):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400870 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 -0400871 return bool (self.hdmx)
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400872
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400873@add_method(fontTools.ttLib.getTableClass('VORG'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400874def subset_glyphs (self, s):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -0400875 self.VOriginRecords = {g:v for g,v in self.VOriginRecords.iteritems() if g in s.glyphs}
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400876 self.numVertOriginYMetrics = len (self.VOriginRecords)
877 return True # Never drop; has default metrics
878
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400879@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400880def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400881 if not options.glyph_names:
Behdad Esfahbod42648242013-07-23 12:56:06 -0400882 self.formatType = 3.0
883 return True
884
885@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400886def subset_glyphs (self, s):
Behdad Esfahbod42648242013-07-23 12:56:06 -0400887 self.extraNames = [] # This seems to do it
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -0400888 return True
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400889
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400890# Copied from _g_l_y_f.py
891ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes
892ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points
893ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true
894WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0
895NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!)
896MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one
897WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy
898WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11
899WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow
900USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph
901OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts
902SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple)
903UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS)
904
905@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
906def getComponentNamesFast (self, glyfTable):
907 if struct.unpack(">h", self.data[:2])[0] >= 0:
908 return [] # Not composite
909 data = self.data
910 i = 10
911 components = []
912 more = 1
913 while more:
914 flags, glyphID = struct.unpack(">HH", data[i:i+4])
915 i += 4
916 flags = int(flags)
917 components.append (glyfTable.getGlyphName (int (glyphID)))
918
919 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
920 else: i += 2
921 if flags & WE_HAVE_A_SCALE: i += 2
922 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
923 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
924 more = flags & MORE_COMPONENTS
925 return components
926
927@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
928def remapComponentsFast (self, indices):
929 if struct.unpack(">h", self.data[:2])[0] >= 0:
930 return # Not composite
931 data = bytearray (self.data)
932 i = 10
933 more = 1
934 while more:
935 flags = (data[i] << 8) | data[i+1]
936 glyphID = (data[i+2] << 8) | data[i+3]
937 # Remap
938 glyphID = indices.index (glyphID)
939 data[i+2] = glyphID >> 8
940 data[i+3] = glyphID & 0xFF
941 i += 4
942 flags = int(flags)
943
944 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
945 else: i += 2
946 if flags & WE_HAVE_A_SCALE: i += 2
947 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
948 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
949 more = flags & MORE_COMPONENTS
950 self.data = str (data)
951
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400952@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
953def dropInstructionsFast (self):
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400954 numContours = struct.unpack(">h", self.data[:2])[0]
955 data = bytearray (self.data)
956 i = 10
957 if numContours >= 0:
958 i += 2 * numContours # endPtsOfContours
959 instructionLen = (data[i] << 8) | data[i+1]
960 # Zero it
961 data[i] = data [i+1] = 0
962 i += 2
Behdad Esfahbod0fb69882013-07-24 17:25:35 -0400963 if instructionLen:
964 # Splice it out
965 data = data[:i] + data[i+instructionLen:]
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400966 else:
967 more = 1
968 while more:
969 flags = (data[i] << 8) | data[i+1]
970 # Turn instruction flag off
971 flags &= ~WE_HAVE_INSTRUCTIONS
972 data[i+0] = flags >> 8
973 data[i+1] = flags & 0xFF
974 i += 4
975 flags = int(flags)
976
977 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
978 else: i += 2
979 if flags & WE_HAVE_A_SCALE: i += 2
980 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
981 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
982 more = flags & MORE_COMPONENTS
983 # Cut off
984 data = data[:i]
985 if len(data) % 4:
986 # add pad bytes
987 nPadBytes = 4 - (len(data) % 4)
988 for i in range (nPadBytes):
989 data.append (0)
990 self.data = str (data)
991
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400992@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400993def closure_glyphs (self, s):
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400994 decompose = s.glyphs
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400995 # I don't know if component glyphs can be composite themselves.
996 # We handle them anyway.
997 while True:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -0400998 components = set ()
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400999 for g in decompose:
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001000 if g not in self.glyphs:
Behdad Esfahbodf8c20e42013-07-23 23:13:23 -04001001 continue
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001002 gl = self.glyphs[g]
1003 if hasattr (gl, "data"):
1004 for c in gl.getComponentNamesFast (self):
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001005 if c not in s.glyphs:
1006 components.add (c)
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001007 else:
1008 # TTX seems to expand gid0..3 always
1009 if gl.isComposite ():
1010 for c in gl.components:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001011 if c.glyphName not in s.glyphs:
1012 components.add (c.glyphName)
1013 components = set (c for c in components if c not in s.glyphs)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001014 if not components:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001015 break
1016 decompose = components
1017 s.glyphs.update (components)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001018
1019@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001020def subset_glyphs (self, s):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001021 self.glyphs = {g:v for g,v in self.glyphs.iteritems() if g in s.glyphs}
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001022 indices = [i for i,g in enumerate (self.glyphOrder) if g in s.glyphs]
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001023 for v in self.glyphs.itervalues():
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -04001024 if hasattr (v, "data"):
1025 v.remapComponentsFast (indices)
1026 else:
1027 pass # No need
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001028 self.glyphOrder = [g for g in self.glyphOrder if g in s.glyphs]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -04001029 return bool (self.glyphs)
Behdad Esfahbod861d9152013-07-22 16:47:24 -04001030
Behdad Esfahboded98c612013-07-23 12:37:41 -04001031@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -04001032def prune_post_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001033 if not options.hinting:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001034 for v in self.glyphs.itervalues():
Behdad Esfahbod6ec88542013-07-24 16:52:47 -04001035 if hasattr (v, "data"):
1036 v.dropInstructionsFast ()
1037 else:
1038 v.program = fontTools.ttLib.tables.ttProgram.Program()
1039 v.program.fromBytecode([])
Behdad Esfahboded98c612013-07-23 12:37:41 -04001040 return True
1041
Behdad Esfahbod2b677c82013-07-23 13:37:13 -04001042@add_method(fontTools.ttLib.getTableClass('CFF '))
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001043def prune_pre_subset (self, s):
Behdad Esfahbod4e721862013-08-13 16:24:45 -04001044 cff = self.cff
1045 # CFF table should have one font only
1046 cff.fontNames = cff.fontNames[:1]
1047 return bool (cff.fontNames)
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001048
1049@add_method(fontTools.ttLib.getTableClass('CFF '))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001050def subset_glyphs (self, s):
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001051 cff = self.cff
1052 for fontname in cff.keys():
1053 font = cff[fontname]
1054 cs = font.CharStrings
1055 if cs.charStringsAreIndexed:
1056 indices = [i for i,g in enumerate (font.charset) if g in s.glyphs]
1057 # Load all glyphs
1058 for g in font.charset:
1059 if g not in s.glyphs: continue
1060 cs.getItemAndSelector (g)
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001061 csi = cs.charStringsIndex
1062 csi.items = [csi.items[i] for i in indices]
1063 csi.offsets = [] # Don't need it; loaded all glyphs
Behdad Esfahbod31ebebe2013-08-13 16:02:33 -04001064 if hasattr (font, "FDSelect"):
Behdad Esfahbod8e3b8862013-08-13 16:02:18 -04001065 sel = font.FDSelect
1066 sel.format = None
1067 sel.gidArray = [font.FDSelect.gidArray[i] for i in indices]
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001068 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 -04001069 else:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001070 cs.charStrings = {g:v for g,v in cs.charStrings.iteritems() if g in s.glyphs}
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001071 font.charset = [g for g in font.charset if g in s.glyphs]
1072 font.numGlyphs = len (font.charset)
Behdad Esfahbod409286a2013-08-13 15:57:33 -04001073 return any (cff[fontname].numGlyphs for fontname in cff.keys())
Behdad Esfahbod1a4e72e2013-08-13 15:46:37 -04001074
1075@add_method(fontTools.ttLib.getTableClass('glyf'))
1076def prune_post_subset (self, options):
1077 if not options.hinting:
1078 pass # Drop hints
1079 return True
Behdad Esfahbod2b677c82013-07-23 13:37:13 -04001080
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001081@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001082def closure_glyphs (self, s):
1083 tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [1, 10]]
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001084 for u in s.unicodes_requested:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001085 found = False
1086 for table in tables:
1087 if u in table.cmap:
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001088 s.glyphs.add (table.cmap[u])
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001089 found = True
1090 break
1091 if not found:
1092 s.log ("No glyph for Unicode value %s; skipping." % u)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001093
1094@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001095def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001096 if not options.legacy_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -04001097 # Drop non-Unicode / non-Symbol cmaps
1098 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 -04001099 if not options.symbol_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -04001100 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 -04001101 # TODO Only keep one subtable?
Behdad Esfahbodabb50a12013-07-23 12:58:37 -04001102 # For now, drop format=0 which can't be subset_glyphs easily?
1103 self.tables = [t for t in self.tables if t.format != 0]
1104 return bool (self.tables)
1105
1106@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001107def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -04001108 s.glyphs = s.glyphs_cmaped
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001109 for t in self.tables:
Behdad Esfahbod9453a362013-07-22 16:21:24 -04001110 # For reasons I don't understand I need this here
1111 # to force decompilation of the cmap format 14.
1112 try:
1113 getattr (t, "asdf")
1114 except AttributeError:
1115 pass
Behdad Esfahbodb13d7902013-07-22 16:01:15 -04001116 if t.format == 14:
Behdad Esfahbod9453a362013-07-22 16:21:24 -04001117 # XXX We drop all the default-UVS mappings (g==None)
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001118 t.uvsDict = {v:[(u,g) for (u,g) in l if g in s.glyphs] for (v,l) in t.uvsDict.iteritems()}
1119 t.uvsDict = {v:l for (v,l) in t.uvsDict.iteritems() if l}
Behdad Esfahbodb13d7902013-07-22 16:01:15 -04001120 else:
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001121 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 -04001122 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 -04001123 # XXX Convert formats when needed
Behdad Esfahbod2ac36302013-08-08 23:49:00 -04001124 # In particular, if we have a format=12 without non-BMP
1125 # characters, either drop format=12 one or convert it
1126 # to format=4 if there's not one.
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001127 return bool (self.tables)
1128
Behdad Esfahbod61addb42013-07-23 11:03:49 -04001129@add_method(fontTools.ttLib.getTableClass('name'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -04001130def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001131 if '*' not in options.name_IDs:
1132 self.names = [n for n in self.names if n.nameID in options.name_IDs]
1133 if not options.name_legacy:
Behdad Esfahbod20faeb02013-07-23 13:19:03 -04001134 self.names = [n for n in self.names if n.platformID == 3 and n.platEncID == 1]
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001135 if '*' not in options.name_languages:
1136 self.names = [n for n in self.names if n.langID in options.name_languages]
Behdad Esfahbod20faeb02013-07-23 13:19:03 -04001137 return True # Retain even if empty
Behdad Esfahbod653e9742013-07-22 15:17:12 -04001138
Behdad Esfahbod8c646f62013-07-22 15:06:23 -04001139
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -04001140# TODO OS/2 ulUnicodeRange / ulCodePageRange?
Behdad Esfahbodf71267b2013-07-23 12:59:13 -04001141# TODO Drop unneeded GSUB/GPOS Script/LangSys entries
Behdad Esfahbod398d3892013-07-23 15:29:40 -04001142# TODO Avoid recursing too much
Behdad Esfahbode94aa0e2013-07-23 13:22:04 -04001143# TODO Text direction considerations
1144# TODO Text script / language considerations
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001145# TODO Drop unknown tables? Using DefaultTable.prune?
Behdad Esfahbod8c4f7cc2013-07-24 17:58:29 -04001146# TODO Drop GPOS Device records if not hinting?
Behdad Esfahbod93e26362013-08-09 14:22:48 -04001147# TODO Move font name loading hack to Subsetter?
Behdad Esfahbod56ebd042013-07-22 13:02:24 -04001148
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001149
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001150class Subsetter:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001151
1152 class Options:
Behdad Esfahbod26d9ee72013-08-13 16:55:01 -04001153
1154 class UnknownOptionError (Exception):
1155 pass
1156
Behdad Esfahbod9eeeb4e2013-08-13 16:58:50 -04001157 drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'PCLT', 'LTSH']
1158 drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill'] # Graphite
1159 drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL'] # Color
1160 no_subset_tables_default = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2', 'loca', 'name', 'cvt ', 'fpgm', 'prep']
1161 hinting_tables_default = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
1162
1163 # Based on HarfBuzz shapers
1164 layout_features_groups = {
1165 # Default shaper
1166 'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
1167 'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
1168 'vertical': ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
1169 'ltr': ['ltra', 'ltrm'],
1170 'rtl': ['rtla', 'rtlm'],
1171 # Complex shapers
1172 'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3', 'cswh', 'mset'],
1173 'hangul': ['ljmo', 'vjmo', 'tjmo'],
1174 'tibetal': ['abvs', 'blws', 'abvm', 'blwm'],
1175 'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half', 'abvf', 'pstf', 'cfar', 'vatu', 'cjct',
1176 'init', 'pres', 'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
1177 }
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001178 layout_features_default = unique_sorted (sum (layout_features_groups.itervalues(), []))
Behdad Esfahbod9eeeb4e2013-08-13 16:58:50 -04001179
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001180 drop_tables = drop_tables_default
Behdad Esfahbode6fc8ca2013-08-13 12:25:31 -04001181 no_subset_tables = no_subset_tables_default
1182 hinting_tables = hinting_tables_default
Behdad Esfahbod9eeeb4e2013-08-13 16:58:50 -04001183 layout_features = layout_features_default
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001184 hinting = False
1185 glyph_names = False
1186 legacy_cmap = False
1187 symbol_cmap = False
1188 name_IDs = [1, 2] # Family and Style
1189 name_legacy = False
1190 name_languages = [0x0409] # English
1191 mandatory_glyphs = True # First four for TrueType, .notdef for CFF
1192 recalc_bboxes = False # Slows us down
1193
1194 def __init__ (self, **kwargs):
1195
1196 self.set (**kwargs)
1197
1198 def set (self, **kwargs):
Behdad Esfahboddc0c4832013-08-13 18:50:36 -04001199 for k,v in kwargs.iteritems():
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001200 if not hasattr (self, k):
Behdad Esfahbod26d9ee72013-08-13 16:55:01 -04001201 raise self.UnknownOptionError ("Unknown option '%s'" % k)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001202 setattr (self, k, v)
1203
1204 def parse_opts (self, argv, ignore_unknown=False):
1205 ret = []
1206 opts = {}
1207 for a in argv:
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001208 orig_a = a
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001209 if not a.startswith ('--'):
1210 ret.append (a)
1211 continue
1212 a = a[2:]
1213 i = a.find ('=')
1214 if i == -1:
1215 if a.startswith ("no-"):
1216 k = a[3:]
1217 v = False
1218 else:
1219 k = a
1220 v = True
1221 else:
1222 k = a[:i]
1223 v = a[i+1:]
1224 k = k.replace ('-', '_')
1225 if not hasattr (self, k):
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001226 if ignore_unknown == True or k in ignore_unknown:
1227 ret.append (orig_a)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001228 continue
1229 else:
Behdad Esfahbod26d9ee72013-08-13 16:55:01 -04001230 raise self.UnknownOptionError ("Unknown option '%s'" % a)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001231
1232 ov = getattr (self, k)
1233 if isinstance (ov, bool):
1234 v = bool (v)
1235 elif isinstance (ov, int):
1236 v = int (v)
1237 elif isinstance (ov, list):
1238 v = v.split (',')
1239 v = [int (x, 0) if x[0] in range (10) else x for x in v]
1240
1241 opts[k] = v
1242 self.set (**opts)
1243
1244 return ret
1245
1246
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001247 def __init__ (self, options=None, log=None):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001248
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001249 if not log:
1250 log = Logger()
1251 if not options:
1252 options = Options()
1253
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001254 self.options = options
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001255 self.log = log
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001256 self.unicodes_requested = set ()
1257 self.glyphs_requested = set ()
Behdad Esfahboda7d22432013-08-13 12:47:48 -04001258 self.glyphs = set ()
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001259
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001260 def populate (self, glyphs=[], unicodes=[], text=""):
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001261 self.unicodes_requested.update (unicodes)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001262 if isinstance (text, str):
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001263 text = text.decode ("utf8")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001264 for u in text:
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001265 self.unicodes_requested.add (ord (u))
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001266 self.glyphs_requested.update (glyphs)
Behdad Esfahboda7d22432013-08-13 12:47:48 -04001267 self.glyphs.update (glyphs)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001268
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001269 def pre_prune (self, font):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001270
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001271 for tag in font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001272 if tag == 'GlyphOrder': continue
1273
Behdad Esfahbodfc912be2013-08-13 19:21:17 -04001274 if (tag in self.options.drop_tables or
1275 (tag in self.options.hinting_tables and not self.options.hinting)):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001276 self.log (tag, "dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001277 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001278 continue
1279
1280 clazz = fontTools.ttLib.getTableClass(tag)
1281
1282 if hasattr (clazz, 'prune_pre_subset'):
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001283 table = font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001284 retain = table.prune_pre_subset (self.options)
1285 self.log.lapse ("prune '%s'" % tag)
1286 if not retain:
1287 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001288 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001289 continue
1290 else:
1291 self.log (tag, "pruned")
1292
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001293 def closure_glyphs (self, font):
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001294
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001295 self.glyphs = self.glyphs_requested.copy ()
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001296
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001297 if 'cmap' in font:
1298 font['cmap'].closure_glyphs (self)
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001299 self.glyphs_cmaped = self.glyphs
1300
1301 if self.options.mandatory_glyphs:
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001302 if 'glyf' in font:
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001303 for i in range (4):
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001304 self.glyphs.add (font.getGlyphName (i))
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001305 self.log ("Added first four glyphs to subset")
1306 else:
1307 self.glyphs.add ('.notdef')
1308 self.log ("Added .notdef glyph to subset")
1309
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001310 if 'GSUB' in font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001311 self.log ("Closing glyph list over 'GSUB': %d glyphs before" % len (self.glyphs))
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001312 self.log.glyphs (self.glyphs, font=font)
1313 font['GSUB'].closure_glyphs (self)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001314 self.log ("Closed glyph list over 'GSUB': %d glyphs after" % len (self.glyphs))
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001315 self.log.glyphs (self.glyphs, font=font)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001316 self.log.lapse ("close glyph list over 'GSUB'")
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001317 self.glyphs_gsubed = self.glyphs.copy ()
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001318
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001319 if 'glyf' in font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001320 self.log ("Closing glyph list over 'glyf': %d glyphs before" % len (self.glyphs))
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001321 self.log.glyphs (self.glyphs, font=font)
1322 font['glyf'].closure_glyphs (self)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001323 self.log ("Closed glyph list over 'glyf': %d glyphs after" % len (self.glyphs))
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001324 self.log.glyphs (self.glyphs, font=font)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001325 self.log.lapse ("close glyph list over 'glyf'")
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001326 self.glyphs_glyfed = self.glyphs.copy ()
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001327
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001328 self.glyphs_all = self.glyphs.copy ()
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001329
1330 self.log ("Retaining %d glyphs: " % len (self.glyphs_all))
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001331
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001332 def subset_glyphs (self, font):
1333 for tag in font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001334 if tag == 'GlyphOrder': continue
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001335 clazz = fontTools.ttLib.getTableClass(tag)
1336
Behdad Esfahbode6fc8ca2013-08-13 12:25:31 -04001337 if tag in self.options.no_subset_tables:
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001338 self.log (tag, "subsetting not needed")
1339 elif hasattr (clazz, 'subset_glyphs'):
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001340 table = font[tag]
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -04001341 self.glyphs = self.glyphs_all
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001342 retain = table.subset_glyphs (self)
Behdad Esfahbod033dfcd2013-08-13 11:40:50 -04001343 self.glyphs = self.glyphs_all
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001344 self.log.lapse ("subset '%s'" % tag)
1345 if not retain:
1346 self.log (tag, "subsetted to empty; dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001347 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001348 else:
1349 self.log (tag, "subsetted")
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001350 else:
Behdad Esfahbode6fc8ca2013-08-13 12:25:31 -04001351 self.log (tag, "NOT subset; don't know how to subset; dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001352 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001353
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001354 glyphOrder = font.getGlyphOrder()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001355 glyphOrder = [g for g in glyphOrder if g in self.glyphs_all]
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001356 font.setGlyphOrder (glyphOrder)
1357 font._buildReverseGlyphOrderDict ()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001358 self.log.lapse ("subset GlyphOrder")
1359
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001360 def post_prune (self, font):
1361 for tag in font.keys():
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001362 if tag == 'GlyphOrder': continue
1363 clazz = fontTools.ttLib.getTableClass(tag)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001364 if hasattr (clazz, 'prune_post_subset'):
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001365 table = font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001366 retain = table.prune_post_subset (self.options)
1367 self.log.lapse ("prune '%s'" % tag)
1368 if not retain:
1369 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001370 del font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001371 else:
1372 self.log (tag, "pruned")
1373
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001374 def subset (self, font):
Behdad Esfahbod756af492013-08-01 12:05:26 -04001375
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001376 font.recalcBBoxes = self.options.recalc_bboxes
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001377
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001378 self.pre_prune (font)
1379 self.closure_glyphs (font)
1380 self.subset_glyphs (font)
1381 self.post_prune (font)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001382
Behdad Esfahbod756af492013-08-01 12:05:26 -04001383
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001384import sys, time
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001385
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001386class Logger:
1387
1388 def __init__ (self, verbose=False, xml=False, timing=False):
1389 self.verbose = verbose
1390 self.xml = xml
1391 self.timing = timing
1392 self.last_time = self.start_time = time.time ()
1393
1394 def parse_opts (self, argv):
1395 argv = argv[:]
1396 for v in ['verbose', 'xml', 'timing']:
1397 if "--"+v in argv:
1398 setattr (self, v, True)
1399 argv.remove ("--"+v)
1400 return argv
1401
1402 def __call__ (self, *things):
1403 if not self.verbose:
1404 return
1405 print ' '.join (str (x) for x in things)
1406
1407 def lapse (self, *things):
1408 if not self.timing:
1409 return
1410 new_time = time.time ()
1411 print "Took %0.3fs to %s" % (new_time - self.last_time, ' '.join (str (x) for x in things))
1412 self.last_time = new_time
1413
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001414 def glyphs (self, glyphs, glyph_names=True, font=None):
1415 self ("Names: ", sorted (glyphs))
1416 if font:
Behdad Esfahboddb6d2e92013-08-13 12:42:12 -04001417 reverseGlyphMap = font.getReverseGlyphMap ()
1418 self ("Gids : ", sorted (reverseGlyphMap[g] for g in glyphs))
Behdad Esfahbodf5497842013-08-08 21:57:02 -04001419
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001420 def font (self, font, file=sys.stdout):
1421 if not self.xml:
1422 return
Behdad Esfahbod9a49ead2013-08-13 16:51:59 -04001423 import xmlWriter
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001424 writer = xmlWriter.XMLWriter (file)
1425 font.disassembleInstructions = False # Work around ttx bug
1426 for tag in font.keys():
1427 writer.begintag (tag)
1428 writer.newline ()
1429 font[tag].toXML(writer, font)
1430 writer.endtag (tag)
1431 writer.newline ()
1432
Behdad Esfahbodf6b668e2013-08-13 12:20:59 -04001433
1434def load_font (fontfile, dont_load_glyph_names=False):
1435
1436 # TODO Option for ignoreDecompileErrors?
1437
1438 font = fontTools.ttx.TTFont (fontfile)
1439
1440 # Hack:
1441 #
1442 # If we don't need glyph names, change 'post' class to not try to
1443 # load them. It avoid lots of headache with broken fonts as well
1444 # as loading time.
1445 #
1446 # Ideally ttLib should provide a way to ask it to skip loading
1447 # glyph names. But it currently doesn't provide such a thing.
1448 #
1449 if dont_load_glyph_names:
1450 post = fontTools.ttLib.getTableClass('post')
1451 saved = post.decode_format_2_0
1452 post.decode_format_2_0 = post.decode_format_3_0
1453 f = font['post']
1454 if f.formatType == 2.0:
1455 f.formatType = 3.0
1456 post.decode_format_2_0 = saved
1457
1458 return font
1459
1460
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001461def main (args):
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001462
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001463 log = Logger ()
1464 args = log.parse_opts (args)
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001465
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001466 options = Subsetter.Options ()
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001467 args = options.parse_opts (args, ignore_unknown=['text'])
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001468
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001469 if len (args) < 2:
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001470 print >>sys.stderr, "usage: pyotlss.py font-file glyph..."
1471 sys.exit (1)
1472
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001473 fontfile = args[0]
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001474 args = args[1:]
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001475
Behdad Esfahbodfc912be2013-08-13 19:21:17 -04001476 dont_load_glyph_names = (not options.glyph_names and
1477 all (any (g.startswith (p)
1478 for p in ['gid', 'glyph', 'uni', 'U+'])
1479 for g in args))
Behdad Esfahbodf6b668e2013-08-13 12:20:59 -04001480
1481 font = load_font (fontfile, dont_load_glyph_names=dont_load_glyph_names)
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001482 subsetter = Subsetter (options=options, log=log)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001483 log.lapse ("load font")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001484
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001485 names = font.getGlyphNames()
1486 log.lapse ("loading glyph names")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001487
1488 glyphs = []
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001489 unicodes = []
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001490 text = ""
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001491 for g in args:
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001492 if g in names:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001493 glyphs.append (g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001494 continue
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001495 if g.startswith ('--text='):
1496 text += g[7:]
1497 continue
Behdad Esfahbod9ae5d282013-08-08 21:18:17 -04001498 if g.startswith ('uni') or g.startswith ('U+'):
1499 if g.startswith ('uni') and len (g) > 3:
1500 g = g[3:]
1501 elif g.startswith ('U+') and len (g) > 2:
1502 g = g[2:]
1503 u = int (g, 16)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001504 unicodes.append (u)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001505 continue
1506 if g.startswith ('gid') or g.startswith ('glyph'):
1507 if g.startswith ('gid') and len (g) > 3:
1508 g = g[3:]
1509 elif g.startswith ('glyph') and len (g) > 5:
1510 g = g[5:]
1511 try:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001512 glyphs.append (font.getGlyphName (int (g), requireReal=1))
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001513 except ValueError:
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001514 raise Exception ("Invalid glyph identifier: %s" % g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001515 continue
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001516 raise Exception ("Invalid glyph identifier: %s" % g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001517 log.lapse ("compile glyph list")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001518 log ("Unicodes:", unicodes)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001519 log ("Glyphs:", glyphs)
1520
Behdad Esfahbod9ec52152013-08-13 14:04:44 -04001521 subsetter.populate (glyphs=glyphs, unicodes=unicodes, text=text)
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001522 subsetter.subset (font)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -04001523
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001524 font.save (fontfile + '.subset')
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001525 log.lapse ("compile and save font")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001526
Behdad Esfahbodd1c66ec2013-08-13 12:30:14 -04001527 log.last_time = log.start_time
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001528 log.lapse ("make one with everything (TOTAL TIME)")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001529
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001530 log.font (font)
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001531
1532if __name__ == '__main__':
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001533 main (sys.argv[1:])