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