]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
* scripts/midi2ly.py (Key.dump): pychecker cleanups.
[lilypond.git] / python / lilylib.py
1 ################################################################
2 # lilylib.py -- options and stuff
3
4 # source file of the GNU LilyPond music typesetter
5 #
6 # (c) 1998--2006 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 #                 Jan Nieuwenhuizen <janneke@gnu.org>
8
9 ###  subst:\(^\|[^._a-z]\)\(abspath\|identify\|warranty\|progress\|warning\|error\|exit\|getopt_args\|option_help_str\|options_help_str\|help\|setup_temp\|read_pipe\|system\|cleanup_temp\|strip_extension\|cp_to_dir\|mkdir_p\|init\) *(
10 ###  replace:\1ly.\2 (
11
12 ### subst: \(help_summary\|keep_temp_dir_p\|option_definitions\|original_dir\|program_name\|pseudo_filter_p\|temp_dir\|verbose_p\)
13
14 import __main__
15 import glob
16 import os
17 import re
18 import shutil
19 import string
20 import sys
21 import tempfile
22 import optparse
23
24 ################################################################
25 # Users of python modules should include this snippet
26 # and customize variables below.
27
28 # We'll suffer this path init stuff as long as we don't install our
29 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
30 # it as we do with teTeX on Red Hat Linux: set some environment var
31 # (PYTHONPATH) in profile)
32
33 # If set, LILYPONDPREFIX must take prevalence
34 # if datadir is not set, we're doing a build and LILYPONDPREFIX
35
36 datadir = '@local_lilypond_datadir@'
37 if not os.path.isdir (datadir):
38         datadir = '@lilypond_datadir@'
39 if os.environ.has_key ('LILYPONDPREFIX') :
40         datadir = os.environ['LILYPONDPREFIX']
41         while datadir[-1] == os.sep:
42                 datadir= datadir[:-1]
43
44 sys.path.insert (0, os.path.join (datadir, 'python'))
45
46
47
48
49 localedir = '@localedir@'
50 try:
51         import gettext
52         gettext.bindtextdomain ('lilypond', localedir)
53         gettext.textdomain ('lilypond')
54         _ = gettext.gettext
55 except:
56         def _ (s):
57                 return s
58 underscore = _
59
60 def progress (s):
61         sys.stderr.write (s)
62
63 def warning (s):
64         sys.stderr.write (__main__.program_name + ": " + _ ("warning: %s") % s + '\n')
65
66 def error (s):
67         sys.stderr.write (__main__.program_name + ": " + _ ("error: %s") % s + '\n')
68         
69 def exit (i):
70         be_verbose = get_global_option('verbose_p', 'verbose')
71         if be_verbose:
72                 raise _ ('Exiting (%d)...') % i
73         else:
74                 sys.exit (i)
75         
76 def lilypond_version (binary):
77         p = read_pipe ('%s --version ' % binary)
78
79         ls = p.split ('\n')
80         v= '<not found>'
81         for l in ls:
82                 m = re.search ('GNU LilyPond ([0-9a-z.]+)', p)
83                 if m:
84                         v = m.group (1)
85                         
86         return v
87         
88 def lilypond_version_check (binary, req):
89         if req[0] <> '@' :
90                 v = lilypond_version (binary)
91                 if v <> req:
92                         error (_("Binary %s has version %s, looking for version %s") % \
93                                (binary, v, req))
94                         sys.exit (1)
95         
96         
97 def setup_temp ():
98         
99         ''' Create a temporary directory, and return its name. '''
100         
101         if not __main__.keep_temp_dir_p:
102                 __main__.temp_dir = tempfile.mktemp (__main__.program_name)
103         try:
104                 os.mkdir (__main__.temp_dir, 0700)
105         except OSError:
106                 pass
107
108         return __main__.temp_dir
109
110 def command_name (cmd):
111         # Strip all stuf after command,
112         # deal with "((latex ) >& 1 ) .." too
113         cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
114         return os.path.basename (cmd)
115
116 def error_log (name):
117         name = re.sub('[^a-z]','x', name)
118         return tempfile.mktemp ('%s.errorlog' % name)
119
120 def read_pipe (cmd, mode = 'r'):
121         
122         
123         redirect = ''
124         error_log_file = ''
125         if be_verbose:
126                 progress (_ ("Opening pipe `%s\'") % cmd)
127         else:
128                 error_log_file = error_log (command_name (cmd))
129                 redirect = ' 2>%s' % error_log_file
130                 
131         pipe = os.popen (cmd + redirect, mode)
132         output = pipe.read ()
133         status = pipe.close ()
134         # successful pipe close returns 'None'
135         if not status:
136                 status = 0
137         signal = 0x0f & status
138         exit_status = status >> 8
139
140         if status:
141                 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
142                 
143                 if not be_verbose:
144                         contents = open (error_log_file).read ()
145                         if contents:
146                                 error (_ ("The error log is as follows:"))
147                                 sys.stderr.write (contents)
148
149                 # Ugh. code dup
150                 if error_log_file:
151                         os.unlink (error_log_file)
152
153                 exit (1)
154                 
155         if be_verbose:
156                 progress ('\n')
157
158         if error_log_file:
159                 os.unlink (error_log_file)
160                 
161         return output
162
163 def get_global_option (old, new):
164         try:
165                 return __main__.__dict__[old]
166         except KeyError:
167                 return __main__.global_options.__dict__[new]
168
169 def system (cmd, ignore_error = 0, progress_p = 0):
170         
171         '''System CMD.  If IGNORE_ERROR, do not complain when CMD
172 returns non zero.  If PROGRESS_P, always show progress.
173
174 RETURN VALUE
175
176 Exit status of CMD '''
177
178         name = command_name (cmd)
179         error_log_file = ''
180
181         ## UGH
182         be_verbose = get_global_option('verbose_p', 'verbose')
183         pseudo_filter = get_global_option ('pseudo_filter_p', 'pseudo_filter')
184         
185         if be_verbose:
186                 progress_p = 1
187                 progress (_ ("Invoking `%s\'") % cmd)
188         else:
189                 progress ( _("Running %s...") % name)
190
191         redirect = ''
192         if not progress_p:
193                 error_log_file = error_log (name)
194                 redirect = ' 1>/dev/null 2>' + error_log_file
195         elif pseudo_filter:
196                 redirect = ' 1>/dev/null'
197
198         status = os.system (cmd + redirect)
199         signal = 0x0f & status
200         exit_status = status >> 8
201         
202         if status:
203                 
204                 exit_type =  'status %d' % exit_status
205                 if signal:
206                         exit_type = 'signal %d' % signal 
207                 
208                 msg = _ ("`%s\' failed (%s)") % (name, exit_type)
209                 if ignore_error:
210                         if be_verbose:
211                                 warning (msg + ' ' + _ ("(ignored)"))
212                 else:
213                         error (msg)
214                         if not progress_p and error_log_file:
215                                 error (_ ("The error log is as follows:"))
216                                 sys.stderr.write (open (error_log_file).read ())
217                         if error_log_file:
218                                 os.unlink (error_log_file)
219                         exit (1)
220
221         if error_log_file:
222                 os.unlink (error_log_file)
223         progress ('\n')
224         return status
225
226 def cleanup_temp ():
227         be_verbose = get_global_option('verbose_p', 'verbose')
228         if not __main__.keep_temp_dir_p:
229                 if be_verbose:
230                         progress (_ ("Cleaning %s...") % __main__.temp_dir)
231                 shutil.rmtree (__main__.temp_dir)
232                 if be_verbose:
233                         progress ('\n')
234
235
236 def strip_extension (f, ext):
237         (p, e) = os.path.splitext (f)
238         if e == ext:
239                 e = ''
240         return p + e
241
242
243 def cp_to_dir (pattern, dir):
244         "Copy files matching re PATTERN from cwd to DIR"
245         
246         # Duh.  Python style portable: cp *.EXT OUTDIR
247         # system ('cp *.%s %s' % (ext, outdir), 1)
248
249         files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
250         map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
251
252
253 def search_exe_path (name):
254         p = os.environ['PATH']
255         exe_paths = string.split (p, ':')
256         for e in exe_paths:
257                 full = os.path.join (e, name)
258                 if os.path.exists (full):
259                         return full
260         return None
261
262
263 def mkdir_p (dir, mode=0777):
264         if not os.path.isdir (dir):
265                 makedirs (dir, mode)
266
267 def print_environment ():
268         for (k,v) in os.environ.items ():
269                 sys.stderr.write ("%s=\"%s\"\n" % (k, v)) 
270
271
272 def ps_page_count (ps_name):
273         header = open (ps_name).read (1024)
274         m = re.search ('\n%%Pages: ([0-9]+)', header)
275         if m:
276                 return string.atoi (m.group (1))
277         return 0
278
279 def make_ps_images (ps_name, resolution = 90, papersize = "a4",
280                     rename_page1_p = 0):
281         base = os.path.basename (re.sub (r'\.e?ps', '', ps_name))
282         header = open (ps_name).read (1024)
283
284         png1 = base + '.png'
285         pngn = base + '-page%d.png'
286         output_file = pngn
287         multi_page = re.search ('\n%%Pages: ', header)
288
289         # png16m is because Lily produces color nowadays.
290         if not multi_page:
291
292                 # GS can produce empty 2nd page if pngn is used.
293                 output_file = png1
294                 cmd = r'''gs\
295                 -dEPSCrop\
296                 -dGraphicsAlphaBits=4\
297                 -dNOPAUSE\
298                 -dTextAlphaBits=4\
299                 -sDEVICE=png16m\
300                 -sOutputFile='%(output_file)s'\
301                 -sPAPERSIZE=%(papersize)s\
302                 -q\
303                 -r%(resolution)d\
304                 '%(ps_name)s'\
305                 -c showpage\
306                 -c quit ''' % vars ()
307         else:
308                 cmd = r'''gs\
309                 -s\
310                 -dGraphicsAlphaBits=4\
311                 -dNOPAUSE\
312                 -dTextAlphaBits=4\
313                 -sDEVICE=png16m\
314                 -sOutputFile='%(output_file)s'\
315                 -sPAPERSIZE=%(papersize)s\
316                 -q\
317                 -r%(resolution)d\
318                 '%(ps_name)s'\
319                 -c quit''' % vars ()
320
321         remove = glob.glob (png1) + glob.glob (base + '-page*.png')
322         map (os.unlink, remove)
323
324         status = system (cmd)
325         signal = 0xf & status
326         exit_status = status >> 8
327
328         if status:
329                 remove = glob.glob (png1) + glob.glob (base + '-page*.png')
330                 map (os.unlink, remove)
331                 error (_ ("%s exited with status: %d") % ('GS', status))
332                 exit (1)
333
334         if rename_page1_p and multi_page:
335                 os.rename (pngn % 1, png1)
336         files = glob.glob (png1) + glob.glob (re.sub ('%d', '*', pngn))
337         return files
338
339 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
340     def format_heading(self, heading):
341             if heading:
342                     return heading[0].upper() + heading[1:] + ':\n'
343             return ''
344     def format_option_strings(self, option):
345             sep = ' '
346             if option._short_opts and option._long_opts:
347                     sep = ','
348
349             metavar = ''
350             if option.takes_value():
351                     metavar = '=%s' % option.metavar or option.dest.upper()
352
353             return "%3s%s %s%s" % (" ".join (option._short_opts),
354                                    sep,
355                                    " ".join (option._long_opts),
356                                    metavar)
357
358     def format_usage(self, usage):
359         return _("Usage: %s\n") % usage
360     
361     def format_description(self, description):
362             return description
363
364 def get_option_parser (*args, **kwargs): 
365         p = optparse.OptionParser (*args, **kwargs)
366         p.formatter = NonDentedHeadingFormatter () 
367         return p