-
Notifications
You must be signed in to change notification settings - Fork 7
/
Nastaliq Connection Editor.py
314 lines (276 loc) · 11.6 KB
/
Nastaliq Connection Editor.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
# MenuTitle: Nastaliq Connection Editor
# -*- coding: utf-8 -*-
__doc__ = """
Edit Nastaliq connections in a font that conforms to Qalmi glyph naming
convention
"""
import sys
from AppKit import NSObject
import vanilla
import csv
from io import StringIO
import re
from AppKit import NSView, NSColor, NSRectFill, NSBezierPath, NSAffineTransform
from vanilla.vanillaBase import VanillaBaseObject, VanillaCallbackWrapper
import traceback
def glyphsort(x):
x = re.sub(r"(\D)([0-9])$", r"\g<1>0\2", x)
x = re.sub(r"^GAF", "KAF", x)
x = re.sub(r"^TE", "BE", x)
return x
if "GlyphView" not in locals():
class GlyphView(NSView):
@objc.python_method
def setGlyphs(self, glyphs):
self.glyphs = glyphs
self.setNeedsDisplay_(True)
@objc.python_method
def setMaster(self, master_id):
self.master = master_id
self.setNeedsDisplay_(True)
def drawRect_(self, rect):
try:
NSColor.whiteColor().set()
NSRectFill(self.bounds())
NSColor.blackColor().setFill()
p = NSBezierPath.bezierPath()
xcursor = 0
ycursor = 0
for i, g in enumerate(self.glyphs):
layer = g.layers[self.master]
if i > 0:
# Do anchor correction here
prevlayer = self.glyphs[i - 1].layers[self.master]
entry = prevlayer.anchors["entry"]
exit = layer.anchors["exit"]
if entry and exit:
diffX = entry.position.x - exit.position.x
diffY = entry.position.y - exit.position.y
xcursor = xcursor + diffX
ycursor = ycursor + diffY
else:
NSColor.redColor().setFill()
else:
xcursor = xcursor - layer.bounds.origin.x
thisPath = NSBezierPath.bezierPath()
thisPath.appendBezierPath_(layer.completeBezierPath)
t = NSAffineTransform.transform()
t.translateXBy_yBy_(xcursor, -layer.master.descender + ycursor)
thisPath.transformUsingAffineTransform_(t)
p.appendBezierPath_(thisPath)
t = NSAffineTransform.transform()
if xcursor > 0:
master = self.glyphs[0].layers[self.master].master
vscale = self.bounds().size.height / (
master.ascender - master.descender
)
hscale = self.bounds().size.width / xcursor
t.scaleBy_(min(hscale, vscale))
p.transformUsingAffineTransform_(t)
p.fill()
except Exception as e:
print("Oops!", sys.exc_info()[0], "occured.")
traceback.print_exc(file=sys.stdout)
class NastaliqEditor(object):
def __init__(self, connections):
self.connections = connections
columns = [
{"title": x, "editable": x != "Left Glyph", "width": 40}
for x in self.connections["colnames"]
]
columns[0]["width"] = 100
self.w = vanilla.Window((1000, 1000), "Nastaliq Editor", closable=True)
self.w.LeftLabel = vanilla.TextBox((-200, 10, 200, 17), "", alignment="center")
self.w.LeftButton = vanilla.Button(
(-200, 30, 30, 17), "<", callback=self.decrement
)
self.w.RightLabel = vanilla.TextBox((-170, 30, 140, 17), "", alignment="center")
self.w.RightButton = vanilla.Button(
(-30, 30, 30, 17), ">", callback=self.increment
)
self.w.myList = vanilla.List(
(0, 0, -300, -0),
self.connections["rows"],
columnDescriptions=columns,
editCallback=self.editCallback,
menuCallback=self.menuCallback,
)
self.w.myList._clickTarget = VanillaCallbackWrapper(
self.clickCallback
)
self.w.myList._tableView.setTarget_(self.w.myList._clickTarget)
self.w.myList._tableView.setAction_("action:")
self.w.CompileButton = vanilla.Button(
(-200, -20, 200, 17), "Compile", callback=self.compile
)
self.glyphView = GlyphView.alloc().init()
self.glyphView.glyphs = []
self.glyphView.master = Glyphs.font.masters[0].id
self.glyphView.setFrame_(((0, 0), (600, 400)))
self.w.scrollView = vanilla.ScrollView((-280, 50, 300, 400), self.glyphView)
self.w.masterDropdown = vanilla.PopUpButton((-250, 500, -100, 20),
[x.name for x in Glyphs.font.masters],
callback=self.setMaster
)
self.selectedPair = None
self.inAdd = False
self.w.open()
def setMaster(self, sender):
master_ix = sender.get()
self.glyphView.setMaster(Glyphs.font.masters[master_ix].id)
def editCallback(self, sender):
if self.inAdd:
return
ccol, crow = self.w.myList.getEditedColumnAndRow()
print("Col was ", crow, ccol)
newdata = self.w.myList[crow][self.connections["colnames"][ccol]]
print("New data was ", newdata)
self.setNewPair(crow, ccol, newdata)
sys.stdout.flush()
def clickCallback(self, sender):
crow = self.w.myList._tableView.clickedRow()
ccol = self.w.myList._tableView.clickedColumn()
if ccol < 1:
return
self.setNewPair(crow, ccol)
def decrement(self, sender):
try:
self.add(-1)
except Exception as e:
print("Oops!", sys.exc_info()[0], "occured.")
traceback.print_exc(file=sys.stdout)
def increment(self, sender):
try:
self.add(1)
except Exception as e:
print("Oops!", sys.exc_info()[0], "occured.")
traceback.print_exc(file=sys.stdout)
def add(self, increment):
if not self.selectedPair:
return
crow, ccol = self.selectedPair
colname = self.connections["colnames"][ccol]
availableAlternates = [ str(g.name) for g in Glyphs.font.glyphs if str(g.name).startswith(colname) ]
currentAlternate = colname+str(self.connections["rows"][crow][colname])
if not currentAlternate in availableAlternates:
# Weirdness
return
# Add +increment
index = availableAlternates.index(currentAlternate)
print(availableAlternates, currentAlternate)
if index == 0 and increment == -1: return
if index == len(availableAlternates)-1 and increment == 1: return
newGlyph = availableAlternates[index + increment]
data = newGlyph[len(colname):]
print(data)
self.inAdd = True
self.setNewPair(crow, ccol, data)
newdict = self.w.myList[crow]
newdict[colname] = data
self.w.myList[crow] = newdict
self.inAdd = False
def setNewPair(self, crow, ccol, newdata=None):
left = self.connections["rows"][crow]["Left Glyph"]
colname = self.connections["colnames"][ccol]
if newdata and Glyphs.font.glyphs[colname + str(newdata)]:
self.connections["rows"][crow][colname] = newdata
Glyphs.font.userData["nastaliqConnections"] = self.connections
data = self.connections["rows"][crow][colname]
self.w.LeftLabel.set(left)
self.w.RightLabel.set(colname + str(data))
self.selectedPair = (crow, ccol)
if Glyphs.font.glyphs[colname + str(data)]:
leftglyph = Glyphs.font.glyphs[left]
rightglyph = Glyphs.font.glyphs[colname + str(data)]
self.glyphView.setGlyphs([leftglyph, rightglyph])
sys.stdout.flush()
def menuCallback(self, sender):
sys.stdout.flush()
def compile(self, sender):
rows = Glyphs.font.userData["nastaliqConnections"]["rows"]
rules = {}
for line in rows:
left_glyph = line["Left Glyph"]
remainder = line.items()
for (g, v) in remainder:
if g == "Left Glyph":
continue
old = g + "1"
if v == "1" or v == 1 or not v:
continue
replacement = g + str(v)
if not old in rules:
rules[old] = {}
if not replacement in rules[old]:
rules[old][replacement] = []
if left_glyph in Glyphs.font.glyphs:
rules[old][replacement].append(left_glyph)
code = ""
for oldglyph in rules:
if oldglyph not in Glyphs.font.glyphs:
continue
for replacement in rules[oldglyph]:
if replacement not in Glyphs.font.glyphs:
continue
context = rules[oldglyph][replacement]
if len(context) > 1:
context = "[ %s ]" % (" ".join(context))
else:
context = context[0]
code = code + (
"rsub %s' %s by %s;\n" % (oldglyph, context, replacement)
)
print(code)
if not Glyphs.font.features["rlig"]:
Glyphs.font.features["rlig"] = GSFeature("rlig", "")
Glyphs.font.features["rlig"].code = "lookupflag IgnoreMarks;\n" + code
Message("rlig feature written", "New feature rules written")
def mergeConnections(new, old):
# Turn old into a dict
dOld = {}
for row in old["rows"]:
dOld[row["Left Glyph"]] = row
for row in new["rows"]:
for col in new["colnames"]:
if row["Left Glyph"] in dOld and col in dOld[row["Left Glyph"]]:
row[col] = dOld[row["Left Glyph"]][col]
def kickoff():
# Check we have a font open and it's Qalmi-like
if not Glyphs.font:
Message("No font open", "Open a font")
return
connectables = [
x.name for x in Glyphs.font.glyphs if re.match(r".*[mif](sd?)?[0-9]+$", x.name)
]
medials = [x for x in connectables if re.match(r".*m(sd)?[0-9]+$", x)]
initials = [x for x in connectables if re.match(r".*i(sd)?[0-9]+$", x)]
finals = [x for x in connectables if re.match(r".*f(sd?)?[0-9]+$", x)]
medialstems = sorted(set([re.sub("(sd)?[0-9]+$", "", x) for x in medials]))
initialstems = sorted(set([re.sub("(sd)?[0-9]+$", "", x) for x in initials]))
if len(medials) == 0:
Message(
"Bad glyph name convention",
"Glyph names must conform to Qalmi convention: RASM{m,i,u,f}number",
)
return
connections = {}
connections["colnames"] = ["Left Glyph"]
connections["colnames"].extend(medialstems)
connections["colnames"].extend(initialstems)
# Setup dummy data
connections["rows"] = []
for row in sorted(medials, key=glyphsort):
connections["rows"].append({colname: 1 for colname in connections["colnames"]})
connections["rows"][-1]["Left Glyph"] = row
for row in sorted(finals, key=glyphsort):
connections["rows"].append({colname: 1 for colname in connections["colnames"]})
connections["rows"][-1]["Left Glyph"] = row
# Do we have some connection data already?
if Glyphs.font.userData["nastaliqConnections"]:
mergeConnections(connections, Glyphs.font.userData["nastaliqConnections"])
w = NastaliqEditor(connections)
try:
kickoff()
except Exception as e:
print("Oops!", sys.exc_info()[0], "occured.")
traceback.print_exc(file=sys.stdout)