1 ################################################################
2 # lilylib.py -- options and stuff
4 # source file of the GNU LilyPond music typesetter
6 # (c) 1998--2006 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\)
25 ################################################################
26 # Users of python modules should include this snippet
27 # and customize variables below.
29 # We'll suffer this path init stuff as long as we don't install our
30 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
31 # it as we do with teTeX on Red Hat Linux: set some environment var
32 # (PYTHONPATH) in profile)
34 # If set, LILYPONDPREFIX must take prevalence
35 # if datadir is not set, we're doing a build and LILYPONDPREFIX
37 datadir = '@local_lilypond_datadir@'
38 if not os.path.isdir (datadir):
39 datadir = '@lilypond_datadir@'
40 if os.environ.has_key ('LILYPONDPREFIX') :
41 datadir = os.environ['LILYPONDPREFIX']
42 while datadir[-1] == os.sep:
45 sys.path.insert (0, os.path.join (datadir, 'python'))
50 localedir = '@localedir@'
53 gettext.bindtextdomain ('lilypond', localedir)
54 gettext.textdomain ('lilypond')
62 port.write ('%s (GNU LilyPond) %s\n' % (__main__.program_name, __main__.program_version))
66 sys.stdout.write ('\n')
67 sys.stdout.write (_ ("Copyright (c) %s by") % '1998--2006')
68 sys.stdout.write ('\n')
69 map (lambda x: sys.stdout.write (' %s\n' % x), __main__.copyright)
70 sys.stdout.write ('\n')
71 sys.stdout.write (_ ("Distributed under terms of the GNU General Public License."))
72 sys.stdout.write ('\n')
73 sys.stdout.write (_ ("It comes with NO WARRANTY."))
74 sys.stdout.write ('\n')
80 sys.stderr.write (__main__.program_name + ": " + _ ("warning: %s") % s + '\n')
83 sys.stderr.write (__main__.program_name + ": " + _ ("error: %s") % s + '\n')
86 be_verbose = get_global_option('verbose_p', 'verbose')
88 raise _ ('Exiting (%d)...') % i
92 def getopt_args (opts):
93 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
108 def option_help_str (o):
109 '''Transform one option description (4-tuple) into neatly formatted string'''
127 return ' ' + sh + sep + long + arg
130 def options_help_str (opts):
131 '''Convert a list of options into a neatly formatted string'''
137 s = option_help_str (o)
138 strs.append ((s, o[3]))
145 for ss in re.split ('\n\s*', s[1]):
147 str = str + '%s%s%s\n' \
148 % (s[0], ' ' * (w - len (s[0]) + 3), ss)
151 str = str + '%s%s\n' \
152 % (' ' * (w + 3), ss)
156 ls = [(_ ("Usage: %s [OPTIONS]... FILE") % __main__.program_name),
158 (__main__.help_summary),
162 (options_help_str (__main__.option_definitions)),
164 (_ ("Report bugs to %s.") % 'bug-lilypond@gnu.org'),
166 map (sys.stdout.write, ls)
168 def lilypond_version (binary):
169 p = read_pipe ('%s --version ' % binary)
174 m = re.search ('GNU LilyPond ([0-9a-z.]+)', p)
180 def lilypond_version_check (binary, req):
182 v = lilypond_version (binary)
184 error (_("Binary %s has version %s, looking for version %s") % \
191 ''' Create a temporary directory, and return its name. '''
193 if not __main__.keep_temp_dir_p:
194 __main__.temp_dir = tempfile.mktemp (__main__.program_name)
196 os.mkdir (__main__.temp_dir, 0700)
200 return __main__.temp_dir
202 def command_name (cmd):
203 # Strip all stuf after command,
204 # deal with "((latex ) >& 1 ) .." too
205 cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
206 return os.path.basename (cmd)
208 def error_log (name):
209 name = re.sub('[^a-z]','x', name)
210 return tempfile.mktemp ('%s.errorlog' % name)
212 def read_pipe (cmd, mode = 'r'):
218 progress (_ ("Opening pipe `%s\'") % cmd)
220 error_log_file = error_log (command_name (cmd))
221 redirect = ' 2>%s' % error_log_file
223 pipe = os.popen (cmd + redirect, mode)
224 output = pipe.read ()
225 status = pipe.close ()
226 # successful pipe close returns 'None'
229 signal = 0x0f & status
230 exit_status = status >> 8
233 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
236 contents = open (error_log_file).read ()
238 error (_ ("The error log is as follows:"))
239 sys.stderr.write (contents)
243 os.unlink (error_log_file)
251 os.unlink (error_log_file)
255 def get_global_option (old, new):
257 return __main__.__dict__[old]
259 return __main__.global_options.__dict__[new]
261 def system (cmd, ignore_error = 0, progress_p = 0):
263 '''System CMD. If IGNORE_ERROR, do not complain when CMD
264 returns non zero. If PROGRESS_P, always show progress.
268 Exit status of CMD '''
270 name = command_name (cmd)
274 be_verbose = get_global_option('verbose_p', 'verbose')
275 pseudo_filter = get_global_option ('pseudo_filter_p', 'pseudo_filter')
279 progress (_ ("Invoking `%s\'") % cmd)
281 progress ( _("Running %s...") % name)
285 error_log_file = error_log (name)
286 redirect = ' 1>/dev/null 2>' + error_log_file
288 redirect = ' 1>/dev/null'
290 status = os.system (cmd + redirect)
291 signal = 0x0f & status
292 exit_status = status >> 8
296 exit_type = 'status %d' % exit_status
298 exit_type = 'signal %d' % signal
300 msg = _ ("`%s\' failed (%s)") % (name, exit_type)
303 warning (msg + ' ' + _ ("(ignored)"))
306 if not progress_p and error_log_file:
307 error (_ ("The error log is as follows:"))
308 sys.stderr.write (open (error_log_file).read ())
310 os.unlink (error_log_file)
314 os.unlink (error_log_file)
319 be_verbose = get_global_option('verbose_p', 'verbose')
320 if not __main__.keep_temp_dir_p:
322 progress (_ ("Cleaning %s...") % __main__.temp_dir)
323 shutil.rmtree (__main__.temp_dir)
328 def strip_extension (f, ext):
329 (p, e) = os.path.splitext (f)
335 def cp_to_dir (pattern, dir):
336 "Copy files matching re PATTERN from cwd to DIR"
338 # Duh. Python style portable: cp *.EXT OUTDIR
339 # system ('cp *.%s %s' % (ext, outdir), 1)
341 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
342 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
345 def search_exe_path (name):
346 p = os.environ['PATH']
347 exe_paths = string.split (p, ':')
349 full = os.path.join (e, name)
350 if os.path.exists (full):
355 def mkdir_p (dir, mode=0777):
356 if not os.path.isdir (dir):
359 def print_environment ():
360 for (k,v) in os.environ.items ():
361 sys.stderr.write ("%s=\"%s\"\n" % (k, v))
364 def ps_page_count (ps_name):
365 header = open (ps_name).read (1024)
366 m = re.search ('\n%%Pages: ([0-9]+)', header)
368 return string.atoi (m.group (1))
371 def make_ps_images (ps_name, resolution = 90, papersize = "a4",
373 base = os.path.basename (re.sub (r'\.e?ps', '', ps_name))
374 header = open (ps_name).read (1024)
377 pngn = base + '-page%d.png'
379 multi_page = re.search ('\n%%Pages: ', header)
381 # png16m is because Lily produces color nowadays.
384 # GS can produce empty 2nd page if pngn is used.
388 -dGraphicsAlphaBits=4\
392 -sOutputFile='%(output_file)s'\
393 -sPAPERSIZE=%(papersize)s\
398 -c quit ''' % vars ()
402 -dGraphicsAlphaBits=4\
406 -sOutputFile='%(output_file)s'\
407 -sPAPERSIZE=%(papersize)s\
413 remove = glob.glob (png1) + glob.glob (base + '-page*.png')
414 map (os.unlink, remove)
416 status = system (cmd)
417 signal = 0xf & status
418 exit_status = status >> 8
421 remove = glob.glob (png1) + glob.glob (base + '-page*.png')
422 map (os.unlink, remove)
423 error (_ ("%s exited with status: %d") % ('GS', status))
426 if rename_page1_p and multi_page:
427 os.rename (pngn % 1, png1)
428 files = glob.glob (png1) + glob.glob (re.sub ('%d', '*', pngn))
431 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
432 def format_heading(self, heading):
434 return heading[0].upper() + heading[1:] + ':\n'
436 def format_option_strings(self, option):
438 if option._short_opts and option._long_opts:
442 if option.takes_value():
443 metavar = '=%s' % option.metavar or option.dest.upper()
445 return "%3s%s %s%s" % (" ".join (option._short_opts),
447 " ".join (option._long_opts),
450 def format_usage(self, usage):
451 return _("Usage: %s\n") % usage
453 def format_description(self, description):
456 def get_option_parser (*args, **kwargs):
457 p = optparse.OptionParser (*args, **kwargs)
458 p.formatter = NonDentedHeadingFormatter ()