Debian Codegraph @

texmf-dist/scripts/lilyglyphs/lily-image-commands.py

raw
1 #!/usr/bin/env python
2
3 # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 # %
5 # This file is part of the 'lilyglyphs' LaTeX package. %
6 # ========== %
7 # %
8 # https://github.com/openlilylib/lilyglyphs %
9 # http://www.openlilylib.org/lilyglyphs %
10 # %
11 # Copyright 2012-2020 Urs Liska and others, [email protected] %
12 # %
13 # 'lilyglyphs' is free software: you can redistribute it and/or modify %
14 # it under the terms of the LaTeX Project Public License, either %
15 # version 1.3 of this license or (at your option) any later version. %
16 # You may find the latest version of this license at %
17 # http://www.latex-project.org/lppl.txt %
18 # more information on %
19 # http://latex-project.org/lppl/ %
20 # and version 1.3 or later is part of all distributions of LaTeX %
21 # version 2005/12/01 or later. %
22 # %
23 # This work has the LPPL maintenance status 'maintained'. %
24 # The Current Maintainer of this work is Urs Liska (see above). %
25 # %
26 # This work consists of the files listed in the file 'manifest.txt' %
27 # which can be found in the 'license' directory. %
28 # %
29 # This program is distributed in the hope that it will be useful, %
30 # but WITHOUT ANY WARRANTY; without even the implied warranty of %
31 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. %
32 # %
33 # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
34
35 import os, sys, getopt, datetime, subprocess, argparse, lilyglyphs_common as lg
36
37
38
39 # ###############
40 # string to be printed before the actual command
41 lily_src_prefix = """\\version "2.16.2"
42
43 #(set-global-staff-size 14)
44
45 \paper {
46 indent = 0
47 }
48 \header {
49 tagline = ""
50 }
51
52 """
53
54 # string to be printed after the actual command definition
55 lily_src_score = """
56 \\score {
57 \\new Staff \\with {
58 \\remove "Staff_symbol_engraver"
59 \\remove "Clef_engraver"
60 \\remove "Time_signature_engraver"
61 }
62 """
63
64 def main():
65 """Do the actual work of the script"""
66 print('')
67 print('buildglyphimages.py,')
68 print('Part of lilyglyphs.')
69 print('')
70
71 # set CWD and ensure the necessary subdirs are present
72 check_paths()
73 print('')
74
75 # load and parse input file
76 lg.read_input_file(in_file)
77 read_entries()
78 print('')
79
80 # generate LilyPond source files for each command
81 # and compile them
82 write_lily_src_files()
83 print('')
84 lg.compile_lily_files()
85 print('')
86
87 # remove intermediate files and move pdfs to pdf directory
88 lg.cleanup_lily_files()
89 print('')
90
91 # generate latex commands and example code
92 # and write them to the output file
93 lg.generate_latex_commands()
94 print('')
95 write_latex_file()
96
97
98 def check_paths():
99 """Sets CWD to 'glyphimages' subdir or root of lilyglyphs_private
100 and makes sure that the necessary subdirectories are present"""
101
102 # one level above 'definitions' is 'glyphimages'
103 os.chdir(os.path.join(in_path, '..'))
104
105 # check the presence of the necessary subdirectories
106 # and create them if necessary
107 # (otherwise we'll get errors when trying to write in them)
108 ls = os.listdir('.')
109 if not lg.dir_lysrc in ls:
110 os.mkdir(lg.dir_lysrc)
111 if not lg.dir_pdfs in ls:
112 os.mkdir(lg.dir_pdfs)
113 if not lg.dir_cmd in ls:
114 os.mkdir(lg.dir_cmd)
115
116 def cmd_filename(cmd_name):
117 if cmd_name.startswith('lily'):
118 return cmd_name[:4] + '-' + cmd_name[4:]
119 elif cmd_name.startswith('lily-'):
120 return cmd_name
121 else:
122 return 'lily-' + cmd_name
123
124 # set default scale and raise arguments to empty
125 scale = ''
126 rais = ''
127
128 def read_entries():
129 """Parses the input source file and extracts glyph entries"""
130 print('Read entries of LilyPond commands:')
131 for i in range(len(lg.definitions_file)):
132 if '%%lilyglyphs' in lg.definitions_file[i]:
133 i = read_entry(i)
134 print(lg.lily_files)
135
136 def read_entry(i):
137 """Reads a single glyph entry from the input file and stores it
138 in the global dictionary lg.in_cmds"""
139 global scale, rais
140 # read comment line(s)
141 i += 1
142 is_protected = False
143 comment = []
144 # loop over the comment line(s)
145 while i < len(lg.definitions_file):
146 line = lg.definitions_file[i].strip()
147 # check for 'protected' entries that shouldn't be processed newly
148 if not line[0] == '%':
149 break
150 elif '%%protected' in line:
151 is_protected = True
152 elif 'scale=' in line:
153 dummy, scale = line.split('=')
154 elif 'raise=' in line:
155 dummy, rais = line.split('=')
156 else:
157 line = line[1:].strip()
158 comment.append(line)
159 i += 1
160
161 # remove any empty lines
162 while len(lg.definitions_file[i].strip()) == 0:
163 i += 1
164
165 # read command name
166 line = lg.definitions_file[i].strip()
167 cmd_name = line[: line.find('=') - 1]
168 print('- ' + cmd_name, end=' ')
169 if is_protected:
170 print('(protected and skipped)')
171 else:
172 print('') #(for line break only)
173
174 # read actual command until we find a line the begins with a closing curly bracket
175 i += 1
176 lilySrc = []
177 while lg.definitions_file[i][0] != '}':
178 lilySrc.append(lg.definitions_file[i])
179 i += 1
180 if not is_protected:
181 lg.in_cmds[cmd_name] = {}
182 lg.in_cmds[cmd_name]['comment'] = comment
183 lg.in_cmds[cmd_name]['lilySrc'] = lilySrc
184 lg.in_cmds[cmd_name]['element'] = cmd_filename(cmd_name)
185 lg.in_cmds[cmd_name]['type'] = 'image'
186 if scale:
187 lg.in_cmds[cmd_name]['scale'] = scale
188 if rais:
189 lg.in_cmds[cmd_name]['raise'] = rais
190
191 lg.lily_files.append(cmd_filename(cmd_name))
192 return i
193
194
195 def usage():
196 print("""buildglyphimages. Part of the lilyglyphs package.
197 Parses a template file, creates
198 single .ly files from it, uses LilyPond to create single glyph
199 pdf files and set up template files to be used in LaTeX.
200 The input file has to be located in the glyphimages folder
201 of either the lilyglyph package itself or of a copy of
202 the lilyglyphs_private directory structure contained in the
203 distribution.
204 For detailed instructions refer to the manual.
205 Usage:
206 buildglyphimages.py in-file-name.
207 """)
208
209 def write_file_info(name, fout):
210 """Formats file specific information for the lilyPond source file"""
211 long_line = '% This file defines a single glyph to be created with LilyPond: %\n'
212 width = len(long_line) - 1
213 header = '%' * width + '\n'
214 spacer = '%' + ' ' * (width - 2) + '%\n'
215 padding = width - len(name) - 8
216 fout.write(header)
217 fout.write(spacer)
218 fout.write(long_line)
219 fout.write(spacer)
220 fout.write('% ' + name + '.ly' + ' ' * padding + '%\n')
221 fout.write(spacer)
222 fout.write(header)
223 fout.write(lg.signature())
224 fout.write('\n\n')
225
226 def write_latex_file():
227 """Composes LaTeX file and writes it to disk"""
228 print('Generate LaTeX file')
229 print(lg.dir_cmd, in_basename)
230 lg.write_latex_file(os.path.join(os.getcwd(), lg.dir_cmd, in_basename + '.tex'))
231
232 def write_lily_src_files():
233 """Generates one .ly file for each found new command"""
234 skip_cmds = []
235 print('Write .ly files for each entry:')
236 for cmd_name in lg.in_cmds:
237 print('- ' + cmd_name)
238 gen_src_name = os.path.join(lg.dir_lysrc, cmd_filename(cmd_name) + '.ly')
239 # handle existing commands
240 if os.path.exists(gen_src_name):
241 action = ''
242 while not (action == 'Y' or action == 'N'):
243 action = input('already present. Overwrite (y/n)? ')
244 action = action.upper()
245 if action == 'N':
246 skip_cmds.append(cmd_name)
247 continue
248
249 # open a single lily src file for write access
250 fout = open(gen_src_name, 'w')
251
252 #output the license information
253 fout.write(lg.lilyglyphs_copyright_string)
254 fout.write('\n')
255
256 #output information on the actual file
257 write_file_info(cmd_name, fout)
258
259 #write the default LilyPond stuff
260 fout.write(lily_src_prefix)
261
262 # write the comment for the command
263 fout.write('%{\n')
264 for line in lg.in_cmds[cmd_name]['comment']:
265 fout.write(line + '\n')
266 fout.write('%}\n\n')
267
268 # write the actual command
269 fout.write(cmd_name + ' = {\n')
270 for line in lg.in_cmds[cmd_name]['lilySrc']:
271 fout.write(line + '\n')
272 fout.write('}\n')
273
274 # write the score definition
275 fout.write(lily_src_score)
276
277 # finish the LilyPond file
278 fout.write(' \\' + cmd_name + '\n')
279 fout.write('}\n\n')
280
281 fout.close()
282
283 # remove skipped commands from in_cmds
284 print(skip_cmds)
285 for cmd_name in skip_cmds:
286 del lg.in_cmds[cmd_name]
287 lg.lily_files.remove(cmd_filename(cmd_name))
288
289 # ####################################
290 # Finally launch the program
291 if __name__ == "__main__":
292
293 # parse command line arguments
294 parser = argparse.ArgumentParser(
295 description='Process templates to LilyPond input files,' +
296 'compile these and generate LaTeX commands.',
297 parents=[lg.common_arguments])
298 parser.add_argument('i',
299 type=lg.is_file,
300 metavar='INPUT',
301 help='File with command templates.')
302 args = parser.parse_args()
303
304 # if we have exactly one existing file
305 # join its components and run the program
306
307 # process filename argument, providing absolute path
308 script_path, script_name = os.path.split(sys.argv[0])
309
310 in_file = os.path.join(os.getcwd(), vars(args)['i'])
311 # check if the input file is in the right place
312 # this has to be the definitions subdir of
313 # the package directory or the lilyglyphs_private dir
314 in_path, in_filename = os.path.split(in_file)
315 in_path = os.path.normpath(in_path)
316 if not (('lilyglyphs' in in_path) and (in_path.endswith('definitions'))):
317 print('File in the wrong location: ' + in_path)
318 usage()
319 sys.exit(2)
320 in_basename, in_ext = os.path.splitext(in_filename)
321 main()