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'))
50 # UGH. - why? Py2exe barfs
51 if __name__ == '__main__':
57 program_name = 'unset'
59 original_dir = os.getcwd ()
60 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
64 help_summary = _ ("lilylib module")
66 option_definitions = [
67 ('', 'h', 'help', _ ("print this help")),
71 ################################################################
73 # Handle bug in Python 1.6-2.1
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.
79 # Ugh. py2exe barfs on conditional imports
80 if float (sys.version[0:3]) <= 2.1:
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.
95 # Ugh. py2exe barfs on conditional imports
98 resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
102 localedir = '@localedir@'
105 gettext.bindtextdomain ('lilypond', localedir)
106 gettext.textdomain ('lilypond')
114 port.write ('%s (GNU LilyPond) %s\n' % (__main__.program_name, __main__.program_version))
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')
132 sys.stderr.write (__main__.program_name + ": " + _ ("warning: %s") % s + '\n')
135 sys.stderr.write (__main__.program_name + ": " + _ ("error: %s") % s + '\n')
138 if __main__.verbose_p:
139 raise _ ('Exiting (%d)...') % i
143 def getopt_args (opts):
144 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
159 def option_help_str (o):
160 '''Transform one option description (4-tuple ) into neatly formatted string'''
178 return ' ' + sh + sep + long + arg
181 def options_help_str (opts):
182 '''Convert a list of options into a neatly formatted string'''
188 s = option_help_str (o)
189 strs.append ((s, o[3]))
196 for ss in re.split ('\n\s*', s[1]):
198 str = str + '%s%s%s\n' \
199 % (s[0], ' ' * (w - len (s[0]) + 3), ss)
202 str = str + '%s%s\n' \
203 % (' ' * (w + 3), ss)
207 ls = [(_ ("Usage: %s [OPTIONS]... FILE") % __main__.program_name),
209 (__main__.help_summary),
213 (options_help_str (__main__.option_definitions)),
215 (_ ("Report bugs to %s.") % 'bug-lilypond@gnu.org'),
217 map (sys.stdout.write, ls)
219 def lilypond_version (binary):
220 p = read_pipe ('%s --version ' % binary)
225 m = re.search ('GNU LilyPond ([0-9a-z.]+)', p)
231 def lilypond_version_check (binary, req):
233 v = lilypond_version (binary)
235 error (_("Binary %s has version %s, looking for version %s") % \
242 ''' Create a temporary directory, and return its name. '''
244 if not __main__.keep_temp_dir_p:
245 __main__.temp_dir = tempfile.mktemp (__main__.program_name)
247 os.mkdir (__main__.temp_dir, 0700)
251 return __main__.temp_dir
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)
259 def error_log (name):
260 name = re.sub('[^a-z]','x', name)
261 return tempfile.mktemp ('%s.errorlog' % name)
263 def read_pipe (cmd, mode = 'r'):
268 if __main__.verbose_p:
269 progress (_ ("Opening pipe `%s\'") % cmd)
271 error_log_file = error_log (command_name (cmd))
272 redirect = ' 2>%s' % error_log_file
274 pipe = os.popen (cmd + redirect, mode)
275 output = pipe.read ()
276 status = pipe.close ()
277 # successful pipe close returns 'None'
280 signal = 0x0f & status
281 exit_status = status >> 8
284 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
286 if not __main__.verbose_p:
287 contents = open (error_log_file).read ()
289 error (_ ("The error log is as follows:"))
290 sys.stderr.write (contents)
294 os.unlink (error_log_file)
298 if __main__.verbose_p:
302 os.unlink (error_log_file)
306 def system (cmd, ignore_error = 0, progress_p = 0):
308 '''System CMD. If IGNORE_ERROR, do not complain when CMD
309 returns non zero. If PROGRESS_P, always show progress.
313 Exit status of CMD '''
315 name = command_name (cmd)
318 if __main__.verbose_p:
320 progress (_ ("Invoking `%s\'") % cmd)
322 progress ( _("Running %s...") % name)
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'
331 status = os.system (cmd + redirect)
332 signal = 0x0f & status
333 exit_status = status >> 8
337 exit_type = 'status %d' % exit_status
339 exit_type = 'signal %d' % signal
341 msg = _ ("`%s\' failed (%s)") % (name, exit_type)
343 if __main__.verbose_p:
344 warning (msg + ' ' + _ ("(ignored)"))
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 ())
351 os.unlink (error_log_file)
355 os.unlink (error_log_file)
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:
368 def strip_extension (f, ext):
369 (p, e) = os.path.splitext (f)
375 def cp_to_dir (pattern, dir):
376 "Copy files matching re PATTERN from cwd to DIR"
378 # Duh. Python style portable: cp *.EXT OUTDIR
379 # system ('cp *.%s %s' % (ext, outdir), 1)
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)
385 # Python < 1.5.2 compatibility
387 # On most platforms, this is equivalent to
388 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
390 if os.path.__dict__.has_key ('abspath'):
391 abspath = os.path.abspath
394 return os.path.normpath (os.path.join (os.getcwd (), path))
396 if os.__dict__.has_key ('makedirs'):
397 makedirs = os.makedirs
399 def makedirs (dir, mode=0777):
400 system ('mkdir -p %s' % dir)
404 def search_exe_path (name):
405 p = os.environ['PATH']
406 exe_paths = string.split (p, ':')
408 full = os.path.join (e, name)
409 if os.path.exists (full):
414 def mkdir_p (dir, mode=0777):
415 if not os.path.isdir (dir):
418 def print_environment ():
419 for (k,v) in os.environ.items ():
420 sys.stderr.write ("%s=\"%s\"\n" % (k, v))
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' % \
428 system (cmd, progress_p = 1)
429 box = open (bbox).read ()
430 m = re.match (BOUNDING_BOX_RE, box)
433 gr = map (string.atoi, m.groups ())
438 def make_ps_images (ps_name, resolution = 90, papersize = "a4",
440 base = os.path.basename (re.sub (r'\.e?ps', '', ps_name))
441 header = open (ps_name).read (1024)
444 pngn = base + '-page%d.png'
446 multi_page = re.search ('\n%%Pages: ', header)
448 # png16m is because Lily produces color nowadays.
451 # GS can produce empty 2nd page if pngn is used.
455 -dGraphicsAlphaBits=4\
459 -sOutputFile='%(output_file)s'\
460 -sPAPERSIZE=%(papersize)s\
465 -c quit ''' % vars ()
469 -dGraphicsAlphaBits=4\
473 -sOutputFile='%(output_file)s'\
474 -sPAPERSIZE=%(papersize)s\
480 remove = glob.glob (png1) + glob.glob (base + '-page*.png')
481 map (os.unlink, remove)
483 status = system (cmd)
484 signal = 0xf & status
485 exit_status = status >> 8
488 remove = glob.glob (png1) + glob.glob (base + '-page*.png')
489 map (os.unlink, remove)
490 error (_ ("%s exited with status: %d") % ('GS', status))
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))