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