]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
* The grand 2005-2006 replace.
[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 getopt
16 import glob
17 import os
18 import re
19 import shutil
20 import string
21 import sys
22 import tempfile
23
24 ################################################################
25 # Users of python modules should include this snippet
26 # and customize variables below.
27
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)
32
33 # If set, LILYPONDPREFIX must take prevalence
34 # if datadir is not set, we're doing a build and LILYPONDPREFIX
35
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:
42                 datadir= datadir[:-1]
43
44 sys.path.insert (0, os.path.join (datadir, 'python'))
45
46
47
48
49 localedir = '@localedir@'
50 try:
51         import gettext
52         gettext.bindtextdomain ('lilypond', localedir)
53         gettext.textdomain ('lilypond')
54         _ = gettext.gettext
55 except:
56         def _ (s):
57                 return s
58 underscore = _
59
60 def identify (port):
61         port.write ('%s (GNU LilyPond) %s\n' % (__main__.program_name, __main__.program_version))
62
63 def warranty ():
64         identify (sys.stdout)
65         sys.stdout.write ('\n')
66         sys.stdout.write (_ ("Copyright (c) %s by") % '1998--2006')
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')
74
75 def progress (s):
76         sys.stderr.write (s)
77
78 def warning (s):
79         sys.stderr.write (__main__.program_name + ": " + _ ("warning: %s") % s + '\n')
80
81 def error (s):
82         sys.stderr.write (__main__.program_name + ": " + _ ("error: %s") % s + '\n')
83         
84 def exit (i):
85         if __main__.verbose_p:
86                 raise _ ('Exiting (%d)...') % i
87         else:
88                 sys.exit (i)
89                 
90 def getopt_args (opts):
91         '''Construct arguments (LONG, SHORT) for getopt from  list of options.'''
92         short = ''
93         long = []
94         for o in opts:
95                 if o[1]:
96                         short = short + o[1]
97                         if o[0]:
98                                 short = short + ':'
99                 if o[2]:
100                         l = o[2]
101                         if o[0]:
102                                 l = l + '='
103                         long.append (l)
104         return (short, long)
105
106 def option_help_str (o):
107         '''Transform one option description (4-tuple) into neatly formatted string'''
108         sh = '  '       
109         if o[1]:
110                 sh = '-%s' % o[1]
111
112         sep = '  '
113         if o[1] and o[2]:
114                 sep = ', '
115                 
116         long = ''
117         if o[2]:
118                 long= '--%s' % o[2]
119
120         arg = ''
121         if o[0]:
122                 if o[2]:
123                         arg = '='
124                 arg = arg + o[0]
125         return '  ' + sh + sep + long + arg
126
127
128 def options_help_str (opts):
129         '''Convert a list of options into a neatly formatted string'''
130         w = 0
131         strs =[]
132         helps = []
133
134         for o in opts:
135                 s = option_help_str (o)
136                 strs.append ((s, o[3]))
137                 if len (s) > w:
138                         w = len (s)
139
140         str = ''
141         for s in strs:
142                 first = 1
143                 for ss in re.split ('\n\s*', s[1]):
144                         if first:
145                                 str = str + '%s%s%s\n' \
146                                         % (s[0], ' ' * (w - len (s[0]) + 3), ss)
147                                 first = 0
148                         else:
149                                 str = str + '%s%s\n' \
150                                         % (' ' * (w + 3), ss)
151         return str
152
153 def help ():
154         ls = [(_ ("Usage: %s [OPTIONS]... FILE") % __main__.program_name),
155               ('\n\n'),
156               (__main__.help_summary),
157               ('\n\n'),
158               (_ ("Options:")),
159               ('\n'),
160               (options_help_str (__main__.option_definitions)),
161               ('\n\n'),
162               (_ ("Report bugs to %s.") % 'bug-lilypond@gnu.org'),
163               ('\n')]
164         map (sys.stdout.write, ls)
165
166 def lilypond_version (binary):
167         p = read_pipe ('%s --version ' % binary)
168
169         ls = p.split ('\n')
170         v= '<not found>'
171         for l in ls:
172                 m = re.search ('GNU LilyPond ([0-9a-z.]+)', p)
173                 if m:
174                         v = m.group (1)
175                         
176         return v
177         
178 def lilypond_version_check (binary, req):
179         if req[0] <> '@' :
180                 v = lilypond_version (binary)
181                 if v <> req:
182                         error (_("Binary %s has version %s, looking for version %s") % \
183                                (binary, v, req))
184                         sys.exit (1)
185         
186         
187 def setup_temp ():
188         
189         ''' Create a temporary directory, and return its name. '''
190         
191         if not __main__.keep_temp_dir_p:
192                 __main__.temp_dir = tempfile.mktemp (__main__.program_name)
193         try:
194                 os.mkdir (__main__.temp_dir, 0700)
195         except OSError:
196                 pass
197
198         return __main__.temp_dir
199
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)
205
206 def error_log (name):
207         name = re.sub('[^a-z]','x', name)
208         return tempfile.mktemp ('%s.errorlog' % name)
209
210 def read_pipe (cmd, mode = 'r'):
211         
212         
213         redirect = ''
214         error_log_file = ''
215         if __main__.verbose_p:
216                 progress (_ ("Opening pipe `%s\'") % cmd)
217         else:
218                 error_log_file = error_log (command_name (cmd))
219                 redirect = ' 2>%s' % error_log_file
220                 
221         pipe = os.popen (cmd + redirect, mode)
222         output = pipe.read ()
223         status = pipe.close ()
224         # successful pipe close returns 'None'
225         if not status:
226                 status = 0
227         signal = 0x0f & status
228         exit_status = status >> 8
229
230         if status:
231                 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
232                 
233                 if not __main__.verbose_p:
234                         contents = open (error_log_file).read ()
235                         if contents:
236                                 error (_ ("The error log is as follows:"))
237                                 sys.stderr.write (contents)
238
239                 # Ugh. code dup
240                 if error_log_file:
241                         os.unlink (error_log_file)
242
243                 exit (1)
244                 
245         if __main__.verbose_p:
246                 progress ('\n')
247
248         if error_log_file:
249                 os.unlink (error_log_file)
250                 
251         return output
252
253 def system (cmd, ignore_error = 0, progress_p = 0):
254         
255         '''System CMD.  If IGNORE_ERROR, do not complain when CMD
256 returns non zero.  If PROGRESS_P, always show progress.
257
258 RETURN VALUE
259
260 Exit status of CMD '''
261
262         name = command_name (cmd)
263         error_log_file = ''
264         
265         if __main__.verbose_p:
266                 progress_p = 1
267                 progress (_ ("Invoking `%s\'") % cmd)
268         else:
269                 progress ( _("Running %s...") % name)
270
271         redirect = ''
272         if not progress_p:
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'
277
278         status = os.system (cmd + redirect)
279         signal = 0x0f & status
280         exit_status = status >> 8
281         
282         if status:
283                 
284                 exit_type =  'status %d' % exit_status
285                 if signal:
286                         exit_type = 'signal %d' % signal 
287                 
288                 msg = _ ("`%s\' failed (%s)") % (name, exit_type)
289                 if ignore_error:
290                         if __main__.verbose_p:
291                                 warning (msg + ' ' + _ ("(ignored)"))
292                 else:
293                         error (msg)
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 ())
297                         if error_log_file:
298                                 os.unlink (error_log_file)
299                         exit (1)
300
301         if error_log_file:
302                 os.unlink (error_log_file)
303         progress ('\n')
304         return status
305
306 def cleanup_temp ():
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:
312                         progress ('\n')
313
314
315 def strip_extension (f, ext):
316         (p, e) = os.path.splitext (f)
317         if e == ext:
318                 e = ''
319         return p + e
320
321
322 def cp_to_dir (pattern, dir):
323         "Copy files matching re PATTERN from cwd to DIR"
324         
325         # Duh.  Python style portable: cp *.EXT OUTDIR
326         # system ('cp *.%s %s' % (ext, outdir), 1)
327
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)
330
331
332 def search_exe_path (name):
333         p = os.environ['PATH']
334         exe_paths = string.split (p, ':')
335         for e in exe_paths:
336                 full = os.path.join (e, name)
337                 if os.path.exists (full):
338                         return full
339         return None
340
341
342 def mkdir_p (dir, mode=0777):
343         if not os.path.isdir (dir):
344                 makedirs (dir, mode)
345
346 def print_environment ():
347         for (k,v) in os.environ.items ():
348                 sys.stderr.write ("%s=\"%s\"\n" % (k, v)) 
349
350
351 def ps_page_count (ps_name):
352         header = open (ps_name).read (1024)
353         m = re.search ('\n%%Pages: ([0-9]+)', header)
354         if m:
355                 return string.atoi (m.group (1))
356         return 0
357
358 def make_ps_images (ps_name, resolution = 90, papersize = "a4",
359                     rename_page1_p = 0):
360         base = os.path.basename (re.sub (r'\.e?ps', '', ps_name))
361         header = open (ps_name).read (1024)
362
363         png1 = base + '.png'
364         pngn = base + '-page%d.png'
365         output_file = pngn
366         multi_page = re.search ('\n%%Pages: ', header)
367
368         # png16m is because Lily produces color nowadays.
369         if not multi_page:
370
371                 # GS can produce empty 2nd page if pngn is used.
372                 output_file = png1
373                 cmd = r'''gs\
374                 -dEPSCrop\
375                 -dGraphicsAlphaBits=4\
376                 -dNOPAUSE\
377                 -dTextAlphaBits=4\
378                 -sDEVICE=png16m\
379                 -sOutputFile='%(output_file)s'\
380                 -sPAPERSIZE=%(papersize)s\
381                 -q\
382                 -r%(resolution)d\
383                 '%(ps_name)s'\
384                 -c showpage\
385                 -c quit ''' % vars ()
386         else:
387                 cmd = r'''gs\
388                 -s\
389                 -dGraphicsAlphaBits=4\
390                 -dNOPAUSE\
391                 -dTextAlphaBits=4\
392                 -sDEVICE=png16m\
393                 -sOutputFile='%(output_file)s'\
394                 -sPAPERSIZE=%(papersize)s\
395                 -q\
396                 -r%(resolution)d\
397                 '%(ps_name)s'\
398                 -c quit''' % vars ()
399
400         remove = glob.glob (png1) + glob.glob (base + '-page*.png')
401         map (os.unlink, remove)
402
403         status = system (cmd)
404         signal = 0xf & status
405         exit_status = status >> 8
406
407         if status:
408                 remove = glob.glob (png1) + glob.glob (base + '-page*.png')
409                 map (os.unlink, remove)
410                 error (_ ("%s exited with status: %d") % ('GS', status))
411                 exit (1)
412
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))
416         return files