-
Notifications
You must be signed in to change notification settings - Fork 2
/
lilypond.py
259 lines (199 loc) · 7.61 KB
/
lilypond.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
# -*- coding: utf-8 -*-
# Copyright (c) 2012 Andreas Klauer <Andreas.Klauer@metamorpher.de>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
'''
LilyPond (GNU Music Typesetter) integration addon for Anki 2.
Code is based on / inspired by libanki's LaTeX integration.
'''
# --- Imports: ---
from anki.hooks import addHook, wrap
from anki.lang import _
from anki.utils import call, checksum, stripHTML, tmpfile
from aqt import mw
from aqt.qt import *
from aqt.utils import getOnlyText, showInfo
from htmlentitydefs import entitydefs
import cgi, os, re, shutil
# --- Globals: ---
# http://lilypond.org/doc/v2.14/Documentation/usage/lilypond-output-in-other-programs#inserting-lilypond-output-into-other-programs
lilypondFile = tmpfile("lilypond", ".ly")
lilypondCmd = ["lilypond", "-dbackend=eps", "-dno-gs-load-fonts", "-dinclude-eps-fonts", "--o", lilypondFile, "--png", lilypondFile]
lilypondPattern = "%ANKI%"
lilypondSplit = "%%%"
lilypondTemplate = u"""
\\paper{
indent=0\\mm
line-width=120\\mm
oddFooterMarkup=##f
oddHeaderMarkup=##f
bookTitleMarkup = ##f
scoreTitleMarkup = ##f
}
\\relative c'' { %s }
""" % (lilypondPattern,)
lilypondTemplates = {}
lilypondDir = os.path.join(mw.pm.addonFolder(), "lilypond")
lilypondRegexp = re.compile(r"\[lilypond(|=([a-z0-9_-]+))\](.+?)\[/lilypond\]", re.DOTALL | re.IGNORECASE)
lilypondFieldRegexp = re.compile(r"lilypond(|-([a-z0-9_-]+))$", re.DOTALL | re.IGNORECASE)
lilypondNameRegexp = re.compile(r"^[a-z0-9_-]+$", re.DOTALL | re.IGNORECASE)
lilypondCache = {}
# --- Templates: ---
def tpl_file(name):
'''Build the full filename for template name.'''
return os.path.join(lilypondDir, "%s.ly" % (name,))
def setTemplate(name, content):
'''Set and save a template.'''
lilypondTemplates[name] = content
f = open(tpl_file(name), 'w')
f.write(content)
def getTemplate(name, code):
'''Load template by name and fill it with code.'''
if name is None:
name="default"
tpl = None
if name not in lilypondTemplates:
try:
tpl = open(tpl_file(name)).read()
if tpl and lilypondPattern in tpl:
lilypondTemplates[name] = tpl
except:
if name == "default":
tpl = lilypondTemplate
setTemplate("default", tpl)
finally:
if name not in lilypondTemplates:
raise IOError, "LilyPond Template %s not found or not valid." % (name,)
# Replace one or more occurences of lilypondPattern
codes = code.split(lilypondSplit)
r = lilypondTemplates[name]
for code in codes:
r = r.replace(lilypondPattern, code, 1)
return r
# --- GUI: ---
def templatefiles():
'''Produce list of template files.'''
return [f for f in os.listdir(lilypondDir)
if f.endswith(".ly")]
def addtemplate():
'''Dialog to add a new template file.'''
name = getOnlyText("Please choose a name for your new LilyPond template:")
if not lilypondNameRegexp.match(name):
showInfo("Empty template name or invalid characters.")
return
if os.path.exists(tpl_file(name)):
showInfo("A template with that name already exists.")
setTemplate(name, lilypondTemplate)
mw.addonManager.onEdit(tpl_file(name))
def lilypondMenu():
'''Extend the addon menu with lilypond template entries.'''
lm = None
for action in mw.form.menuPlugins.actions():
menu = action.menu()
if menu and menu.title() == "lilypond":
lm = menu
break
if not lm:
return
a = QAction(_("Add template..."), mw)
mw.connect(a, SIGNAL("triggered()"), addtemplate)
lm.addAction(a)
for file in templatefiles():
m = lm.addMenu(os.path.splitext(file)[0])
a = QAction(_("Edit..."), mw)
p = os.path.join(lilypondDir, file)
mw.connect(a, SIGNAL("triggered()"),
lambda p=p: mw.addonManager.onEdit(p))
m.addAction(a)
a = QAction(_("Delete..."), mw)
mw.connect(a, SIGNAL("triggered()"),
lambda p=p: mw.addonManager.onRem(p))
m.addAction(a)
# --- Functions: ---
def _lyFromHtml(ly):
'''Convert entities and fix newlines.'''
ly = re.sub(r"<(br|div|p) */?>", "\n", ly)
ly = stripHTML(ly)
ly = ly.replace(" ", " ")
for match in re.compile(r"&([a-zA-Z]+);").finditer(ly):
if match.group(1) in entitydefs:
ly = ly.replace(match.group(), entitydefs[match.group(1)])
return ly
def _buildImg(col, ly, fname):
'''Build the image PNG file itself and add it to the media dir.'''
lyfile = open(lilypondFile, "w")
lyfile.write(ly)
lyfile.close()
log = open(lilypondFile+".log", "w")
if call(lilypondCmd, stdout=log, stderr=log):
return _errMsg("lilypond")
# add to media
try:
shutil.move(lilypondFile+".png", os.path.join(col.media.dir(), fname))
except:
return _("Could not move LilyPond PNG file to media dir. No output?<br>")+_errMsg("lilypond")
def _imgLink(col, template, ly):
'''Build an <img src> link for given LilyPond code.'''
# Finalize LilyPond source.
ly = getTemplate(template, ly)
ly = ly.encode("utf8")
# Derive image filename from source.
fname = "lilypond-%s.png" % (checksum(ly),)
link = '<img src="%s">' % (fname,)
# Build image if necessary.
if os.path.exists(fname):
return link
else:
# avoid errornous cards killing performance
if fname in lilypondCache:
return lilypondCache[fname]
err = _buildImg(col, ly, fname)
if err:
lilypondCache[fname] = err
return err
else:
return link
def _errMsg(type):
'''Error message, will be displayed in the card itself.'''
msg = (_("Error executing %s.") % type) + "<br>"
try:
log = open(lilypondFile+".log", "r").read()
if log:
msg += """<small><pre style="text-align: left">""" + cgi.escape(log) + "</pre></small>"
except:
msg += _("Have you installed lilypond?")
return msg
# --- Hooks: ---
def mungeFields(fields, model, data, col):
'''Parse lilypond tags before they are displayed.'''
# Ignore duplicated mungeFields call for the answer side.
if 'FrontSide' in fields:
return fields
for fld in model['flds']:
field = fld['name']
# check field name
match = lilypondFieldRegexp.search(field)
if match \
and fields[field] != "(%s)" % (field,) \
and fields[field] != "ankiflag":
fields[field] = _imgLink(col, match.group(2), _lyFromHtml(fields[field]))
# autofill field for web:
imgfield = field.replace("lilypond", "lilypondimg", 1)
if imgfield in fields and fields[field] != fields[imgfield]:
fields[imgfield] = fields[field]
col.findReplace((data[1],), "^.*$", fields[field], regex=True, field=imgfield)
continue
# check field contents
for match in lilypondRegexp.finditer(fields[field]):
fields[field] = fields[field].replace(
match.group(), _imgLink(col, match.group(2), _lyFromHtml(match.group(3)))
)
return fields
addHook("mungeFields", mungeFields)
def profileLoaded():
'''Monkey patch the addon manager.'''
getTemplate(None, "") # creates default.ly if does not exist
mw.addonManager.rebuildAddonsMenu = wrap(mw.addonManager.rebuildAddonsMenu,
lilypondMenu)
mw.addonManager.rebuildAddonsMenu()
addHook("profileLoaded", profileLoaded)
# --- End of file. ---