1 ################################################################
2 # lilylib.py -- options and stuff
4 # source file of the GNU LilyPond music typesetter
6 # (c) 1998--2005 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
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
:
44 sys
.path
.insert (0, os
.path
.join (datadir
, 'python'))
49 if __name__
== '__main__':
55 program_name
= 'unset'
57 original_dir
= os
.getcwd ()
58 temp_dir
= os
.path
.join (original_dir
, '%s.dir' % program_name
)
62 help_summary
= _ ("lilylib module")
64 option_definitions
= [
65 ('', 'h', 'help', _ ("print this help")),
69 ################################################################
71 # Handle bug in Python 1.6-2.1
73 # there are recursion limits for some patterns in Python 1.6 til 2.1.
74 # fix this by importing pre instead. Fix by Mats.
76 if float (sys
.version
[0:3]) <= 2.1:
86 # Attempt to fix problems with limited stack size set by Python!
87 # Sets unlimited stack size. Note that the resource module only
88 # is available on UNIX.
91 resource
.setrlimit (resource
.RLIMIT_STACK
, (-1, -1))
95 localedir
= '@localedir@'
98 gettext
.bindtextdomain ('lilypond', localedir
)
99 gettext
.textdomain ('lilypond')
107 port
.write ('%s (GNU LilyPond) %s\n' % (__main__
.program_name
, __main__
.program_version
))
110 identify (sys
.stdout
)
111 sys
.stdout
.write ('\n')
112 sys
.stdout
.write (_ ("Copyright (c) %s by") % '1998--2005')
113 sys
.stdout
.write ('\n')
114 map (lambda x
: sys
.stdout
.write (' %s\n' % x
), __main__
.copyright
)
115 sys
.stdout
.write ('\n')
116 sys
.stdout
.write (_ ("Distributed under terms of the GNU General Public License."))
117 sys
.stdout
.write ('\n')
118 sys
.stdout
.write (_ ("It comes with NO WARRANTY."))
119 sys
.stdout
.write ('\n')
125 sys
.stderr
.write (__main__
.program_name
+ ": " + _ ("warning: %s") % s
+ '\n')
128 sys
.stderr
.write (__main__
.program_name
+ ": " + _ ("error: %s") % s
+ '\n')
131 if __main__
.verbose_p
:
132 raise _ ('Exiting (%d)...') % i
136 def getopt_args (opts
):
137 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
152 def option_help_str (o
):
153 '''Transform one option description (4-tuple ) into neatly formatted string'''
171 return ' ' + sh
+ sep
+ long + arg
174 def options_help_str (opts
):
175 '''Convert a list of options into a neatly formatted string'''
181 s
= option_help_str (o
)
182 strs
.append ((s
, o
[3]))
189 for ss
in re
.split ('\n\s*', s
[1]):
191 str = str + '%s%s%s\n' \
192 % (s
[0], ' ' * (w
- len (s
[0]) + 3), ss
)
195 str = str + '%s%s\n' \
196 % (' ' * (w
+ 3), ss
)
200 ls
= [(_ ("Usage: %s [OPTIONS]... FILE") % __main__
.program_name
),
202 (__main__
.help_summary
),
206 (options_help_str (__main__
.option_definitions
)),
208 (_ ("Report bugs to %s.") % 'bug-lilypond@gnu.org'),
210 map (sys
.stdout
.write
, ls
)
212 def lilypond_version (binary
):
213 p
= read_pipe ('%s --version ' % binary
)
218 m
= re
.search ('GNU LilyPond ([0-9a-z.]+)', p
)
224 def lilypond_version_check (binary
, req
):
226 v
= lilypond_version (binary
)
228 error (_("Binary %s has version %s, looking for version %s") % \
235 ''' Create a temporary directory, and return its name. '''
237 if not __main__
.keep_temp_dir_p
:
238 __main__
.temp_dir
= tempfile
.mktemp (__main__
.program_name
)
240 os
.mkdir (__main__
.temp_dir
, 0700)
244 return __main__
.temp_dir
246 def command_name (cmd
):
247 # Strip all stuf after command,
248 # deal with "((latex ) >& 1 ) .." too
249 cmd
= re
.match ('([\(\)]*)([^\\\ ]*)', cmd
).group (2)
250 return os
.path
.basename (cmd
)
252 def error_log (name
):
253 name
= re
.sub('[^a-z]','x', name
)
254 return tempfile
.mktemp ('%s.errorlog' % name
)
256 def read_pipe (cmd
, mode
= 'r'):
261 if __main__
.verbose_p
:
262 progress (_ ("Opening pipe `%s\'") % cmd
)
264 error_log_file
= error_log (command_name (cmd
))
265 redirect
= ' 2>%s' % error_log_file
267 pipe
= os
.popen (cmd
+ redirect
, mode
)
268 output
= pipe
.read ()
269 status
= pipe
.close ()
270 # successful pipe close returns 'None'
273 signal
= 0x0f & status
274 exit_status
= status
>> 8
277 error (_ ("`%s\' failed (%d)") % (cmd
, exit_status
))
279 if not __main__
.verbose_p
:
280 contents
= open (error_log_file
).read ()
282 error (_ ("The error log is as follows:"))
283 sys
.stderr
.write (contents
)
287 os
.unlink (error_log_file
)
291 if __main__
.verbose_p
:
295 os
.unlink (error_log_file
)
299 def system (cmd
, ignore_error
= 0, progress_p
= 0):
301 '''System CMD. If IGNORE_ERROR, do not complain when CMD
302 returns non zero. If PROGRESS_P, always show progress.
306 Exit status of CMD '''
308 name
= command_name (cmd
)
311 if __main__
.verbose_p
:
313 progress (_ ("Invoking `%s\'") % cmd
)
315 progress ( _("Running %s...") % name
)
319 error_log_file
= error_log (name
)
320 redirect
= ' 1>/dev/null 2>' + error_log_file
321 elif __main__
.pseudo_filter_p
:
322 redirect
= ' 1>/dev/null'
324 status
= os
.system (cmd
+ redirect
)
325 signal
= 0x0f & status
326 exit_status
= status
>> 8
330 exit_type
= 'status %d' % exit_status
332 exit_type
= 'signal %d' % signal
334 msg
= _ ("`%s\' failed (%s)") % (name
, exit_type
)
336 if __main__
.verbose_p
:
337 warning (msg
+ ' ' + _ ("(ignored)"))
340 if not progress_p
and error_log_file
:
341 error (_ ("The error log is as follows:"))
342 sys
.stderr
.write (open (error_log_file
).read ())
344 os
.unlink (error_log_file
)
348 os
.unlink (error_log_file
)
353 if not __main__
.keep_temp_dir_p
:
354 if __main__
.verbose_p
:
355 progress (_ ("Cleaning %s...") % __main__
.temp_dir
)
356 shutil
.rmtree (__main__
.temp_dir
)
357 if __main__
.verbose_p
:
361 def strip_extension (f
, ext
):
362 (p
, e
) = os
.path
.splitext (f
)
368 def cp_to_dir (pattern
, dir):
369 "Copy files matching re PATTERN from cwd to DIR"
371 # Duh. Python style portable: cp *.EXT OUTDIR
372 # system ('cp *.%s %s' % (ext, outdir), 1)
374 files
= filter (lambda x
, p
=pattern
: re
.match (p
, x
), os
.listdir ('.'))
375 map (lambda x
, d
=dir: shutil
.copy2 (x
, os
.path
.join (d
, x
)), files
)
378 # Python < 1.5.2 compatibility
380 # On most platforms, this is equivalent to
381 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
383 if os
.path
.__dict
__.has_key ('abspath'):
384 abspath
= os
.path
.abspath
387 return os
.path
.normpath (os
.path
.join (os
.getcwd (), path
))
389 if os
.__dict
__.has_key ('makedirs'):
390 makedirs
= os
.makedirs
392 def makedirs (dir, mode
=0777):
393 system ('mkdir -p %s' % dir)
396 def mkdir_p (dir, mode
=0777):
397 if not os
.path
.isdir (dir):
403 # tex needs lots of memory, more than it gets by default on Debian
404 non_path_environment
= {
405 'extra_mem_top' : '1000000',
406 'extra_mem_bottom' : '1000000',
407 'pool_size' : '250000',
410 def setup_environment ():
413 kpse
= read_pipe ('kpsexpand \$TEXMF')
414 texmf
= re
.sub ('[ \t\n]+$','', kpse
)
415 type1_paths
= read_pipe ('kpsewhich -expand-path=\$T1FONTS')
418 # TODO: * prevent multiple addition.
419 # * clean TEXINPUTS, MFINPUTS, TFMFONTS,
420 # as these take prevalence over $TEXMF
421 # and thus may break tex run?
423 'TEXMF' : "{%s,%s}" % (datadir
, texmf
) ,
425 # 'GS_FONTPATH' : type1_paths,
426 # 'GS_LIB' : datadir + '/ps',
431 # $TEXMF is special, previous value is already taken care of
432 if os
.environ
.has_key ('TEXMF'):
433 del os
.environ
['TEXMF']
435 for key
in environment
.keys ():
436 val
= environment
[key
]
437 if os
.environ
.has_key (key
):
438 val
= os
.environ
[key
] + os
.pathsep
+ val
439 os
.environ
[key
] = val
441 for key
in non_path_environment
.keys ():
442 val
= non_path_environment
[key
]
443 os
.environ
[key
] = val
445 def print_environment ():
446 for (k
,v
) in os
.environ
.items ():
447 sys
.stderr
.write ("%s=\"%s\"\n" % (k
, v
))
449 BOUNDING_BOX_RE
= '^%%BoundingBox: (-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)'
450 def get_bbox (filename
):
451 bbox
= filename
+ '.bbox'
452 ## -sOutputFile does not work with bbox?
453 cmd
= 'gs -sDEVICE=bbox -q -dNOPAUSE %s -c showpage -c quit 2>%s' % \
455 system (cmd
, progress_p
= 1)
456 box
= open (bbox
).read ()
457 m
= re
.match (BOUNDING_BOX_RE
, box
)
460 gr
= map (string
.atoi
, m
.groups ())
465 def make_ps_images (ps_name
, resolution
= 90, papersize
= "a4",
467 base
= os
.path
.basename (re
.sub (r
'\.e?ps', '', ps_name
))
468 header
= open (ps_name
).read (1024)
471 pngn
= base
+ '-page%d.png'
473 multi_page
= re
.search ('\n%%Pages: ', header
)
475 # png16m is because Lily produces color nowadays.
478 # GS can produce empty 2nd page if pngn is used.
482 -dGraphicsAlphaBits=4\
486 -sOutputFile='%(output_file)s'\
487 -sPAPERSIZE=%(papersize)s\
492 -c quit ''' % vars ()
496 -dGraphicsAlphaBits=4\
500 -sOutputFile='%(output_file)s'\
501 -sPAPERSIZE=%(papersize)s\
507 remove
= glob
.glob (png1
) + glob
.glob (base
+ '-page*.png')
508 map (os
.unlink
, remove
)
510 status
= system (cmd
)
511 signal
= 0xf & status
512 exit_status
= status
>> 8
515 remove
= glob
.glob (png1
) + glob
.glob (base
+ '-page*.png')
516 map (os
.unlink
, remove
)
517 error (_ ("%s exited with status: %d") % ('GS', status
))
520 if rename_page1_p
and multi_page
:
521 os
.rename (pngn
% 1, png1
)
522 files
= glob
.glob (png1
) + glob
.glob (re
.sub ('%d', '*', pngn
))