]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
(grob-cause): replace backslashes by /
[lilypond.git] / python / lilylib.py
1 ################################################################
2 # lilylib.py -- options and stuff
3
4 # source file of the GNU LilyPond music typesetter
5 #
6 # (c) 1998--2006 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 #                 Jan Nieuwenhuizen <janneke@gnu.org>
8
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\) *(
10 ###  replace:\1ly.\2 (
11
12 ### subst: \(help_summary\|keep_temp_dir_p\|option_definitions\|original_dir\|program_name\|pseudo_filter_p\|temp_dir\|verbose_p\)
13
14 import __main__
15 import glob
16 import os
17 import re
18 import shutil
19 import string
20 import sys
21 import optparse
22
23 ################################################################
24 # Users of python modules should include this snippet
25 # and customize variables below.
26
27 # We'll suffer this path init stuff as long as we don't install our
28 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
29 # it as we do with teTeX on Red Hat Linux: set some environment var
30 # (PYTHONPATH) in profile)
31
32 # If set, LILYPONDPREFIX must take prevalence
33 # if datadir is not set, we're doing a build and LILYPONDPREFIX
34
35 datadir = '@local_lilypond_datadir@'
36 if not os.path.isdir (datadir):
37         datadir = '@lilypond_datadir@'
38 if os.environ.has_key ('LILYPONDPREFIX') :
39         datadir = os.environ['LILYPONDPREFIX']
40         while datadir[-1] == os.sep:
41                 datadir= datadir[:-1]
42
43 sys.path.insert (0, os.path.join (datadir, 'python'))
44
45
46
47
48 localedir = '@localedir@'
49 try:
50         import gettext
51         gettext.bindtextdomain ('lilypond', localedir)
52         gettext.textdomain ('lilypond')
53         _ = gettext.gettext
54 except:
55         def _ (s):
56                 return s
57 underscore = _
58
59 def progress (s):
60         sys.stderr.write (s)
61
62 def warning (s):
63         sys.stderr.write (__main__.program_name + ": " + _ ("warning: %s") % s + '\n')
64
65 def error (s):
66         sys.stderr.write (__main__.program_name + ": " + _ ("error: %s") % s + '\n')
67         
68 def exit (i):
69         be_verbose = get_global_option('verbose_p', 'verbose')
70         if be_verbose:
71                 raise _ ('Exiting (%d)...') % i
72         else:
73                 sys.exit (i)
74         
75 def lilypond_version (binary):
76         p = read_pipe ('%s --version ' % binary)
77
78         ls = p.split ('\n')
79         v= '<not found>'
80         for l in ls:
81                 m = re.search ('GNU LilyPond ([0-9a-z.]+)', p)
82                 if m:
83                         v = m.group (1)
84                         
85         return v
86         
87 def lilypond_version_check (binary, req):
88         if req[0] <> '@' :
89                 v = lilypond_version (binary)
90                 if v <> req:
91                         error (_("Binary %s has version %s, looking for version %s") % \
92                                (binary, v, req))
93                         sys.exit (1)
94         
95         
96
97 def command_name (cmd):
98         # Strip all stuf after command,
99         # deal with "((latex ) >& 1 ) .." too
100         cmd = re.match ('([\(\)]*)([^\\\ ]*)', cmd).group (2)
101         return os.path.basename (cmd)
102
103 def error_log (name):
104         name = re.sub('[^a-z]','x', name)
105         return tempfile.mktemp ('%s.errorlog' % name)
106
107 def read_pipe (cmd, mode = 'r'):
108         
109         
110         redirect = ''
111         error_log_file = ''
112         if be_verbose:
113                 progress (_ ("Opening pipe `%s\'") % cmd)
114         else:
115                 error_log_file = error_log (command_name (cmd))
116                 redirect = ' 2>%s' % error_log_file
117                 
118         pipe = os.popen (cmd + redirect, mode)
119         output = pipe.read ()
120         status = pipe.close ()
121         # successful pipe close returns 'None'
122         if not status:
123                 status = 0
124         signal = 0x0f & status
125         exit_status = status >> 8
126
127         if status:
128                 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
129                 
130                 if not be_verbose:
131                         contents = open (error_log_file).read ()
132                         if contents:
133                                 error (_ ("The error log is as follows:"))
134                                 sys.stderr.write (contents)
135
136                 # Ugh. code dup
137                 if error_log_file:
138                         os.unlink (error_log_file)
139
140                 exit (1)
141                 
142         if be_verbose:
143                 progress ('\n')
144
145         if error_log_file:
146                 os.unlink (error_log_file)
147                 
148         return output
149
150 def get_global_option (old, new):
151         try:
152                 return __main__.__dict__[old]
153         except KeyError:
154                 return __main__.global_options.__dict__[new]
155
156 def system (cmd, ignore_error = 0, progress_p = 0):
157         
158         '''System CMD.  If IGNORE_ERROR, do not complain when CMD
159 returns non zero.  If PROGRESS_P, always show progress.
160
161 RETURN VALUE
162
163 Exit status of CMD '''
164
165         name = command_name (cmd)
166         error_log_file = ''
167
168         ## UGH
169         be_verbose = get_global_option('verbose_p', 'verbose')
170         pseudo_filter = get_global_option ('pseudo_filter_p', 'pseudo_filter')
171         
172         if be_verbose:
173                 progress_p = 1
174                 progress (_ ("Invoking `%s\'") % cmd)
175         else:
176                 progress ( _("Running %s...") % name)
177
178         redirect = ''
179         if not progress_p:
180                 error_log_file = error_log (name)
181                 redirect = ' 1>/dev/null 2>' + error_log_file
182         elif pseudo_filter:
183                 redirect = ' 1>/dev/null'
184
185         status = os.system (cmd + redirect)
186         signal = 0x0f & status
187         exit_status = status >> 8
188         
189         if status:
190                 
191                 exit_type =  'status %d' % exit_status
192                 if signal:
193                         exit_type = 'signal %d' % signal 
194                 
195                 msg = _ ("`%s\' failed (%s)") % (name, exit_type)
196                 if ignore_error:
197                         if be_verbose:
198                                 warning (msg + ' ' + _ ("(ignored)"))
199                 else:
200                         error (msg)
201                         if not progress_p and error_log_file:
202                                 error (_ ("The error log is as follows:"))
203                                 sys.stderr.write (open (error_log_file).read ())
204                         if error_log_file:
205                                 os.unlink (error_log_file)
206                         exit (1)
207
208         if error_log_file:
209                 os.unlink (error_log_file)
210         progress ('\n')
211         return status
212
213 def cleanup_temp ():
214         be_verbose = get_global_option('verbose_p', 'verbose')
215         if not __main__.keep_temp_dir_p:
216                 if be_verbose:
217                         progress (_ ("Cleaning %s...") % __main__.temp_dir)
218                 shutil.rmtree (__main__.temp_dir)
219                 if be_verbose:
220                         progress ('\n')
221
222
223 def strip_extension (f, ext):
224         (p, e) = os.path.splitext (f)
225         if e == ext:
226                 e = ''
227         return p + e
228
229
230 def cp_to_dir (pattern, dir):
231         "Copy files matching re PATTERN from cwd to DIR"
232         
233         # Duh.  Python style portable: cp *.EXT OUTDIR
234         # system ('cp *.%s %s' % (ext, outdir), 1)
235
236         files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
237         map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
238
239
240 def search_exe_path (name):
241         p = os.environ['PATH']
242         exe_paths = string.split (p, ':')
243         for e in exe_paths:
244                 full = os.path.join (e, name)
245                 if os.path.exists (full):
246                         return full
247         return None
248
249
250 def mkdir_p (dir, mode=0777):
251         if not os.path.isdir (dir):
252                 makedirs (dir, mode)
253
254 def print_environment ():
255         for (k,v) in os.environ.items ():
256                 sys.stderr.write ("%s=\"%s\"\n" % (k, v)) 
257
258
259 def ps_page_count (ps_name):
260         header = open (ps_name).read (1024)
261         m = re.search ('\n%%Pages: ([0-9]+)', header)
262         if m:
263                 return string.atoi (m.group (1))
264         return 0
265
266 def make_ps_images (ps_name, resolution = 90, papersize = "a4",
267                     rename_page1_p = 0):
268         base = os.path.basename (re.sub (r'\.e?ps', '', ps_name))
269         header = open (ps_name).read (1024)
270
271         png1 = base + '.png'
272         pngn = base + '-page%d.png'
273         output_file = pngn
274         multi_page = re.search ('\n%%Pages: ', header)
275
276         # png16m is because Lily produces color nowadays.
277         if not multi_page:
278
279                 # GS can produce empty 2nd page if pngn is used.
280                 output_file = png1
281                 cmd = r'''gs\
282                 -dEPSCrop\
283                 -dGraphicsAlphaBits=4\
284                 -dNOPAUSE\
285                 -dTextAlphaBits=4\
286                 -sDEVICE=png16m\
287                 -sOutputFile='%(output_file)s'\
288                 -sPAPERSIZE=%(papersize)s\
289                 -q\
290                 -r%(resolution)d\
291                 '%(ps_name)s'\
292                 -c showpage\
293                 -c quit ''' % vars ()
294         else:
295                 cmd = r'''gs\
296                 -s\
297                 -dGraphicsAlphaBits=4\
298                 -dNOPAUSE\
299                 -dTextAlphaBits=4\
300                 -sDEVICE=png16m\
301                 -sOutputFile='%(output_file)s'\
302                 -sPAPERSIZE=%(papersize)s\
303                 -q\
304                 -r%(resolution)d\
305                 '%(ps_name)s'\
306                 -c quit''' % vars ()
307
308         remove = glob.glob (png1) + glob.glob (base + '-page*.png')
309         map (os.unlink, remove)
310
311         status = system (cmd)
312         signal = 0xf & status
313         exit_status = status >> 8
314
315         if status:
316                 remove = glob.glob (png1) + glob.glob (base + '-page*.png')
317                 map (os.unlink, remove)
318                 error (_ ("%s exited with status: %d") % ('GS', status))
319                 exit (1)
320
321         if rename_page1_p and multi_page:
322                 os.rename (pngn % 1, png1)
323         files = glob.glob (png1) + glob.glob (re.sub ('%d', '*', pngn))
324         return files
325
326 class NonDentedHeadingFormatter (optparse.IndentedHelpFormatter):
327     def format_heading(self, heading):
328             if heading:
329                     return heading[0].upper() + heading[1:] + ':\n'
330             return ''
331     def format_option_strings(self, option):
332             sep = ' '
333             if option._short_opts and option._long_opts:
334                     sep = ','
335
336             metavar = ''
337             if option.takes_value():
338                     metavar = '=%s' % option.metavar or option.dest.upper()
339
340             return "%3s%s %s%s" % (" ".join (option._short_opts),
341                                    sep,
342                                    " ".join (option._long_opts),
343                                    metavar)
344
345     def format_usage(self, usage):
346         return _("Usage: %s\n") % usage
347     
348     def format_description(self, description):
349             return description
350
351 def get_option_parser (*args, **kwargs): 
352         p = optparse.OptionParser (*args, **kwargs)
353         p.formatter = NonDentedHeadingFormatter () 
354         return p