1 ################################################################
2 # lilylib.py -- options and stuff
4 # source file of the GNU LilyPond music typesetter
6 # (c) 1998--2002 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\)
20 ################################################################
21 # Users of python modules should include this snippet
22 # and customize variables below.
24 # We'll suffer this path init stuff as long as we don't install our
25 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
26 # it as we do with teTeX on Red Hat Linux: set some environment var
27 # (PYTHONPATH) in profile)
29 # If set, LILYPONDPREFIX must take prevalence
30 # if datadir is not set, we're doing a build and LILYPONDPREFIX
31 import getopt, os, sys
32 datadir = '@local_lilypond_datadir@'
33 if not os.path.isdir (datadir):
34 datadir = '@lilypond_datadir@'
35 if os.environ.has_key ('LILYPONDPREFIX') :
36 datadir = os.environ['LILYPONDPREFIX']
37 while datadir[-1] == os.sep:
40 sys.path.insert (0, os.path.join (datadir, 'python'))
43 if __name__ == '__main__':
49 program_name = 'unset'
51 original_dir = os.getcwd ()
52 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
56 help_summary = _ ("lilylib module")
58 option_definitions = [
59 ('', 'h', 'help', _ ("this help")),
63 ################################################################
65 # Handle bug in Python 1.6-2.1
67 # there are recursion limits for some patterns in Python 1.6 til 2.1.
68 # fix this by importing pre instead. Fix by Mats.
70 if float (sys.version[0:3]) <= 2.1:
80 # Attempt to fix problems with limited stack size set by Python!
81 # Sets unlimited stack size. Note that the resource module only
82 # is available on UNIX.
85 resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
89 localedir = '@localedir@'
92 gettext.bindtextdomain ('lilypond', localedir)
93 gettext.textdomain ('lilypond')
100 program_version = '@TOPLEVEL_VERSION@'
101 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
102 program_version = '1.7.14'
105 port.write ('%s (GNU LilyPond) %s\n' % (__main__.program_name, program_version))
108 identify (sys.stdout)
109 sys.stdout.write ('\n')
110 sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998--2002'))
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 + '\n')
126 sys.stderr.write (__main__.program_name + ": " + _ ("error: ") + s + '\n')
129 if __main__.verbose_p:
130 raise _ ('Exiting (%d)...') % i
134 def getopt_args (opts):
135 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
150 def option_help_str (o):
151 '''Transform one option description (4-tuple ) into neatly formatted string'''
169 return ' ' + sh + sep + long + arg
172 def options_help_str (opts):
173 '''Convert a list of options into a neatly formatted string'''
179 s = option_help_str (o)
180 strs.append ((s, o[3]))
186 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
190 ls = [(_ ("Usage: %s [OPTION]... FILE") % __main__.program_name),
192 (__main__.help_summary),
196 (options_help_str (__main__.option_definitions)),
198 (_ ("Report bugs to %s") % 'bug-lilypond@gnu.org'),
200 map (sys.stdout.write, ls)
204 ''' Create a temporary directory, and return its name. '''
206 if not __main__.keep_temp_dir_p:
207 __main__.temp_dir = tempfile.mktemp (__main__.program_name)
209 os.mkdir (__main__.temp_dir, 0777)
213 return __main__.temp_dir
215 def command_name (cmd):
216 return re.match ('^[ \t]*([^ \t]*)', cmd).group (1)
218 def error_log (name):
219 return os.path.join (__main__.temp_dir, '%s.errorlog' % name)
221 def read_pipe (cmd, mode = 'r'):
223 if __main__.verbose_p:
224 progress (_ ("Opening pipe `%s\'") % cmd)
225 redirect = ' 2>%s' % error_log (command_name (cmd))
226 pipe = os.popen (cmd + redirect, mode)
227 output = pipe.read ()
228 status = pipe.close ()
229 # successful pipe close returns 'None'
232 signal = 0x0f & status
233 exit_status = status >> 8
236 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
237 if not __main__.verbose_p:
238 error (_ ("The error log is as follows:"))
239 sys.stderr.write (open (error_log (command_name (cmd)).read ()))
241 if __main__.verbose_p:
245 def system (cmd, ignore_error = 0, progress_p = 0):
247 '''System CMD. If IGNORE_ERROR, do not complain when CMD
248 returns non zero. If PROGRESS_P, always show progress.
252 Exit status of CMD '''
254 name = command_name (cmd)
256 if __main__.verbose_p:
258 progress (_ ("Invoking `%s\'") % cmd)
260 progress ( _("Running %s...") % name)
264 redirect = ' 1>/dev/null 2>' + error_log (name)
265 elif __main__.pseudo_filter_p:
266 redirect = ' 1>/dev/null'
268 status = os.system (cmd + redirect)
269 signal = 0x0f & status
270 exit_status = status >> 8
274 exit_type = 'status %d' % exit_status
276 exit_type = 'signal %d' % signal
278 msg = _ ("`%s\' failed (%s)") % (name, exit_type)
280 if __main__.verbose_p:
281 warning (msg + ' ' + _ ("(ignored)"))
285 error (_ ("The error log is as follows:"))
286 sys.stderr.write (open (error_log (name)).read ())
293 if not __main__.keep_temp_dir_p:
294 if __main__.verbose_p:
295 progress (_ ("Cleaning %s...") % __main__.temp_dir)
296 shutil.rmtree (__main__.temp_dir)
297 if __main__.verbose_p:
301 def strip_extension (f, ext):
302 (p, e) = os.path.splitext (f)
308 def cp_to_dir (pattern, dir):
309 "Copy files matching re PATTERN from cwd to DIR"
310 # Duh. Python style portable: cp *.EXT OUTDIR
311 # system ('cp *.%s %s' % (ext, outdir), 1)
312 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
313 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
316 # Python < 1.5.2 compatibility
318 # On most platforms, this is equivalent to
319 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
320 if os.path.__dict__.has_key ('abspath'):
321 abspath = os.path.abspath
324 return os.path.normpath (os.path.join (os.getcwd (), path))
326 if os.__dict__.has_key ('makedirs'):
327 makedirs = os.makedirs
329 def makedirs (dir, mode=0777):
330 system ('mkdir -p %s' % dir)
333 def mkdir_p (dir, mode=0777):
334 if not os.path.isdir (dir):
340 # tex needs lots of memory, more than it gets by default on Debian
341 non_path_environment = {
342 'extra_mem_top' : '1000000',
343 'extra_mem_bottom' : '1000000',
344 'pool_size' : '250000',
347 def setup_environment ():
350 kpse = read_pipe ('kpsexpand \$TEXMF')
351 texmf = re.sub ('[ \t\n]+$','', kpse)
352 type1_paths = read_pipe ('kpsewhich -expand-path=\$T1FONTS')
355 # TODO: * prevent multiple addition.
356 # * clean TEXINPUTS, MFINPUTS, TFMFONTS,
357 # as these take prevalence over $TEXMF
358 # and thus may break tex run?
359 'TEXMF' : "{%s,%s}" % (datadir, texmf) ,
360 'GS_FONTPATH' : type1_paths,
361 'GS_LIB' : datadir + '/ps',
364 # $TEXMF is special, previous value is already taken care of
365 if os.environ.has_key ('TEXMF'):
366 del os.environ['TEXMF']
368 for key in environment.keys ():
369 val = environment[key]
370 if os.environ.has_key (key):
371 val = os.environ[key] + os.pathsep + val
372 os.environ[key] = val
374 for key in non_path_environment.keys ():
375 val = non_path_environment[key]
376 os.environ[key] = val
378 def print_environment ():
379 for (k,v) in os.environ.items ():
380 sys.stderr.write ("%s=\"%s\"\n" % (k, v))
382 def get_bbox (filename):
383 bbox = filename + '.bbox'
384 ## -sOutputFile does not work with bbox?
385 cmd = 'gs -sDEVICE=bbox -q -dNOPAUSE %s -c quit 2>%s' % \
387 system (cmd, progress_p = 1)
388 box = open (bbox).read ()
389 m = re.match ('^%%BoundingBox: ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)',
393 gr = map (string.atoi, m.groups ())
397 def make_preview (name):
398 ## ly2dvi/lilypond-book discrepancy
399 preview_ps = name + '.preview.ps'
400 if not os.path.isfile (preview_ps):
401 preview_ps = name + '.eps'
402 bbox = get_bbox (preview_ps)
403 trans_ps = name + '.trans.ps'
407 fo = open (trans_ps, 'w')
408 fo.write ('%d %d translate\n' % (-bbox[0] + margin,
412 x = (2* margin + bbox[2] - bbox[0]) \
413 * __main__.preview_resolution / 72.0
414 y = (2* margin + bbox[3] - bbox[1]) \
415 * __main__.preview_resolution / 72.0
421 cmd = r'''gs -g%dx%d -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -q -sOutputFile=%s -r%d -dNOPAUSE %s %s -c quit ''' % \
422 (x, y, png, __main__.preview_resolution, trans_ps, preview_ps)
424 status = system (cmd)
425 signal = 0xf & status
426 exit_status = status >> 8
430 error (_ ("Removing output file"))
433 def make_page_images (name, resolution = 90):
435 """ Generate images for
436 all pages in the PS file NAME. NAME should be the basename
437 (not including the extension.).
440 cmd = 'gs -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -sOutputFile="%s-page%%d.png" -r%d -dNOPAUSE %s -c quit'
441 cmd = cmd % (name, resolution, name + '.ps')