blob: 362ac5c3f23686293a5cfc7fd3e77ed4b304292c [file] [log] [blame]
Behdad Esfahbod54660612013-07-21 18:16:55 -04001#!/usr/bin/python
2
3# Python OpenType Layout Subsetter
Behdad Esfahbod0fe6a512013-07-23 11:17:35 -04004#
5# Copyright 2013 Google, Inc. All Rights Reserved.
6#
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18#
19# Google Author(s): Behdad Esfahbod
20#
Behdad Esfahbod54660612013-07-21 18:16:55 -040021
Behdad Esfahbodfa3bc5e2013-07-24 14:37:58 -040022# Try running on PyPy
23try:
24 import numpypy
25except ImportError:
26 pass
27
Behdad Esfahbod54660612013-07-21 18:16:55 -040028import fontTools.ttx
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -040029import struct
Behdad Esfahbod54660612013-07-21 18:16:55 -040030
Behdad Esfahbod54660612013-07-21 18:16:55 -040031
Behdad Esfahbod02b92062013-07-21 18:40:59 -040032def add_method (*clazzes):
Behdad Esfahbod54660612013-07-21 18:16:55 -040033 def wrapper(method):
Behdad Esfahbod02b92062013-07-21 18:40:59 -040034 for clazz in clazzes:
Behdad Esfahbodc0d59592013-07-24 14:41:47 -040035 assert clazz.__name__ != 'DefaultTable', 'Oops, table class not found.'
Behdad Esfahbod02b92062013-07-21 18:40:59 -040036 setattr (clazz, method.func_name, method)
Behdad Esfahbod54660612013-07-21 18:16:55 -040037 return wrapper
38
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040039def unique_sorted (l):
Behdad Esfahbod2d9a0962013-07-31 13:33:31 -040040 return sorted (set (l))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040041
Behdad Esfahbod97e17b82013-07-31 15:59:21 -040042def safeEval(data, eval=eval):
43 """A (kindof) safe replacement for eval."""
44 return eval(data, {"__builtins__":{}}, {})
45
Behdad Esfahbod78661bb2013-07-23 10:23:42 -040046
Behdad Esfahbod54660612013-07-21 18:16:55 -040047@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040048def intersect (self, glyphs):
Behdad Esfahbod610b0552013-07-23 14:52:18 -040049 "Returns ascending list of matching coverage values."
50 return [i for (i,g) in enumerate (self.glyphs) if g in glyphs]
51
52@add_method(fontTools.ttLib.tables.otTables.Coverage)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040053def subset (self, glyphs):
Behdad Esfahbodd821ea02013-07-23 10:50:43 -040054 "Returns ascending list of remaining coverage values."
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040055 indices = self.intersect (glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -040056 self.glyphs = [g for g in self.glyphs if g in glyphs]
57 return indices
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040058
Behdad Esfahbod54660612013-07-21 18:16:55 -040059@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040060def intersect (self, glyphs):
Behdad Esfahbode10803e2013-08-08 21:09:27 -040061 "Returns ascending list of matching class values."
62 return unique_sorted (([0] if any (g not in self.classDefs.items() for g in glyphs) else []) + \
63 [v for g,v in self.classDefs.items() if g in glyphs])
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040064
65@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040066def intersects_class (self, glyphs, klass):
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040067 "Returns true if any of glyphs has requested class."
Behdad Esfahbode10803e2013-08-08 21:09:27 -040068 assert isinstance (klass, int)
Behdad Esfahbod0befd6b2013-08-05 22:47:14 -040069 if klass == 0:
70 if any (g not in self.classDefs.items() for g in glyphs):
71 return True
72 # Fall through
Behdad Esfahbodb8d55882013-07-23 22:17:39 -040073 return any (g in glyphs for g,v in self.classDefs.items() if v == klass)
74
75@add_method(fontTools.ttLib.tables.otTables.ClassDef)
Behdad Esfahbod327dcc32013-07-31 13:50:51 -040076def subset (self, glyphs, remap=False):
Behdad Esfahboddd6fc842013-08-06 11:12:49 -040077 "Returns ascending list of remaining classes. Doesn't reuse class 0."
Behdad Esfahbod54660612013-07-21 18:16:55 -040078 self.classDefs = {g:v for g,v in self.classDefs.items() if g in glyphs}
Behdad Esfahboddd6fc842013-08-06 11:12:49 -040079 indices = unique_sorted ([0] + self.classDefs.values ())
Behdad Esfahbodde71dca2013-07-24 12:40:54 -040080 if remap:
81 self.remap (indices)
82 return indices
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -040083
84@add_method(fontTools.ttLib.tables.otTables.ClassDef)
85def remap (self, class_map):
86 "Remaps classes."
87 self.classDefs = {g:class_map.index (v) for g,v in self.classDefs.items()}
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -040088
Behdad Esfahbod54660612013-07-21 18:16:55 -040089@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -040090def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -040091 if self.Format in [1, 2]:
Behdad Esfahbod254442b2013-07-31 14:20:13 -040092 return [v for g,v in self.mapping.items() if g in s.glyphs]
Behdad Esfahbod610b0552013-07-23 14:52:18 -040093 else:
94 assert 0, "unknown format: %s" % self.Format
95
96@add_method(fontTools.ttLib.tables.otTables.SingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -040097def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -040098 if self.Format in [1, 2]:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -040099 self.mapping = {g:v for g,v in self.mapping.items() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400100 return bool (self.mapping)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400101 else:
102 assert 0, "unknown format: %s" % self.Format
103
104@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400105def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400106 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400107 indices = self.Coverage.intersect (s.glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400108 return sum ((self.Sequence[i].Substitute for i in indices), [])
109 else:
110 assert 0, "unknown format: %s" % self.Format
111
112@add_method(fontTools.ttLib.tables.otTables.MultipleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400113def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400114 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400115 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400116 self.Sequence = [self.Sequence[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400117 self.SequenceCount = len (self.Sequence)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400118 return bool (self.SequenceCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400119 else:
120 assert 0, "unknown format: %s" % self.Format
121
122@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400123def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400124 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400125 return sum ((v for g,v in self.alternates.items() if g in s.glyphs), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400126 else:
127 assert 0, "unknown format: %s" % self.Format
128
129@add_method(fontTools.ttLib.tables.otTables.AlternateSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400130def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400131 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400132 self.alternates = {g:v for g,v in self.alternates.items() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400133 return bool (self.alternates)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400134 else:
135 assert 0, "unknown format: %s" % self.Format
136
137@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400138def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400139 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400140 return sum (([seq.LigGlyph for seq in seqs if all(c in s.glyphs for c in seq.Component)]
141 for g,seqs in self.ligatures.items() if g in s.glyphs), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400142 else:
143 assert 0, "unknown format: %s" % self.Format
144
145@add_method(fontTools.ttLib.tables.otTables.LigatureSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400146def subset_glyphs (self, s):
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400147 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400148 self.ligatures = {g:v for g,v in self.ligatures.items() if g in s.glyphs}
149 self.ligatures = {g:[seq for seq in seqs if all(c in s.glyphs for c in seq.Component)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400150 for g,seqs in self.ligatures.items()}
151 self.ligatures = {g:v for g,v in self.ligatures.items() if v}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400152 return bool (self.ligatures)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400153 else:
154 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400155
Behdad Esfahbod54660612013-07-21 18:16:55 -0400156@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400157def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400158 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400159 indices = self.Coverage.intersect (s.glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400160 if not indices or \
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400161 not all (c.intersect (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400162 return []
163 return [self.Substitute[i] for i in indices]
164 else:
165 assert 0, "unknown format: %s" % self.Format
166
167@add_method(fontTools.ttLib.tables.otTables.ReverseChainSingleSubst)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400168def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400169 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400170 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400171 self.Substitute = [self.Substitute[i] for i in indices]
172 self.GlyphCount = len (self.Substitute)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400173 return bool (self.GlyphCount and all (c.subset (s.glyphs) for c in self.LookAheadCoverage + self.BacktrackCoverage))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400174 else:
175 assert 0, "unknown format: %s" % self.Format
176
177@add_method(fontTools.ttLib.tables.otTables.SinglePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400178def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400179 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400180 return len (self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400181 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400182 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400183 self.Value = [self.Value[i] for i in indices]
184 self.ValueCount = len (self.Value)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400185 return bool (self.ValueCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400186 else:
187 assert 0, "unknown format: %s" % self.Format
188
189@add_method(fontTools.ttLib.tables.otTables.PairPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400190def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400191 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400192 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400193 self.PairSet = [self.PairSet[i] for i in indices]
194 for p in self.PairSet:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400195 p.PairValueRecord = [r for r in p.PairValueRecord if r.SecondGlyph in s.glyphs]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400196 p.PairValueCount = len (p.PairValueRecord)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400197 self.PairSet = [p for p in self.PairSet if p.PairValueCount]
Behdad Esfahbod54660612013-07-21 18:16:55 -0400198 self.PairSetCount = len (self.PairSet)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400199 return bool (self.PairSetCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400200 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400201 class1_map = self.ClassDef1.subset (s.glyphs, remap=True)
202 class2_map = self.ClassDef2.subset (s.glyphs, remap=True)
Behdad Esfahbod4aa6ce32013-07-22 12:15:36 -0400203 self.Class1Record = [self.Class1Record[i] for i in class1_map]
204 for c in self.Class1Record:
205 c.Class2Record = [c.Class2Record[i] for i in class2_map]
206 self.Class1Count = len (class1_map)
207 self.Class2Count = len (class2_map)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400208 return bool (self.Class1Count and self.Class2Count and self.Coverage.subset (s.glyphs))
Behdad Esfahbod54660612013-07-21 18:16:55 -0400209 else:
210 assert 0, "unknown format: %s" % self.Format
211
212@add_method(fontTools.ttLib.tables.otTables.CursivePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400213def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400214 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400215 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400216 self.EntryExitRecord = [self.EntryExitRecord[i] for i in indices]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400217 self.EntryExitCount = len (self.EntryExitRecord)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400218 return bool (self.EntryExitCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400219 else:
220 assert 0, "unknown format: %s" % self.Format
221
222@add_method(fontTools.ttLib.tables.otTables.MarkBasePos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400223def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400224 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400225 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400226 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
227 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400228 base_indices = self.BaseCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400229 self.BaseArray.BaseRecord = [self.BaseArray.BaseRecord[i] for i in base_indices]
230 self.BaseArray.BaseCount = len (self.BaseArray.BaseRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400231 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400232 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400233 self.ClassCount = len (class_indices)
234 for m in self.MarkArray.MarkRecord:
235 m.Class = class_indices.index (m.Class)
236 for b in self.BaseArray.BaseRecord:
237 b.BaseAnchor = [b.BaseAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400238 return bool (self.ClassCount and self.MarkArray.MarkCount and self.BaseArray.BaseCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400239 else:
240 assert 0, "unknown format: %s" % self.Format
241
242@add_method(fontTools.ttLib.tables.otTables.MarkLigPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400243def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400244 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400245 mark_indices = self.MarkCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400246 self.MarkArray.MarkRecord = [self.MarkArray.MarkRecord[i] for i in mark_indices]
247 self.MarkArray.MarkCount = len (self.MarkArray.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400248 ligature_indices = self.LigatureCoverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400249 self.LigatureArray.LigatureAttach = [self.LigatureArray.LigatureAttach[i] for i in ligature_indices]
250 self.LigatureArray.LigatureCount = len (self.LigatureArray.LigatureAttach)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400251 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400252 class_indices = unique_sorted (v.Class for v in self.MarkArray.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400253 self.ClassCount = len (class_indices)
254 for m in self.MarkArray.MarkRecord:
255 m.Class = class_indices.index (m.Class)
256 for l in self.LigatureArray.LigatureAttach:
257 for c in l.ComponentRecord:
258 c.LigatureAnchor = [c.LigatureAnchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400259 return bool (self.ClassCount and self.MarkArray.MarkCount and self.LigatureArray.LigatureCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400260 else:
261 assert 0, "unknown format: %s" % self.Format
262
263@add_method(fontTools.ttLib.tables.otTables.MarkMarkPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400264def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400265 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400266 mark1_indices = self.Mark1Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400267 self.Mark1Array.MarkRecord = [self.Mark1Array.MarkRecord[i] for i in mark1_indices]
268 self.Mark1Array.MarkCount = len (self.Mark1Array.MarkRecord)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400269 mark2_indices = self.Mark2Coverage.subset (s.glyphs)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400270 self.Mark2Array.Mark2Record = [self.Mark2Array.Mark2Record[i] for i in mark2_indices]
271 self.Mark2Array.MarkCount = len (self.Mark2Array.Mark2Record)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400272 # Prune empty classes
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400273 class_indices = unique_sorted (v.Class for v in self.Mark1Array.MarkRecord)
Behdad Esfahbodc6396b72013-07-22 12:31:33 -0400274 self.ClassCount = len (class_indices)
275 for m in self.Mark1Array.MarkRecord:
276 m.Class = class_indices.index (m.Class)
277 for b in self.Mark2Array.Mark2Record:
278 b.Mark2Anchor = [b.Mark2Anchor[i] for i in class_indices]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400279 return bool (self.ClassCount and self.Mark1Array.MarkCount and self.Mark2Array.MarkCount)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400280 else:
281 assert 0, "unknown format: %s" % self.Format
282
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400283@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
284 fontTools.ttLib.tables.otTables.MultipleSubst,
285 fontTools.ttLib.tables.otTables.AlternateSubst,
286 fontTools.ttLib.tables.otTables.LigatureSubst,
287 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
288 fontTools.ttLib.tables.otTables.SinglePos,
289 fontTools.ttLib.tables.otTables.PairPos,
290 fontTools.ttLib.tables.otTables.CursivePos,
291 fontTools.ttLib.tables.otTables.MarkBasePos,
292 fontTools.ttLib.tables.otTables.MarkLigPos,
293 fontTools.ttLib.tables.otTables.MarkMarkPos)
294def subset_lookups (self, lookup_indices):
295 pass
296
297@add_method(fontTools.ttLib.tables.otTables.SingleSubst,
298 fontTools.ttLib.tables.otTables.MultipleSubst,
299 fontTools.ttLib.tables.otTables.AlternateSubst,
300 fontTools.ttLib.tables.otTables.LigatureSubst,
301 fontTools.ttLib.tables.otTables.ReverseChainSingleSubst,
302 fontTools.ttLib.tables.otTables.SinglePos,
303 fontTools.ttLib.tables.otTables.PairPos,
304 fontTools.ttLib.tables.otTables.CursivePos,
305 fontTools.ttLib.tables.otTables.MarkBasePos,
306 fontTools.ttLib.tables.otTables.MarkLigPos,
307 fontTools.ttLib.tables.otTables.MarkMarkPos)
308def collect_lookups (self):
309 return []
310
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400311@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
312 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
313def __classify_context (self):
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400314
315 class ContextHelper:
316 def __init__ (self, klass, Format):
317 if klass.__name__.endswith ('Subst'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400318 Typ = 'Sub'
319 Type = 'Subst'
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400320 else:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400321 Typ = 'Pos'
322 Type = 'Pos'
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400323 if klass.__name__.startswith ('Chain'):
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400324 Chain = 'Chain'
325 else:
326 Chain = ''
327 ChainTyp = Chain+Typ
328
329 self.Typ = Typ
330 self.Type = Type
331 self.Chain = Chain
332 self.ChainTyp = ChainTyp
333
334 self.LookupRecord = Type+'LookupRecord'
335
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400336 if Format == 1:
337 ContextData = None
338 ChainContextData = None
339 RuleData = lambda r: r.Input
340 ChainRuleData = lambda r: r.Backtrack + r.Input + r.LookAhead
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400341 SetRuleData = None
342 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400343 elif Format == 2:
Behdad Esfahbode3f20732013-07-24 11:26:43 -0400344 ContextData = lambda r: (r.ClassDef,)
345 ChainContextData = lambda r: (r.LookAheadClassDef, r.InputClassDef, r.BacktrackClassDef)
346 RuleData = lambda r: (r.Class,)
347 ChainRuleData = lambda r: (r.LookAhead, r.Input, r.Backtrack)
348 def SetRuleData (r, d): (r.Class,) = d
349 def ChainSetRuleData (r, d): (r.LookAhead, r.Input, r.Backtrack) = d
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400350 elif Format == 3:
351 ContextData = None
352 ChainContextData = None
353 RuleData = lambda r: r.Coverage
354 ChainRuleData = lambda r: r.LookAheadCoverage + r.InputCoverage + r.BacktrackCoverage
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400355 SetRuleData = None
356 ChainSetRuleData = None
Behdad Esfahbod452ab6c2013-07-23 22:57:43 -0400357 else:
358 assert 0, "unknown format: %s" % Format
359
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400360 if Chain:
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400361 self.ContextData = ChainContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400362 self.RuleData = ChainRuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400363 self.SetRuleData = ChainSetRuleData
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400364 else:
Behdad Esfahbod707a37a2013-07-23 21:08:26 -0400365 self.ContextData = ContextData
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400366 self.RuleData = RuleData
Behdad Esfahbod44fc6f62013-07-24 11:24:39 -0400367 self.SetRuleData = SetRuleData
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400368
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400369 if Format == 1:
370 self.Rule = ChainTyp+'Rule'
371 self.RuleCount = ChainTyp+'RuleCount'
372 self.RuleSet = ChainTyp+'RuleSet'
373 self.RuleSetCount = ChainTyp+'RuleSetCount'
374 elif Format == 2:
375 self.Rule = ChainTyp+'ClassRule'
376 self.RuleCount = ChainTyp+'ClassRuleCount'
377 self.RuleSet = ChainTyp+'ClassSet'
378 self.RuleSetCount = ChainTyp+'ClassSetCount'
Behdad Esfahbod89987002013-07-23 23:07:42 -0400379
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400380 self.ClassDef = 'InputClassDef' if Chain else 'ClassDef'
Behdad Esfahbod27108392013-07-23 16:40:47 -0400381
Behdad Esfahbodb178dca2013-07-23 22:51:50 -0400382 if self.Format not in [1, 2, 3]:
383 return None # Don't shoot the messenger; let it go
384 if not hasattr (self.__class__, "__ContextHelpers"):
385 self.__class__.__ContextHelpers = {}
386 if self.Format not in self.__class__.__ContextHelpers:
387 self.__class__.__ContextHelpers[self.Format] = ContextHelper (self.__class__, self.Format)
388 return self.__class__.__ContextHelpers[self.Format]
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400389
Behdad Esfahbodf2b6d9c2013-07-23 17:31:54 -0400390@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400391def closure_glyphs (self, s):
Behdad Esfahbod1ab2dbf2013-07-23 17:17:21 -0400392 c = self.__classify_context ()
393
Behdad Esfahbod00776972013-07-23 15:33:00 -0400394 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400395 indices = self.Coverage.intersect (s.glyphs)
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400396 rss = getattr (self, c.RuleSet)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400397 return sum ((s.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs (s) \
Behdad Esfahboddd6fc842013-08-06 11:12:49 -0400398 for i in indices if rss[i] \
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400399 for r in getattr (rss[i], c.Rule) \
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400400 if r and all (g in s.glyphs for g in c.RuleData (r)) \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400401 for ll in getattr (r, c.LookupRecord) if ll \
Behdad Esfahbodeeca9822013-07-23 17:42:17 -0400402 ), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400403 elif self.Format == 2:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400404 if not self.Coverage.intersect (s.glyphs):
Behdad Esfahbod31084302013-07-23 22:22:38 -0400405 return []
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400406 # XXX Intersect glyphs with coverage before going further
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400407 indices = getattr (self, c.ClassDef).intersect (s.glyphs)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400408 rss = getattr (self, c.RuleSet)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400409 return sum ((s.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs (s) \
Behdad Esfahboddd6fc842013-08-06 11:12:49 -0400410 for i in indices if rss[i] \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400411 for r in getattr (rss[i], c.Rule) \
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400412 if r and all (all (cd.intersects_class (s.glyphs, k) for k in klist) \
413 for cd,klist in zip (c.ContextData (self), c.RuleData (r))) \
Behdad Esfahbodb8d55882013-07-23 22:17:39 -0400414 for ll in getattr (r, c.LookupRecord) if ll \
415 ), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400416 elif self.Format == 3:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400417 if not all (x.intersect (s.glyphs) for x in c.RuleData (self)):
Behdad Esfahbod00776972013-07-23 15:33:00 -0400418 return []
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400419 return sum ((s.table.LookupList.Lookup[ll.LookupListIndex].closure_glyphs (s) \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400420 for ll in getattr (self, c.LookupRecord) if ll), [])
Behdad Esfahbod00776972013-07-23 15:33:00 -0400421 else:
422 assert 0, "unknown format: %s" % self.Format
423
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400424@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ContextPos,
425 fontTools.ttLib.tables.otTables.ChainContextSubst, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400426def subset_glyphs (self, s):
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400427 c = self.__classify_context ()
428
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400429 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400430 indices = self.Coverage.subset (s.glyphs)
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400431 rss = getattr (self, c.RuleSet)
432 rss = [rss[i] for i in indices]
433 for rs in rss:
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400434 if rs:
435 ss = getattr (rs, c.Rule)
436 ss = [r for r in ss \
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400437 if r and all (g in s.glyphs for g in c.RuleData (r))]
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400438 setattr (rs, c.Rule, ss)
439 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbodcbba4a62013-07-23 17:27:18 -0400440 # Prune empty subrulesets
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400441 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
Behdad Esfahbodd8c7e102013-07-23 17:07:06 -0400442 setattr (self, c.RuleSet, rss)
443 setattr (self, c.RuleSetCount, len (rss))
444 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400445 elif self.Format == 2:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400446 if not self.Coverage.subset (s.glyphs):
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400447 return False
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400448 # XXX Intersect glyphs with coverage before going further
449 indices = getattr (self, c.ClassDef).subset (s.glyphs, remap=False)
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400450 rss = getattr (self, c.RuleSet)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400451 rss = [rss[i] for i in indices]
452 ContextData = c.ContextData (self)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400453 klass_maps = [x.subset (s.glyphs, remap=True) for x in ContextData]
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400454 for rs in rss:
455 if rs:
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400456 ss = getattr (rs, c.Rule)
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400457 ss = [r for r in ss \
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400458 if r and all (all (k in klass_map for k in klist) \
459 for klass_map,klist in zip (klass_maps, c.RuleData (r)))]
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400460 setattr (rs, c.Rule, ss)
461 setattr (rs, c.RuleCount, len (ss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400462
463 # Remap rule classes
464 for r in ss:
Behdad Esfahbode10803e2013-08-08 21:09:27 -0400465 c.SetRuleData (r, [[klass_map.index (k) for k in klist] \
466 for klass_map,klist in zip (klass_maps, c.RuleData (r))])
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400467 # Prune empty subrulesets
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400468 rss = [rs for rs in rss if rs and getattr (rs, c.Rule)]
469 setattr (self, c.RuleSet, rss)
470 setattr (self, c.RuleSetCount, len (rss))
Behdad Esfahbode9a3bd62013-07-23 22:41:11 -0400471 return bool (rss)
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400472 elif self.Format == 3:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400473 return all (x.subset (s.glyphs) for x in c.RuleData (self))
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400474 else:
475 assert 0, "unknown format: %s" % self.Format
Behdad Esfahbod54660612013-07-21 18:16:55 -0400476
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400477@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
478 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400479def subset_lookups (self, lookup_indices):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400480 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400481
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400482 if self.Format in [1, 2]:
Behdad Esfahbod9e735722013-07-23 16:35:23 -0400483 for rs in getattr (self, c.RuleSet):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400484 if rs:
485 for r in getattr (rs, c.Rule):
486 if r:
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400487 setattr (r, c.LookupRecord, [ll for ll in getattr (r, c.LookupRecord) if ll \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400488 if ll.LookupListIndex in lookup_indices])
489 for ll in getattr (r, c.LookupRecord):
490 if ll:
491 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400492 elif self.Format == 3:
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400493 setattr (self, c.LookupRecord, [ll for ll in getattr (self, c.LookupRecord) if ll \
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400494 if ll.LookupListIndex in lookup_indices])
495 for ll in getattr (self, c.LookupRecord):
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400496 if ll:
497 ll.LookupListIndex = lookup_indices.index (ll.LookupListIndex)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400498 else:
499 assert 0, "unknown format: %s" % self.Format
500
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400501@add_method(fontTools.ttLib.tables.otTables.ContextSubst, fontTools.ttLib.tables.otTables.ChainContextSubst,
502 fontTools.ttLib.tables.otTables.ContextPos, fontTools.ttLib.tables.otTables.ChainContextPos)
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400503def collect_lookups (self):
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400504 c = self.__classify_context ()
Behdad Esfahbod44c2b3c2013-07-23 16:00:32 -0400505
Behdad Esfahbod1f573632013-07-23 23:04:43 -0400506 if self.Format in [1, 2]:
Behdad Esfahbod27108392013-07-23 16:40:47 -0400507 return [ll.LookupListIndex \
Behdad Esfahbodbac31f52013-07-23 23:00:39 -0400508 for rs in getattr (self, c.RuleSet) if rs \
509 for r in getattr (rs, c.Rule) if r \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400510 for ll in getattr (r, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400511 elif self.Format == 3:
Behdad Esfahbod6870f8a2013-07-23 16:18:30 -0400512 return [ll.LookupListIndex \
Behdad Esfahbod7c225a62013-07-23 21:33:13 -0400513 for ll in getattr (self, c.LookupRecord) if ll]
Behdad Esfahbod59dfc132013-07-23 15:39:20 -0400514 else:
515 assert 0, "unknown format: %s" % self.Format
516
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400517@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400518def closure_glyphs (self, s):
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400519 if self.Format == 1:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400520 return self.ExtSubTable.closure_glyphs (s)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400521 else:
522 assert 0, "unknown format: %s" % self.Format
523
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400524@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400525def subset_glyphs (self, s):
Behdad Esfahbod54660612013-07-21 18:16:55 -0400526 if self.Format == 1:
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400527 return self.ExtSubTable.subset_glyphs (s)
Behdad Esfahbod54660612013-07-21 18:16:55 -0400528 else:
529 assert 0, "unknown format: %s" % self.Format
530
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400531@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
532def subset_lookups (self, lookup_indices):
533 if self.Format == 1:
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400534 return self.ExtSubTable.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400535 else:
536 assert 0, "unknown format: %s" % self.Format
537
538@add_method(fontTools.ttLib.tables.otTables.ExtensionSubst, fontTools.ttLib.tables.otTables.ExtensionPos)
539def collect_lookups (self):
540 if self.Format == 1:
541 return self.ExtSubTable.collect_lookups ()
542 else:
543 assert 0, "unknown format: %s" % self.Format
544
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400545@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400546def closure_glyphs (self, s):
547 return sum ((st.closure_glyphs (s) for st in self.SubTable if st), [])
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400548
549@add_method(fontTools.ttLib.tables.otTables.Lookup)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400550def subset_glyphs (self, s):
551 self.SubTable = [st for st in self.SubTable if st and st.subset_glyphs (s)]
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400552 self.SubTableCount = len (self.SubTable)
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400553 return bool (self.SubTableCount)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400554
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400555@add_method(fontTools.ttLib.tables.otTables.Lookup)
556def subset_lookups (self, lookup_indices):
557 for s in self.SubTable:
558 s.subset_lookups (lookup_indices)
559
560@add_method(fontTools.ttLib.tables.otTables.Lookup)
561def collect_lookups (self):
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400562 return unique_sorted (sum ((st.collect_lookups () for st in self.SubTable if st), []))
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400563
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400564@add_method(fontTools.ttLib.tables.otTables.LookupList)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400565def subset_glyphs (self, s):
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400566 "Returns the indices of nonempty lookups."
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400567 return [i for (i,l) in enumerate (self.Lookup) if l and l.subset_glyphs (s)]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400568
569@add_method(fontTools.ttLib.tables.otTables.LookupList)
570def subset_lookups (self, lookup_indices):
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400571 self.Lookup = [self.Lookup[i] for i in lookup_indices if i < self.LookupCount]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400572 self.LookupCount = len (self.Lookup)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400573 for l in self.Lookup:
574 l.subset_lookups (lookup_indices)
575
576@add_method(fontTools.ttLib.tables.otTables.LookupList)
577def closure_lookups (self, lookup_indices):
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400578 lookup_indices = unique_sorted (lookup_indices)
579 recurse = lookup_indices
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400580 while True:
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400581 recurse_lookups = sum ((self.Lookup[i].collect_lookups () for i in recurse if i < self.LookupCount), [])
582 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 -0400583 if not recurse_lookups:
Behdad Esfahbodbb7e2132013-07-23 13:48:35 -0400584 return unique_sorted (lookup_indices)
585 recurse_lookups = unique_sorted (recurse_lookups)
586 lookup_indices.extend (recurse_lookups)
587 recurse = recurse_lookups
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400588
589@add_method(fontTools.ttLib.tables.otTables.Feature)
590def subset_lookups (self, lookup_indices):
591 self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices]
592 # Now map them.
593 self.LookupListIndex = [lookup_indices.index (l) for l in self.LookupListIndex]
594 self.LookupCount = len (self.LookupListIndex)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -0400595 return self.LookupCount
Behdad Esfahbod54660612013-07-21 18:16:55 -0400596
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400597@add_method(fontTools.ttLib.tables.otTables.Feature)
598def collect_lookups (self):
599 return self.LookupListIndex[:]
600
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400601@add_method(fontTools.ttLib.tables.otTables.FeatureList)
602def subset_lookups (self, lookup_indices):
603 "Returns the indices of nonempty features."
604 feature_indices = [i for (i,f) in enumerate (self.FeatureRecord) if f.Feature.subset_lookups (lookup_indices)]
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400605 self.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400606 return feature_indices
607
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400608@add_method(fontTools.ttLib.tables.otTables.FeatureList)
609def collect_lookups (self, feature_indices):
610 return unique_sorted (sum ((self.FeatureRecord[i].Feature.collect_lookups () for i in feature_indices
611 if i < self.FeatureCount), []))
612
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400613@add_method(fontTools.ttLib.tables.otTables.FeatureList)
614def subset_features (self, feature_indices):
615 self.FeatureRecord = [self.FeatureRecord[i] for i in feature_indices]
616 self.FeatureCount = len (self.FeatureRecord)
617 return bool (self.FeatureCount)
618
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400619@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
620def subset_features (self, feature_indices):
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400621 if self.ReqFeatureIndex in feature_indices:
622 self.ReqFeatureIndex = feature_indices.index (self.ReqFeatureIndex)
623 else:
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400624 self.ReqFeatureIndex = 65535
625 self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod69ce1502013-07-22 18:00:31 -0400626 # Now map them.
627 self.FeatureIndex = [feature_indices.index (f) for f in self.FeatureIndex if f in feature_indices]
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400628 self.FeatureCount = len (self.FeatureIndex)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400629 return bool (self.FeatureCount or self.ReqFeatureIndex != 65535)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400630
631@add_method(fontTools.ttLib.tables.otTables.DefaultLangSys, fontTools.ttLib.tables.otTables.LangSys)
632def collect_features (self):
633 feature_indices = self.FeatureIndex[:]
634 if self.ReqFeatureIndex != 65535:
635 feature_indices.append (self.ReqFeatureIndex)
636 return unique_sorted (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400637
638@add_method(fontTools.ttLib.tables.otTables.Script)
639def subset_features (self, feature_indices):
640 if self.DefaultLangSys and not self.DefaultLangSys.subset_features (feature_indices):
641 self.DefaultLangSys = None
642 self.LangSysRecord = [l for l in self.LangSysRecord if l.LangSys.subset_features (feature_indices)]
643 self.LangSysCount = len (self.LangSysRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400644 return bool (self.LangSysCount or self.DefaultLangSys)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400645
646@add_method(fontTools.ttLib.tables.otTables.Script)
647def collect_features (self):
Behdad Esfahbod2307c8b2013-07-23 11:18:13 -0400648 feature_indices = [l.LangSys.collect_features () for l in self.LangSysRecord]
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400649 if self.DefaultLangSys:
650 feature_indices.append (self.DefaultLangSys.collect_features ())
651 return unique_sorted (sum (feature_indices, []))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400652
653@add_method(fontTools.ttLib.tables.otTables.ScriptList)
654def subset_features (self, feature_indices):
655 self.ScriptRecord = [s for s in self.ScriptRecord if s.Script.subset_features (feature_indices)]
656 self.ScriptCount = len (self.ScriptRecord)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400657 return bool (self.ScriptCount)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400658
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400659@add_method(fontTools.ttLib.tables.otTables.ScriptList)
660def collect_features (self):
661 return unique_sorted (sum ((s.Script.collect_features () for s in self.ScriptRecord), []))
662
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400663@add_method(fontTools.ttLib.getTableClass('GSUB'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400664def closure_glyphs (self, s):
665 s.table = self.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400666 feature_indices = self.table.ScriptList.collect_features ()
667 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400668 orig_glyphs = s.glyphs
669 glyphs = unique_sorted (s.glyphs)
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400670 while True:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400671 s.glyphs = glyphs
672 additions = (sum ((self.table.LookupList.Lookup[i].closure_glyphs (s) \
Behdad Esfahbodafae8322013-07-24 18:57:06 -0400673 for i in lookup_indices if i < self.table.LookupList.LookupCount), []))
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400674 additions = unique_sorted (g for g in additions if g not in glyphs)
675 if not additions:
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400676 s.glyphs = orig_glyphs
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400677 return glyphs
678 glyphs.extend (additions)
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400679 del s.table
Behdad Esfahbod610b0552013-07-23 14:52:18 -0400680
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400681@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400682def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400683 s.glyphs = s.glyphs_gsubed
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400684 lookup_indices = self.table.LookupList.subset_glyphs (s)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400685 self.subset_lookups (lookup_indices)
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400686 self.prune_lookups ()
687 return True
Behdad Esfahbod02b92062013-07-21 18:40:59 -0400688
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400689@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400690def subset_lookups (self, lookup_indices):
691 "Retrains specified lookups, then removes empty features, language systems, and scripts."
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400692 self.table.LookupList.subset_lookups (lookup_indices)
693 feature_indices = self.table.FeatureList.subset_lookups (lookup_indices)
694 self.table.ScriptList.subset_features (feature_indices)
Behdad Esfahbod77cda412013-07-22 11:46:50 -0400695
Behdad Esfahbod78661bb2013-07-23 10:23:42 -0400696@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
697def prune_lookups (self):
698 "Remove unreferenced lookups"
699 feature_indices = self.table.ScriptList.collect_features ()
700 lookup_indices = self.table.FeatureList.collect_lookups (feature_indices)
701 lookup_indices = self.table.LookupList.closure_lookups (lookup_indices)
702 self.subset_lookups (lookup_indices)
703
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400704@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
705def subset_feature_tags (self, feature_tags):
706 feature_indices = [i for (i,f) in enumerate (self.table.FeatureList.FeatureRecord) if f.FeatureTag in feature_tags]
707 self.table.FeatureList.subset_features (feature_indices)
708 self.table.ScriptList.subset_features (feature_indices)
709
710@add_method(fontTools.ttLib.getTableClass('GSUB'), fontTools.ttLib.getTableClass('GPOS'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400711def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400712 if options.layout_features and '*' not in options.layout_features:
713 self.subset_feature_tags (options.layout_features)
Behdad Esfahbod356c42e2013-07-23 12:10:46 -0400714 self.prune_lookups ()
715 return True
716
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400717@add_method(fontTools.ttLib.getTableClass('GDEF'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400718def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400719 glyphs = s.glyphs_gsubed
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400720 table = self.table
721 if table.LigCaretList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400722 indices = table.LigCaretList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400723 table.LigCaretList.LigGlyph = [table.LigCaretList.LigGlyph[i] for i in indices]
724 table.LigCaretList.LigGlyphCount = len (table.LigCaretList.LigGlyph)
725 if not table.LigCaretList.LigGlyphCount:
726 table.LigCaretList = None
727 if table.MarkAttachClassDef:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400728 table.MarkAttachClassDef.classDefs = {g:v for g,v in table.MarkAttachClassDef.classDefs.items() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400729 if not table.MarkAttachClassDef.classDefs:
730 table.MarkAttachClassDef = None
731 if table.GlyphClassDef:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400732 table.GlyphClassDef.classDefs = {g:v for g,v in table.GlyphClassDef.classDefs.items() if g in glyphs}
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400733 if not table.GlyphClassDef.classDefs:
734 table.GlyphClassDef = None
735 if table.AttachList:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400736 indices = table.AttachList.Coverage.subset (glyphs)
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400737 table.AttachList.AttachPoint = [table.AttachList.AttachPoint[i] for i in indices]
738 table.AttachList.GlyphCount = len (table.AttachList.AttachPoint)
739 if not table.AttachList.GlyphCount:
740 table.AttachList = None
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400741 return bool (table.LigCaretList or table.MarkAttachClassDef or table.GlyphClassDef or table.AttachList)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400742
Behdad Esfahbodfd3923e2013-07-22 12:48:17 -0400743@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbodd4e33a72013-07-24 18:51:05 -0400744def prune_pre_subset (self, options):
745 # Prune unknown kern table types
746 self.kernTables = [t for t in self.kernTables if hasattr (t, 'kernTable')]
747 return bool (self.kernTables)
748
749@add_method(fontTools.ttLib.getTableClass('kern'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400750def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400751 glyphs = s.glyphs_gsubed
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400752 for t in self.kernTables:
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400753 t.kernTable = {(a,b):v for ((a,b),v) in t.kernTable.items() if a in glyphs and b in glyphs}
Behdad Esfahbod5270ec42013-07-22 12:57:02 -0400754 self.kernTables = [t for t in self.kernTables if t.kernTable]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400755 return bool (self.kernTables)
Behdad Esfahbodefb984a2013-07-21 22:26:16 -0400756
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400757@add_method(fontTools.ttLib.getTableClass('hmtx'), fontTools.ttLib.getTableClass('vmtx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400758def subset_glyphs (self, s):
759 self.metrics = {g:v for g,v in self.metrics.items() if g in s.glyphs}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400760 return bool (self.metrics)
Behdad Esfahbodc7160442013-07-22 14:29:08 -0400761
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400762@add_method(fontTools.ttLib.getTableClass('hdmx'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400763def subset_glyphs (self, s):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400764 self.hdmx = {sz:{g:v for g,v in l.items() if g in s.glyphs} for (sz,l) in self.hdmx.items()}
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400765 return bool (self.hdmx)
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -0400766
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400767@add_method(fontTools.ttLib.getTableClass('VORG'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400768def subset_glyphs (self, s):
769 self.VOriginRecords = {g:v for g,v in self.VOriginRecords.items() if g in s.glyphs}
Behdad Esfahbode45d6af2013-07-22 15:29:17 -0400770 self.numVertOriginYMetrics = len (self.VOriginRecords)
771 return True # Never drop; has default metrics
772
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400773@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod8c486d82013-07-24 13:34:47 -0400774def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400775 if not options.glyph_names:
Behdad Esfahbod42648242013-07-23 12:56:06 -0400776 self.formatType = 3.0
777 return True
778
779@add_method(fontTools.ttLib.getTableClass('post'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400780def subset_glyphs (self, s):
Behdad Esfahbod42648242013-07-23 12:56:06 -0400781 self.extraNames = [] # This seems to do it
Behdad Esfahbodc9dec9d2013-07-23 10:28:47 -0400782 return True
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400783
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400784# Copied from _g_l_y_f.py
785ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes
786ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points
787ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true
788WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0
789NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!)
790MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one
791WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy
792WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11
793WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow
794USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph
795OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts
796SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple)
797UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS)
798
799@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
800def getComponentNamesFast (self, glyfTable):
801 if struct.unpack(">h", self.data[:2])[0] >= 0:
802 return [] # Not composite
803 data = self.data
804 i = 10
805 components = []
806 more = 1
807 while more:
808 flags, glyphID = struct.unpack(">HH", data[i:i+4])
809 i += 4
810 flags = int(flags)
811 components.append (glyfTable.getGlyphName (int (glyphID)))
812
813 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
814 else: i += 2
815 if flags & WE_HAVE_A_SCALE: i += 2
816 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
817 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
818 more = flags & MORE_COMPONENTS
819 return components
820
821@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
822def remapComponentsFast (self, indices):
823 if struct.unpack(">h", self.data[:2])[0] >= 0:
824 return # Not composite
825 data = bytearray (self.data)
826 i = 10
827 more = 1
828 while more:
829 flags = (data[i] << 8) | data[i+1]
830 glyphID = (data[i+2] << 8) | data[i+3]
831 # Remap
832 glyphID = indices.index (glyphID)
833 data[i+2] = glyphID >> 8
834 data[i+3] = glyphID & 0xFF
835 i += 4
836 flags = int(flags)
837
838 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
839 else: i += 2
840 if flags & WE_HAVE_A_SCALE: i += 2
841 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
842 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
843 more = flags & MORE_COMPONENTS
844 self.data = str (data)
845
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400846@add_method(fontTools.ttLib.getTableModule('glyf').Glyph)
847def dropInstructionsFast (self):
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400848 numContours = struct.unpack(">h", self.data[:2])[0]
849 data = bytearray (self.data)
850 i = 10
851 if numContours >= 0:
852 i += 2 * numContours # endPtsOfContours
853 instructionLen = (data[i] << 8) | data[i+1]
854 # Zero it
855 data[i] = data [i+1] = 0
856 i += 2
Behdad Esfahbod0fb69882013-07-24 17:25:35 -0400857 if instructionLen:
858 # Splice it out
859 data = data[:i] + data[i+instructionLen:]
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400860 else:
861 more = 1
862 while more:
863 flags = (data[i] << 8) | data[i+1]
864 # Turn instruction flag off
865 flags &= ~WE_HAVE_INSTRUCTIONS
866 data[i+0] = flags >> 8
867 data[i+1] = flags & 0xFF
868 i += 4
869 flags = int(flags)
870
871 if flags & ARG_1_AND_2_ARE_WORDS: i += 4
872 else: i += 2
873 if flags & WE_HAVE_A_SCALE: i += 2
874 elif flags & WE_HAVE_AN_X_AND_Y_SCALE: i += 4
875 elif flags & WE_HAVE_A_TWO_BY_TWO: i += 8
876 more = flags & MORE_COMPONENTS
877 # Cut off
878 data = data[:i]
879 if len(data) % 4:
880 # add pad bytes
881 nPadBytes = 4 - (len(data) % 4)
882 for i in range (nPadBytes):
883 data.append (0)
884 self.data = str (data)
885
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400886@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod254442b2013-07-31 14:20:13 -0400887def closure_glyphs (self, s):
888 glyphs = unique_sorted (s.glyphs)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400889 decompose = glyphs
890 # I don't know if component glyphs can be composite themselves.
891 # We handle them anyway.
892 while True:
893 components = []
894 for g in decompose:
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400895 if g not in self.glyphs:
Behdad Esfahbodf8c20e42013-07-23 23:13:23 -0400896 continue
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400897 gl = self.glyphs[g]
898 if hasattr (gl, "data"):
899 for c in gl.getComponentNamesFast (self):
900 if c not in glyphs:
901 components.append (c)
902 else:
903 # TTX seems to expand gid0..3 always
904 if gl.isComposite ():
905 for c in gl.components:
906 if c.glyphName not in glyphs:
907 components.append (c.glyphName)
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400908 components = [c for c in components if c not in glyphs]
909 if not components:
910 return glyphs
911 decompose = unique_sorted (components)
912 glyphs.extend (components)
913
914@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400915def subset_glyphs (self, s):
916 self.glyphs = {g:v for g,v in self.glyphs.items() if g in s.glyphs}
917 indices = [i for i,g in enumerate (self.glyphOrder) if g in s.glyphs]
Behdad Esfahbod4cf7a802013-07-24 16:08:35 -0400918 for v in self.glyphs.values ():
919 if hasattr (v, "data"):
920 v.remapComponentsFast (indices)
921 else:
922 pass # No need
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400923 self.glyphOrder = [g for g in self.glyphOrder if g in s.glyphs]
Behdad Esfahbod4027dd82013-07-23 10:56:04 -0400924 return bool (self.glyphs)
Behdad Esfahbod861d9152013-07-22 16:47:24 -0400925
Behdad Esfahboded98c612013-07-23 12:37:41 -0400926@add_method(fontTools.ttLib.getTableClass('glyf'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400927def prune_post_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400928 if not options.hinting:
Behdad Esfahbod6ec88542013-07-24 16:52:47 -0400929 for v in self.glyphs.values ():
930 if hasattr (v, "data"):
931 v.dropInstructionsFast ()
932 else:
933 v.program = fontTools.ttLib.tables.ttProgram.Program()
934 v.program.fromBytecode([])
Behdad Esfahboded98c612013-07-23 12:37:41 -0400935 return True
936
Behdad Esfahbod2b677c82013-07-23 13:37:13 -0400937@add_method(fontTools.ttLib.getTableClass('CFF '))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400938def subset_glyphs (self, s):
Behdad Esfahbod2b677c82013-07-23 13:37:13 -0400939 assert 0, "unimplemented"
940
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400941@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -0400942def closure_glyphs (self, s):
943 tables = [t for t in self.tables if t.platformID == 3 and t.platEncID in [1, 10]]
944 extra = []
Behdad Esfahbod98259f22013-07-31 20:16:24 -0400945 for u in s.unicodes_requested:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -0400946 found = False
947 for table in tables:
948 if u in table.cmap:
949 extra.append (table.cmap[u])
950 found = True
951 break
952 if not found:
953 s.log ("No glyph for Unicode value %s; skipping." % u)
954 return extra
955
956@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400957def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400958 if not options.legacy_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400959 # Drop non-Unicode / non-Symbol cmaps
960 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 -0400961 if not options.symbol_cmap:
Behdad Esfahbodde4a15b2013-07-23 13:05:42 -0400962 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 -0400963 # TODO Only keep one subtable?
Behdad Esfahbodabb50a12013-07-23 12:58:37 -0400964 # For now, drop format=0 which can't be subset_glyphs easily?
965 self.tables = [t for t in self.tables if t.format != 0]
966 return bool (self.tables)
967
968@add_method(fontTools.ttLib.getTableClass('cmap'))
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400969def subset_glyphs (self, s):
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -0400970 s.glyphs = s.glyphs_cmaped
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400971 for t in self.tables:
Behdad Esfahbod9453a362013-07-22 16:21:24 -0400972 # For reasons I don't understand I need this here
973 # to force decompilation of the cmap format 14.
974 try:
975 getattr (t, "asdf")
976 except AttributeError:
977 pass
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400978 if t.format == 14:
Behdad Esfahbod9453a362013-07-22 16:21:24 -0400979 # XXX We drop all the default-UVS mappings (g==None)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -0400980 t.uvsDict = {v:[(u,g) for (u,g) in l if g in s.glyphs] for (v,l) in t.uvsDict.items()}
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400981 t.uvsDict = {v:l for (v,l) in t.uvsDict.items() if l}
982 else:
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -0400983 t.cmap = {u:g for (u,g) in t.cmap.items() if g in s.glyphs_requested or u in s.unicodes_requested}
Behdad Esfahbodb13d7902013-07-22 16:01:15 -0400984 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 -0400985 # XXX Convert formats when needed
Behdad Esfahbod61addb42013-07-23 11:03:49 -0400986 return bool (self.tables)
987
Behdad Esfahbod61addb42013-07-23 11:03:49 -0400988@add_method(fontTools.ttLib.getTableClass('name'))
Behdad Esfahbodd7b6f8f2013-07-23 12:46:52 -0400989def prune_pre_subset (self, options):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400990 if '*' not in options.name_IDs:
991 self.names = [n for n in self.names if n.nameID in options.name_IDs]
992 if not options.name_legacy:
Behdad Esfahbod20faeb02013-07-23 13:19:03 -0400993 self.names = [n for n in self.names if n.platformID == 3 and n.platEncID == 1]
Behdad Esfahbod97e17b82013-07-31 15:59:21 -0400994 if '*' not in options.name_languages:
995 self.names = [n for n in self.names if n.langID in options.name_languages]
Behdad Esfahbod20faeb02013-07-23 13:19:03 -0400996 return True # Retain even if empty
Behdad Esfahbod653e9742013-07-22 15:17:12 -0400997
Behdad Esfahbod8c646f62013-07-22 15:06:23 -0400998
Behdad Esfahbodbc25f162013-07-23 12:56:54 -0400999drop_tables_default = ['BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'PCLT', 'LTSH']
Behdad Esfahbod103a12f2013-07-23 15:08:39 -04001000drop_tables_default += ['Feat', 'Glat', 'Gloc', 'Silf', 'Sill'] # Graphite
Behdad Esfahbod38e852c2013-07-23 16:56:50 -04001001drop_tables_default += ['CBLC', 'CBDT', 'sbix', 'COLR', 'CPAL'] # Color
Behdad Esfahboded98c612013-07-23 12:37:41 -04001002no_subset_tables = ['gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2', 'loca', 'name', 'cvt ', 'fpgm', 'prep']
Behdad Esfahbodbc25f162013-07-23 12:56:54 -04001003hinting_tables = ['cvt ', 'fpgm', 'prep', 'hdmx', 'VDMX']
Behdad Esfahbod29df0462013-07-23 11:05:25 -04001004
Behdad Esfahbod356c42e2013-07-23 12:10:46 -04001005# Based on HarfBuzz shapers
1006layout_features_dict = {
1007 # Default shaper
1008 'common': ['ccmp', 'liga', 'locl', 'mark', 'mkmk', 'rlig'],
1009 'horizontal': ['calt', 'clig', 'curs', 'kern', 'rclt'],
1010 'vertical': ['valt', 'vert', 'vkrn', 'vpal', 'vrt2'],
1011 'ltr': ['ltra', 'ltrm'],
1012 'rtl': ['rtla', 'rtlm'],
1013 # Complex shapers
Behdad Esfahbodf36b5a92013-08-04 16:54:46 -04001014 'arabic': ['init', 'medi', 'fina', 'isol', 'med2', 'fin2', 'fin3', 'cswh', 'mset'],
Behdad Esfahbod356c42e2013-07-23 12:10:46 -04001015 'hangul': ['ljmo', 'vjmo', 'tjmo'],
1016 'tibetal': ['abvs', 'blws', 'abvm', 'blwm'],
1017 'indic': ['nukt', 'akhn', 'rphf', 'rkrf', 'pref', 'blwf', 'half', 'abvf', 'pstf', 'cfar', 'vatu', 'cjct',
1018 'init', 'pres', 'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm'],
1019}
1020layout_features_all = unique_sorted (sum (layout_features_dict.values (), []))
1021
Behdad Esfahbod75e14fc2013-07-22 14:49:54 -04001022# TODO OS/2 ulUnicodeRange / ulCodePageRange?
Behdad Esfahbodf71267b2013-07-23 12:59:13 -04001023# TODO Drop unneeded GSUB/GPOS Script/LangSys entries
Behdad Esfahbod398d3892013-07-23 15:29:40 -04001024# TODO Avoid recursing too much
Behdad Esfahbode94aa0e2013-07-23 13:22:04 -04001025# TODO Text direction considerations
1026# TODO Text script / language considerations
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001027# TODO Drop unknown tables? Using DefaultTable.prune?
Behdad Esfahbod8c4f7cc2013-07-24 17:58:29 -04001028# TODO Drop GPOS Device records if not hinting?
Behdad Esfahbod56ebd042013-07-22 13:02:24 -04001029
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001030
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001031class Subsetter:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001032
1033 class Options:
1034 drop_tables = drop_tables_default
1035 layout_features = layout_features_all
1036 hinting = False
1037 glyph_names = False
1038 legacy_cmap = False
1039 symbol_cmap = False
1040 name_IDs = [1, 2] # Family and Style
1041 name_legacy = False
1042 name_languages = [0x0409] # English
1043 mandatory_glyphs = True # First four for TrueType, .notdef for CFF
1044 recalc_bboxes = False # Slows us down
1045
1046 def __init__ (self, **kwargs):
1047
1048 self.set (**kwargs)
1049
1050 def set (self, **kwargs):
1051 for k,v in kwargs.items ():
1052 if not hasattr (self, k):
1053 raise Exception ("Unknown option '%s'" % k)
1054 setattr (self, k, v)
1055
1056 def parse_opts (self, argv, ignore_unknown=False):
1057 ret = []
1058 opts = {}
1059 for a in argv:
1060 if not a.startswith ('--'):
1061 ret.append (a)
1062 continue
1063 a = a[2:]
1064 i = a.find ('=')
1065 if i == -1:
1066 if a.startswith ("no-"):
1067 k = a[3:]
1068 v = False
1069 else:
1070 k = a
1071 v = True
1072 else:
1073 k = a[:i]
1074 v = a[i+1:]
1075 k = k.replace ('-', '_')
1076 if not hasattr (self, k):
1077 if ignore_unknown:
1078 ret.append (a)
1079 continue
1080 else:
1081 raise Exception ("Unknown option '%s'" % a)
1082
1083 ov = getattr (self, k)
1084 if isinstance (ov, bool):
1085 v = bool (v)
1086 elif isinstance (ov, int):
1087 v = int (v)
1088 elif isinstance (ov, list):
1089 v = v.split (',')
1090 v = [int (x, 0) if x[0] in range (10) else x for x in v]
1091
1092 opts[k] = v
1093 self.set (**opts)
1094
1095 return ret
1096
1097
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001098 def __init__ (self, font=None, options=None, log=None):
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001099
1100 if isinstance (font, basestring):
1101 font = fontTools.ttx.TTFont (font)
1102 if not log:
1103 log = Logger()
1104 if not options:
1105 options = Options()
1106
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001107 self.font = font
1108 self.options = options
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001109 self.log = log
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001110 self.unicodes_requested = set ()
1111 self.glyphs_requested = set ()
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001112
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001113 def populate (self, glyphs=[], unicodes=[], text=""):
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001114 self.unicodes_requested.update (unicodes)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001115 if isinstance (text, str):
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001116 text = text.decode ("utf8")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001117 for u in text:
Behdad Esfahbod618c0862013-07-31 20:11:17 -04001118 self.unicodes_requested.add (ord (u))
Behdad Esfahbodc4eb3db2013-07-31 19:56:19 -04001119 self.glyphs_requested.update (glyphs)
Behdad Esfahbod3d513b72013-07-31 14:11:40 -04001120
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001121 def pre_prune (self):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001122
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001123 for tag in self.font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001124 if tag == 'GlyphOrder': continue
1125
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001126 if tag in self.options.drop_tables or \
1127 (tag in hinting_tables and not self.options.hinting):
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001128 self.log (tag, "dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001129 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001130 continue
1131
1132 clazz = fontTools.ttLib.getTableClass(tag)
1133
1134 if hasattr (clazz, 'prune_pre_subset'):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001135 table = self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001136 retain = table.prune_pre_subset (self.options)
1137 self.log.lapse ("prune '%s'" % tag)
1138 if not retain:
1139 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001140 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001141 continue
1142 else:
1143 self.log (tag, "pruned")
1144
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001145 def closure_glyphs (self):
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001146
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001147 self.glyphs = self.glyphs_requested
1148
1149 if 'cmap' in self.font:
1150 extra_glyphs = self.font['cmap'].closure_glyphs (self)
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001151 self.glyph = self.glyphs.copy ()
1152 self.glyphs.update (extra_glyphs)
1153 self.glyphs_cmaped = self.glyphs
1154
1155 if self.options.mandatory_glyphs:
1156 self.glyphs = self.glyphs.copy ()
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001157 if 'glyf' in self.font:
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001158 for i in range (4):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001159 self.glyphs.add (self.font.getGlyphName (i))
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001160 self.log ("Added first four glyphs to subset")
1161 else:
1162 self.glyphs.add ('.notdef')
1163 self.log ("Added .notdef glyph to subset")
1164
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001165 if 'GSUB' in self.font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001166 self.log ("Closing glyph list over 'GSUB': %d glyphs before" % len (self.glyphs))
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001167 self.glyphs = set (self.font['GSUB'].closure_glyphs (self))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001168 self.log ("Closed glyph list over 'GSUB': %d glyphs after" % len (self.glyphs))
1169 self.log ("Glyphs:", self.glyphs)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001170 self.log.lapse ("close glyph list over 'GSUB'")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001171 self.glyphs_gsubed = self.glyphs
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001172
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001173 if 'glyf' in self.font:
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001174 self.log ("Closing glyph list over 'glyf': %d glyphs before" % len (self.glyphs))
1175 self.log ("Glyphs:", self.glyphs)
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001176 self.glyphs = set (self.font['glyf'].closure_glyphs (self))
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001177 self.log ("Closed glyph list over 'glyf': %d glyphs after" % len (self.glyphs))
1178 self.log ("Glyphs:", self.glyphs)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001179 self.log.lapse ("close glyph list over 'glyf'")
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001180 self.glyphs_glyfed = self.glyphs
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001181
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001182 self.glyphs_all = self.glyphs
1183
1184 self.log ("Retaining %d glyphs: " % len (self.glyphs_all))
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001185
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001186 def subset_glyphs (self):
1187 for tag in self.font.keys():
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001188 if tag == 'GlyphOrder': continue
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001189 clazz = fontTools.ttLib.getTableClass(tag)
1190
1191 if tag in no_subset_tables:
1192 self.log (tag, "subsetting not needed")
1193 elif hasattr (clazz, 'subset_glyphs'):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001194 table = self.font[tag]
Behdad Esfahboda6dbb7a2013-07-31 19:53:57 -04001195 self.glyphs = self.glyphs_all
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001196 retain = table.subset_glyphs (self)
1197 self.log.lapse ("subset '%s'" % tag)
1198 if not retain:
1199 self.log (tag, "subsetted to empty; dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001200 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001201 else:
1202 self.log (tag, "subsetted")
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001203 else:
1204 self.log (tag, "NOT subset; don't know how to subset")
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001205
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001206 glyphOrder = self.font.getGlyphOrder()
Behdad Esfahbode10803e2013-08-08 21:09:27 -04001207 #print [glyphOrder.index (g) for g in self.glyphs_all]
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001208 glyphOrder = [g for g in glyphOrder if g in self.glyphs_all]
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001209 self.font.setGlyphOrder (glyphOrder)
1210 self.font._buildReverseGlyphOrderDict ()
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001211 self.log.lapse ("subset GlyphOrder")
1212
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001213 def post_prune (self):
1214 for tag in self.font.keys():
Behdad Esfahbod2fb90e22013-07-31 20:04:08 -04001215 if tag == 'GlyphOrder': continue
1216 clazz = fontTools.ttLib.getTableClass(tag)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001217 if hasattr (clazz, 'prune_post_subset'):
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001218 table = self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001219 retain = table.prune_post_subset (self.options)
1220 self.log.lapse ("prune '%s'" % tag)
1221 if not retain:
1222 self.log (tag, "pruned to empty; dropped")
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001223 del self.font[tag]
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001224 else:
1225 self.log (tag, "pruned")
1226
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001227 def subset (self, font):
1228
1229 self.font = font
Behdad Esfahbod756af492013-08-01 12:05:26 -04001230
Behdad Esfahbod98259f22013-07-31 20:16:24 -04001231 self.font.recalcBBoxes = self.options.recalc_bboxes
1232
1233 self.pre_prune ()
1234 self.closure_glyphs ()
1235 self.subset_glyphs ()
1236 self.post_prune ()
1237
Behdad Esfahbod756af492013-08-01 12:05:26 -04001238 del self.font
1239
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001240import sys, time
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001241
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001242class Logger:
1243
1244 def __init__ (self, verbose=False, xml=False, timing=False):
1245 self.verbose = verbose
1246 self.xml = xml
1247 self.timing = timing
1248 self.last_time = self.start_time = time.time ()
1249
1250 def parse_opts (self, argv):
1251 argv = argv[:]
1252 for v in ['verbose', 'xml', 'timing']:
1253 if "--"+v in argv:
1254 setattr (self, v, True)
1255 argv.remove ("--"+v)
1256 return argv
1257
1258 def __call__ (self, *things):
1259 if not self.verbose:
1260 return
1261 print ' '.join (str (x) for x in things)
1262
1263 def lapse (self, *things):
1264 if not self.timing:
1265 return
1266 new_time = time.time ()
1267 print "Took %0.3fs to %s" % (new_time - self.last_time, ' '.join (str (x) for x in things))
1268 self.last_time = new_time
1269
1270 def font (self, font, file=sys.stdout):
1271 if not self.xml:
1272 return
1273 import xmlWriter, sys
1274 writer = xmlWriter.XMLWriter (file)
1275 font.disassembleInstructions = False # Work around ttx bug
1276 for tag in font.keys():
1277 writer.begintag (tag)
1278 writer.newline ()
1279 font[tag].toXML(writer, font)
1280 writer.endtag (tag)
1281 writer.newline ()
1282
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001283def main (args):
Behdad Esfahbod610b0552013-07-23 14:52:18 -04001284
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001285 log = Logger ()
1286 args = log.parse_opts (args)
Behdad Esfahbod4ae81712013-07-22 11:57:13 -04001287
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001288 options = Subsetter.Options ()
1289 args = options.parse_opts (args)
1290
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001291 if len (args) < 2:
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001292 import sys
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001293 print >>sys.stderr, "usage: pyotlss.py font-file glyph..."
1294 sys.exit (1)
1295
Behdad Esfahboddf3d7572013-07-31 15:03:43 -04001296 fontfile = args[0]
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001297 args = args[1:]
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001298
Behdad Esfahbodb3ee60c2013-07-24 19:21:40 -04001299 # TODO Option for ignoreDecompileErrors?
Behdad Esfahbod88264a62013-07-31 14:45:13 -04001300 font = fontTools.ttx.TTFont (fontfile)
Behdad Esfahbod063a2db2013-07-31 15:22:02 -04001301 s = Subsetter (font=font, options=options, log=log)
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001302 log.lapse ("load font")
Behdad Esfahbod02b92062013-07-21 18:40:59 -04001303
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001304 # Hack:
1305 #
1306 # If we don't need glyph names, change 'post' class to not try to
1307 # load them. It avoid lots of headache with broken fonts as well
1308 # as loading time.
1309 #
1310 # Ideally ttLib should provide a way to ask it to skip loading
1311 # glyph names. But it currently doesn't provide such a thing.
1312 #
1313 if not options.glyph_names \
1314 and all (any (g.startswith (p) for p in ['gid', 'glyph', 'uni']) \
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001315 for g in args):
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001316 post = fontTools.ttLib.getTableClass('post')
1317 saved = post.decode_format_2_0
1318 post.decode_format_2_0 = post.decode_format_3_0
1319 f = font['post']
1320 if f.formatType == 2.0:
1321 f.formatType = 3.0
1322 post.decode_format_2_0 = saved
1323 del post, saved, f
1324
1325 names = font.getGlyphNames()
1326 log.lapse ("loading glyph names")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001327
1328 glyphs = []
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001329 unicodes = []
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001330 for g in args:
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001331 if g in names:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001332 glyphs.append (g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001333 continue
1334 if g.startswith ('uni') and len (g) > 3:
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001335 u = int (g[3:], 16)
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001336 unicodes.append (u)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001337 continue
1338 if g.startswith ('gid') or g.startswith ('glyph'):
1339 if g.startswith ('gid') and len (g) > 3:
1340 g = g[3:]
1341 elif g.startswith ('glyph') and len (g) > 5:
1342 g = g[5:]
1343 try:
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001344 glyphs.append (font.getGlyphName (int (g), requireReal=1))
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001345 except ValueError:
1346 raise Exception ("Invalid glyph identifier %s" % g)
1347 continue
1348 raise Exception ("Invalid glyph identifier %s" % g)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001349 log.lapse ("compile glyph list")
Behdad Esfahbode7f5a892013-07-31 19:58:59 -04001350 log ("Unicodes:", unicodes)
Behdad Esfahbod6df089a2013-07-31 19:27:14 -04001351 log ("Glyphs:", glyphs)
1352
Behdad Esfahbod8c8ff452013-07-31 19:47:37 -04001353 s.populate (glyphs=glyphs, unicodes=unicodes)
1354 s.subset (font)
Behdad Esfahbodd1d41bc2013-07-21 23:15:32 -04001355
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001356 font.save (fontfile + '.subset')
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001357 log.lapse ("compile and save font")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001358
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001359 log.last_time = s.log.start_time
1360 log.lapse ("make one with everything (TOTAL TIME)")
Behdad Esfahbodde71dca2013-07-24 12:40:54 -04001361
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001362 log.font (font)
Behdad Esfahbod8c486d82013-07-24 13:34:47 -04001363
1364if __name__ == '__main__':
Behdad Esfahbod97e17b82013-07-31 15:59:21 -04001365 import sys
1366 main (sys.argv[1:])