-
Notifications
You must be signed in to change notification settings - Fork 0
/
mkligtable.py
executable file
·319 lines (292 loc) · 11.8 KB
/
mkligtable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""Read the files from the specified sfdir directory, generating a
ligtable to drop into a tftopl generated pl file."""
import sys
import os
import re
def between(string, left='"', right=None, start=0):
if right is None:
right = left
left = string.index(left, start)+1
return string[left : string.index(right, left)]
class ChainSub (object):
def __init__(self):
self.classes = []
self.bclasses = []
self.fclasses = []
self.substitutions = [] #A list of quadruplets, each
#quadruplet consisting of an index to
#classes, an index to bclasses, an
#index to fclasses and a substitution
#subtable.
def lookahead(self):
lookaheads = {}
for c, bc, fc, table in self.substitutions:
if bc is None:
for glyph in self.classes[c]:
subs = lookaheads.setdefault(
glyph, {})
for forward in self.fclasses[fc]:
subs[forward] = (
substitutions[
table + " subtable"
][glyph])
return lookaheads
def lookbehind(self):
lookbehinds = {}
for c, bc, fc, table in self.substitutions:
if fc is None:
for glyph in self.classes[c]:
for backward in self.bclasses[bc]:
subs = lookbehinds.setdefault(
backward, {})
subs[glyph] = (
substitutions[
table + " subtable"
][glyph])
return lookbehinds
def ligtable(
internals,
substitutions,
lookaheads,
lookbehinds,
ligatures,
kernings,
boundary_characters = ".,;:()-!?"
):
bchar = max(set(range(256))-set(internals))
#Bring data in a form we can use to write the ligtable
init = {}
fina = {}
interesting_glyphs = set()
#"Interesting" are those glyphs that have ligature
#or kerning data associated with them.
for name, table in substitutions.items():
if "'init'" in name:
init.update(table)
elif "'fina'" in name:
fina.update(table)
interesting_glyphs.update(set(table))
liga = {}
for name, table in ligatures.items():
liga.update(table)
interesting_glyphs.update(set(table))
kern = {}
for name, table in kernings.items():
kern.update(table)
interesting_glyphs.update(set(table))
interesting_glyphs.update(lookaheads)
interesting_glyphs.update(lookbehinds)
boundary_characters = [
positions[unicodes[ord(boundary_character)]]
for boundary_character in boundary_characters] + [
bchar]
#Replace references to 'usual' glyphs by their medial and historic
#forms in the encoding tables.
#Start writing the ligtable:
#It starts with a boundarychar.
print("(BOUNDARYCHAR O %o)" % bchar)
print("(LIGTABLE");
print(" (LABEL BOUNDARYCHAR)")
for general, initial in init.items():
print(" (LIG O %o O %o)" % (
positions[general],
positions[initial]))
print(" (STOP)")
#Deal with init forms.
#These are lookbehind contextuals, therefor "/LIG"
for boundary_character in boundary_characters:
print(" (LABEL O %o)" % boundary_character)
for general, initial in init.items():
print(" (/LIG O %o O %o)" % (
positions[general],
positions[initial]))
print(" (STOP)")
#Deal with other glyphs.
for glyph in interesting_glyphs:
print(" (LABEL O %o)" % positions[glyph])
for lookbehind, to in lookbehinds.get(
glyph, {}).items():
print(" (/LIG O %o O %o)" % (
positions[lookbehind],
positions[to]))
for lookahead, to in lookaheads.get(
glyph, {}).items():
print(" (LIG/ O %o O %o)" % (
positions[lookahead],
positions[to]))
if glyph in fina:
for boundary_character in boundary_characters:
print(" (LIG/ O %o O %o)" % (
boundary_character,
positions[fina[glyph]]))
for ligother, to in liga.get(
glyph, {}).items():
print(" (LIG O %o O %o)" % (
positions[ligother],
positions[to]))
for kernother, amount in kern.get(
glyph, {}).items():
print(" (KRN O %o R %f)" % (
positions[internals[kernother]],
amount*0.001))
print(" (STOP)")
print(" )")
#if __name__=="__main__":
# directory = sys.argv[1]
if True:
directory = "Jena1330.sfdir"
fontprops = os.path.join(directory, "font.props")
lookups = []
chainsubs = []
kernings = {}
substitutions = {}
ligatures = {}
chainsub = None
with open(fontprops) as propsfile:
for line in propsfile:
line = line.strip()
if line.startswith("Lookup"):
#This defines a Lookup table.
#Save its name in lookups.
lookups.append(between(line, '"'))
elif line.startswith("ChainSub2"):
#Chain Substitution header
#If there is a current chaining substitution table, append it to their list.
if chainsub:
chainsubs.append(chainsub)
chainsub = ChainSub()
elif line.startswith("Class"):
#Line defines a substitution class for the current
#ChainSub. The first and second word are the
#"Class:" and a number, the class elements are
#words 2:.
chainsub.classes.append(line.split()[2:])
#Yes, this line is expected to throw an
#AttributeError in some cases.
elif line.startswith("BClass"):
#Line defines a lookbehind class for the current
#ChainSub, similar to "Class".
chainsub.bclasses.append(line.split()[2:])
elif line.startswith("FClass"):
#Line defines a lookforward class for the current
#ChainSub, similar to "Class".
chainsub.fclasses.append(line.split()[2:])
elif line.startswith("ClsList"):
items = line.split()
if len(items)==1:
raise ValueError(
"ClsList was empty."
)
elif len(items)==2:
classlist_index = int(items[1])-1
# FontForge Class indices are 1-based,
# Python list indices are 0-based
else:
raise NotImplementedError(
"Program does not cope with multiple classes yet."
)
elif line.startswith("BClsList"):
items = line.split()
if len(items)==1:
bclasslist_index = None
elif len(items)==2:
bclasslist_index = int(items[1])-1
else:
raise NotImplementedError(
"Program does not cope with multiple classes yet."
)
elif line.startswith("FClsList"):
items = line.split()
if len(items)==1:
fclasslist_index = None
elif len(items)==2:
fclasslist_index = int(items[1])-1
else:
raise NotImplementedError(
"Program does not cope with multiple classes yet."
)
elif line.startswith("SeqLookup"):
#Line defines what do do for the current case for this
#ChainSub. We are supposed to know the lookup
#referenced here
substitution = between(line, '"')
assert(substitution in lookups)
#This and the classlists form a new chain substitution
#item. Save it in the chain substitutions.
chainsub.substitutions.append(
(classlist_index,
bclasslist_index,
fclasslist_index,
substitution))
else:
#Line is not particularly important, ignore.
pass
positions = {}
unicodes = {}
internals = {}
for glyph in os.listdir(directory):
if glyph.endswith(".glyph"):
with open(
os.path.join(directory, glyph)
) as glyphfile:
glyphname = None
for line in glyphfile:
line = line.strip()
if line.startswith("StartChar:"):
glyphname = line.split()[1]
if line.startswith("Encoding:"):
# Encoding lines contain three numbers: The
# code point as by the encoding defined in the
# font.props, the Unicode code point and an
# internal encoding.
(_,
position,
unic,
internal) = line.split()
positions[glyphname] = int(position)
if unic != "-1":
unicodes[int(unic)] = glyphname
internals[int(internal)] = glyphname
if line.startswith("Substitution2:"):
table = substitutions.setdefault(
between(line, '"'),
{})
substitute_to = line.split()[-1]
table[glyphname] = substitute_to
if line.startswith("Kerns2:"):
#decompose the line into data, table pairs
blobs = line[len("Kerns2:"):]
blobs = blobs.split('"')
#Do not have '"' in table names, as it would
#break this!!!!
blobs = list(zip(blobs[::2], blobs[1::2]))
for data, tablename in blobs:
table = kernings.setdefault(
tablename,
{})
kern = table.setdefault(
glyphname,
{})
other, kerning = data.split()
kern[int(other)] = int(kerning)
if line.startswith("Ligature2:"):
table = ligatures.setdefault(
between(line, '"'),
{})
start = line.index('"', line.index('"')+1)
components = line[start+1:].split()
if len(components)>2:
raise NotImplementedError
lig = table.setdefault(
components[0],
{})
lig[components[1]]=glyphname
ligtable(internals,
substitutions,
chainsub.lookahead(),
chainsub.lookbehind(),
ligatures,
kernings
)