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\)
24 ################################################################
25 # Users of python modules should include this snippet
26 # and customize variables below.
28 # We'll suffer this path init stuff as long as we don't install our
29 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
30 # it as we do with teTeX on Red Hat Linux: set some environment var
31 # (PYTHONPATH) in profile)
33 # If set, LILYPONDPREFIX must take prevalence
34 # 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 localedir = '@localedir@'
52 gettext.bindtextdomain ('lilypond', localedir)
53 gettext.textdomain ('lilypond')
61 port.write ('%s (GNU LilyPond) %s\n' % (__main__.program_name, __main__.program_version))
65 sys.stdout.write ('\n')
66 sys.stdout.write (_ ("Copyright (c) %s by") % '1998--2005')
67 sys.stdout.write ('\n')
68 map (lambda x: sys.stdout.write (' %s\n' % x), __main__.copyright)
69 sys.stdout.write ('\n')
70 sys.stdout.write (_ ("Distributed under terms of the GNU General Public License."))
71 sys.stdout.write ('\n')
72 sys.stdout.write (_ ("It comes with NO WARRANTY."))
73 sys.stdout.write ('\n')
79 sys.stderr.write (__main__.program_name + ": " + _ ("warning: %s") % s + '\n')
82 sys.stderr.write (__main__.program_name + ": " + _ ("error: %s") % s + '\n')
85 if __main__.verbose_p:
86 raise _ ('Exiting (%d)...') % i
90 def getopt_args (opts):
91 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
106 def option_help_str (o):
107 '''Transform one option description (4-tuple) into neatly formatted string'''
125 return ' ' + sh + sep + long + arg
128 def options_help_str (opts):
129 '''Convert a list of options into a neatly formatted string'''
135 s = option_help_str (o)
136 strs.append ((s, o[3]))
143 for ss in re.split ('\n\s*', s[1]):
145 str = str + '%s%s%s\n' \
146 % (s[0], ' ' * (w - len (s[0]) + 3), ss)
149 str = str + '%s%s\n' \
150 % (' ' * (w + 3), ss)
154 ls = [(_ ("Usage: %s [OPTIONS]... FILE") % __main__.program_name),
156 (__main__.help_summary),
160 (options_help_str (__main__.option_definitions)),
162 (_ ("Report bugs to %s.") % 'bug-lilypond@gnu.org'),
164 map (sys.stdout.write, ls)
166 def lilypond_version (binary):
167 p = read_pipe ('%s --version ' % binary)
172 m = re.search ('GNU LilyPond ([0-9a-z.]+)', p)
178 def lilypond_version_check (binary, req):
180 v = lilypond_version (binary)
182 error (_("Binary %s has version %s, looking for version %s") % \
189 ''' Create a temporary directory, and return its name. '''
191 if not __main__.keep_temp_dir_p:
192 __main__.temp_dir = tempfile.mktemp (__main__.program_name)
194 os.mkdir (__main__.temp_dir, 0700)
198 return __main__.temp_dir
200 def command_name (cmd):
201 # Strip all stuf after command,
202 # deal with "((latex ) >& 1 ) .." too
203 cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
204 return os.path.basename (cmd)
206 def error_log (name):
207 name = re.sub('[^a-z]','x', name)
208 return tempfile.mktemp ('%s.errorlog' % name)
210 def read_pipe (cmd, mode = 'r'):
215 if __main__.verbose_p:
216 progress (_ ("Opening pipe `%s\'") % cmd)
218 error_log_file = error_log (command_name (cmd))
219 redirect = ' 2>%s' % error_log_file
221 pipe = os.popen (cmd + redirect, mode)
222 output = pipe.read ()
223 status = pipe.close ()
224 # successful pipe close returns 'None'
227 signal = 0x0f & status
228 exit_status = status >> 8
231 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
233 if not __main__.verbose_p:
234 contents = open (error_log_file).read ()
236 error (_ ("The error log is as follows:"))
237 sys.stderr.write (contents)
241 os.unlink (error_log_file)
245 if __main__.verbose_p:
249 os.unlink (error_log_file)
253 def system (cmd, ignore_error = 0, progress_p = 0):
255 '''System CMD. If IGNORE_ERROR, do not complain when CMD
256 returns non zero. If PROGRESS_P, always show progress.
260 Exit status of CMD '''
262 name = command_name (cmd)
265 if __main__.verbose_p:
267 progress (_ ("Invoking `%s\'") % cmd)
269 progress ( _("Running %s...") % name)
273 error_log_file = error_log (name)
274 redirect = ' 1>/dev/null 2>' + error_log_file
275 elif __main__.pseudo_filter_p:
276 redirect = ' 1>/dev/null'
278 status = os.system (cmd + redirect)
279 signal = 0x0f & status
280 exit_status = status >> 8
284 exit_type = 'status %d' % exit_status
286 exit_type = 'signal %d' % signal
288 msg = _ ("`%s\' failed (%s)") % (name, exit_type)
290 if __main__.verbose_p:
291 warning (msg + ' ' + _ ("(ignored)"))
294 if not progress_p and error_log_file:
295 error (_ ("The error log is as follows:"))
296 sys.stderr.write (open (error_log_file).read ())
298 os.unlink (error_log_file)
302 os.unlink (error_log_file)
307 if not __main__.keep_temp_dir_p:
308 if __main__.verbose_p:
309 progress (_ ("Cleaning %s...") % __main__.temp_dir)
310 shutil.rmtree (__main__.temp_dir)
311 if __main__.verbose_p:
315 def strip_extension (f, ext):
316 (p, e) = os.path.splitext (f)
322 def cp_to_dir (pattern, dir):
323 "Copy files matching re PATTERN from cwd to DIR"
325 # Duh. Python style portable: cp *.EXT OUTDIR
326 # system ('cp *.%s %s' % (ext, outdir), 1)
328 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
329 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
332 def search_exe_path (name):
333 p = os.environ['PATH']
334 exe_paths = string.split (p, ':')
336 full = os.path.join (e, name)
337 if os.path.exists (full):
342 def mkdir_p (dir, mode=0777):
343 if not os.path.isdir (dir):
346 def print_environment ():
347 for (k,v) in os.environ.items ():
348 sys.stderr.write ("%s=\"%s\"\n" % (k, v))
351 def ps_page_count (ps_name):
352 header = open (ps_name).read (1024)
353 m = re.search ('\n%%Pages: ([0-9]+)', header)
355 return string.atoi (m.group (1))
358 def make_ps_images (ps_name, resolution = 90, papersize = "a4",
360 base = os.path.basename (re.sub (r'\.e?ps', '', ps_name))
361 header = open (ps_name).read (1024)
364 pngn = base + '-page%d.png'
366 multi_page = re.search ('\n%%Pages: ', header)
368 # png16m is because Lily produces color nowadays.
371 # GS can produce empty 2nd page if pngn is used.
375 -dGraphicsAlphaBits=4\
379 -sOutputFile='%(output_file)s'\
380 -sPAPERSIZE=%(papersize)s\
385 -c quit ''' % vars ()
389 -dGraphicsAlphaBits=4\
393 -sOutputFile='%(output_file)s'\
394 -sPAPERSIZE=%(papersize)s\
400 remove = glob.glob (png1) + glob.glob (base + '-page*.png')
401 map (os.unlink, remove)
403 status = system (cmd)
404 signal = 0xf & status
405 exit_status = status >> 8
408 remove = glob.glob (png1) + glob.glob (base + '-page*.png')
409 map (os.unlink, remove)
410 error (_ ("%s exited with status: %d") % ('GS', status))
413 if rename_page1_p and multi_page:
414 os.rename (pngn % 1, png1)
415 files = glob.glob (png1) + glob.glob (re.sub ('%d', '*', pngn))