1 ################################################################
2 # lilylib.py -- options and stuff
4 # source file of the GNU LilyPond music typesetter
6 # (c) 1998--2003 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 # Jan Nieuwenhuizen <janneke@gnu.org>
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\) *(
12 ### subst: \(help_summary\|keep_temp_dir_p\|option_definitions\|original_dir\|program_name\|pseudo_filter_p\|temp_dir\|verbose_p\)
21 ################################################################
22 # Users of python modules should include this snippet
23 # and customize variables below.
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)
30 # If set, LILYPONDPREFIX must take prevalence
31 # if datadir is not set, we're doing a build and LILYPONDPREFIX
33 import getopt, os, sys
34 datadir = '@local_lilypond_datadir@'
35 if not os.path.isdir (datadir):
36 datadir = '@lilypond_datadir@'
37 if os.environ.has_key ('LILYPONDPREFIX') :
38 datadir = os.environ['LILYPONDPREFIX']
39 while datadir[-1] == os.sep:
42 sys.path.insert (0, os.path.join (datadir, 'python'))
47 if __name__ == '__main__':
53 program_name = 'unset'
55 original_dir = os.getcwd ()
56 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
60 help_summary = _ ("lilylib module")
62 option_definitions = [
63 ('', 'h', 'help', _ ("print this help")),
67 ################################################################
69 # Handle bug in Python 1.6-2.1
71 # there are recursion limits for some patterns in Python 1.6 til 2.1.
72 # fix this by importing pre instead. Fix by Mats.
74 if float (sys.version[0:3]) <= 2.1:
84 # Attempt to fix problems with limited stack size set by Python!
85 # Sets unlimited stack size. Note that the resource module only
86 # is available on UNIX.
89 resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
93 localedir = '@localedir@'
96 gettext.bindtextdomain ('lilypond', localedir)
97 gettext.textdomain ('lilypond')
105 port.write ('%s (GNU LilyPond) %s\n' % (__main__.program_name, __main__.program_version))
108 identify (sys.stdout)
109 sys.stdout.write ('\n')
110 sys.stdout.write (_ ("Copyright (c) %s by") % '1998--2004')
111 sys.stdout.write ('\n')
112 map (lambda x: sys.stdout.write (' %s\n' % x), __main__.copyright)
113 sys.stdout.write ('\n')
114 sys.stdout.write (_ ("Distributed under terms of the GNU General Public License."))
115 sys.stdout.write ('\n')
116 sys.stdout.write (_ ("It comes with NO WARRANTY."))
117 sys.stdout.write ('\n')
123 sys.stderr.write (__main__.program_name + ": " + _ ("warning: %s") % s + '\n')
126 sys.stderr.write (__main__.program_name + ": " + _ ("error: %s") % s + '\n')
129 if __main__.verbose_p:
130 raise _ ('Exiting (%d)...') % i
135 def getopt_args (opts):
136 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
151 def option_help_str (o):
152 '''Transform one option description (4-tuple ) into neatly formatted string'''
170 return ' ' + sh + sep + long + arg
173 def options_help_str (opts):
174 '''Convert a list of options into a neatly formatted string'''
180 s = option_help_str (o)
181 strs.append ((s, o[3]))
187 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
191 ls = [(_ ("Usage: %s [OPTIONS]... FILE") % __main__.program_name),
193 (__main__.help_summary),
197 (options_help_str (__main__.option_definitions)),
199 (_ ("Report bugs to %s.") % 'bug-lilypond@gnu.org'),
201 map (sys.stdout.write, ls)
203 def lilypond_version (binary):
204 p = read_pipe ('%s --version ' % binary)
209 m = re.search ('GNU LilyPond ([0-9a-z.]+)', p)
215 def lilypond_version_check (binary, req):
217 v = lilypond_version (binary)
219 error (_("Binary %s has version %s, looking for version %s") % \
226 ''' Create a temporary directory, and return its name. '''
228 if not __main__.keep_temp_dir_p:
229 __main__.temp_dir = tempfile.mktemp (__main__.program_name)
231 os.mkdir (__main__.temp_dir, 0700)
235 return __main__.temp_dir
237 def command_name (cmd):
239 # deal with "((latex ) >& 1 ) .." too
240 cmd = re.match ("([\(\)]*)([^ ]*)", cmd).group(2)
241 return os.path.split (cmd)[1]
243 def error_log (name):
244 name = re.sub('[^a-z]','x', name)
245 return tempfile.mktemp ('%s.errorlog' % name)
247 def read_pipe (cmd, mode = 'r'):
252 if __main__.verbose_p:
253 progress (_ ("Opening pipe `%s\'") % cmd)
255 error_log_file = error_log (command_name (cmd))
256 redirect = ' 2>%s' % error_log_file
258 pipe = os.popen (cmd + redirect, mode)
259 output = pipe.read ()
260 status = pipe.close ()
261 # successful pipe close returns 'None'
264 signal = 0x0f & status
265 exit_status = status >> 8
268 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
270 if not __main__.verbose_p:
271 contents = open (error_log_file).read ()
273 error (_ ("The error log is as follows:"))
274 sys.stderr.write (contents)
278 os.unlink (error_log_file)
282 if __main__.verbose_p:
286 os.unlink (error_log_file)
290 def system (cmd, ignore_error = 0, progress_p = 0):
292 '''System CMD. If IGNORE_ERROR, do not complain when CMD
293 returns non zero. If PROGRESS_P, always show progress.
297 Exit status of CMD '''
299 name = command_name (cmd)
302 if __main__.verbose_p:
304 progress (_ ("Invoking `%s\'") % cmd)
306 progress ( _("Running %s...") % name)
310 error_log_file = error_log (name)
311 redirect = ' 1>/dev/null 2>' + error_log_file
312 elif __main__.pseudo_filter_p:
313 redirect = ' 1>/dev/null'
315 status = os.system (cmd + redirect)
316 signal = 0x0f & status
317 exit_status = status >> 8
321 exit_type = 'status %d' % exit_status
323 exit_type = 'signal %d' % signal
325 msg = _ ("`%s\' failed (%s)") % (name, exit_type)
327 if __main__.verbose_p:
328 warning (msg + ' ' + _ ("(ignored)"))
331 if not progress_p and error_log_file:
332 error (_ ("The error log is as follows:"))
333 sys.stderr.write (open (error_log_file).read ())
335 os.unlink (error_log_file)
339 os.unlink (error_log_file)
344 if not __main__.keep_temp_dir_p:
345 if __main__.verbose_p:
346 progress (_ ("Cleaning %s...") % __main__.temp_dir)
347 shutil.rmtree (__main__.temp_dir)
348 if __main__.verbose_p:
352 def strip_extension (f, ext):
353 (p, e) = os.path.splitext (f)
359 def cp_to_dir (pattern, dir):
360 "Copy files matching re PATTERN from cwd to DIR"
362 # Duh. Python style portable: cp *.EXT OUTDIR
363 # system ('cp *.%s %s' % (ext, outdir), 1)
365 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
366 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
369 # Python < 1.5.2 compatibility
371 # On most platforms, this is equivalent to
372 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
374 if os.path.__dict__.has_key ('abspath'):
375 abspath = os.path.abspath
378 return os.path.normpath (os.path.join (os.getcwd (), path))
380 if os.__dict__.has_key ('makedirs'):
381 makedirs = os.makedirs
383 def makedirs (dir, mode=0777):
384 system ('mkdir -p %s' % dir)
387 def mkdir_p (dir, mode=0777):
388 if not os.path.isdir (dir):
394 # tex needs lots of memory, more than it gets by default on Debian
395 non_path_environment = {
396 'extra_mem_top' : '1000000',
397 'extra_mem_bottom' : '1000000',
398 'pool_size' : '250000',
401 def setup_environment ():
404 kpse = read_pipe ('kpsexpand \$TEXMF')
405 texmf = re.sub ('[ \t\n]+$','', kpse)
406 type1_paths = read_pipe ('kpsewhich -expand-path=\$T1FONTS')
409 # TODO: * prevent multiple addition.
410 # * clean TEXINPUTS, MFINPUTS, TFMFONTS,
411 # as these take prevalence over $TEXMF
412 # and thus may break tex run?
414 'TEXMF' : "{%s,%s}" % (datadir, texmf) ,
415 'GS_FONTPATH' : type1_paths,
416 'GS_LIB' : datadir + '/ps',
419 # $TEXMF is special, previous value is already taken care of
420 if os.environ.has_key ('TEXMF'):
421 del os.environ['TEXMF']
423 for key in environment.keys ():
424 val = environment[key]
425 if os.environ.has_key (key):
426 val = os.environ[key] + os.pathsep + val
427 os.environ[key] = val
429 for key in non_path_environment.keys ():
430 val = non_path_environment[key]
431 os.environ[key] = val
433 def print_environment ():
434 for (k,v) in os.environ.items ():
435 sys.stderr.write ("%s=\"%s\"\n" % (k, v))
437 BOUNDING_BOX_RE = '^%%BoundingBox: (-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)'
438 def get_bbox (filename):
439 bbox = filename + '.bbox'
440 ## -sOutputFile does not work with bbox?
441 cmd = 'gs -sDEVICE=bbox -q -dNOPAUSE %s -c quit 2>%s' % \
443 system (cmd, progress_p = 1)
444 box = open (bbox).read ()
445 m = re.match (BOUNDING_BOX_RE, box)
448 gr = map (string.atoi, m.groups ())
453 def make_ps_images (ps_name, resolution = 90):
455 ## have better algorithm for deciding when to crop page,
456 ## and when to show full page
457 base = re.sub (r'\.e?ps', '', ps_name)
459 header = open (ps_name).read (1024)
461 match = re.match (BOUNDING_BOX_RE, header)
464 bbox = map (string.atoi, match.groups ())
466 multi_page = re.search ('\n%%Pages: ', header)
469 if multi_page == None:
472 bbox = get_bbox (ps_name)
474 trans_ps = ps_name + '.trans.ps'
475 output_file = re.sub (r'\.e?ps', '.png', ps_name)
477 # need to have margin, otherwise edges of letters will
481 fo = open (trans_ps, 'w')
482 fo.write ('%d %d translate\n' % (-bbox[0] + margin,
486 x = (2* margin + bbox[2] - bbox[0]) \
488 y = (2* margin + bbox[3] - bbox[1]) \
495 cmd = r'''gs -g%dx%d -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -q -sOutputFile=%s -r%d -dNOPAUSE %s %s -c quit ''' % \
496 (x, y, output_file, resolution, trans_ps, ps_name)
498 rms = glob.glob (base + '-page*.png')
501 output_file = re.sub (r'\.e?ps', '-page%d.png', ps_name)
503 rmfile = base + '.png'
504 if os.path.isfile (rmfile):
507 cmd = r'''gs -s -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -q -sOutputFile=%s -dNOPAUSE -r%d %s -c quit''' % (output_file,
510 status = system (cmd)
511 signal = 0xf & status
512 exit_status = status >> 8
517 error (_ ("Removing output file"))
521 cmd = r'''gs -s -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -q -sOutputFile=%s -dNOPAUSE -r%d %s -c quit''' % (output_file,