]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
* Another grand 2003 update.
[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--2003  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 shutil
16 import string
17 import sys
18 import tempfile
19
20 ################################################################
21 # Users of python modules should include this snippet
22 # and customize variables below.
23
24 # We'll suffer this path init stuff as long as we don't install our
25 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
26 # it as we do with teTeX on Red Hat Linux: set some environment var
27 # (PYTHONPATH) in profile)
28
29 # If set, LILYPONDPREFIX must take prevalence
30 # if datadir is not set, we're doing a build and LILYPONDPREFIX
31 import getopt, os, sys
32 datadir = '@local_lilypond_datadir@'
33 if not os.path.isdir (datadir):
34         datadir = '@lilypond_datadir@'
35 if os.environ.has_key ('LILYPONDPREFIX') :
36         datadir = os.environ['LILYPONDPREFIX']
37         while datadir[-1] == os.sep:
38                 datadir= datadir[:-1]
39
40 sys.path.insert (0, os.path.join (datadir, 'python'))
41
42
43
44 # Customize these
45 if __name__ == '__main__':
46         import lilylib as ly
47         global _;_=ly._
48         global re;re = ly.re
49
50         # lilylib globals
51         program_name = 'unset'
52         pseudo_filter_p = 0
53         original_dir = os.getcwd ()
54         temp_dir = os.path.join (original_dir,  '%s.dir' % program_name)
55         keep_temp_dir_p = 0
56         verbose_p = 0
57
58         help_summary = _ ("lilylib module")
59
60         option_definitions = [
61                 ('', 'h', 'help', _ ("this help")),
62                 ]
63
64         from lilylib import *
65 ################################################################
66
67 # Handle bug in Python 1.6-2.1
68 #
69 # there are recursion limits for some patterns in Python 1.6 til 2.1. 
70 # fix this by importing pre instead. Fix by Mats.
71
72 if float (sys.version[0:3]) <= 2.1:
73         try:
74                 import pre
75                 re = pre
76                 del pre
77         except ImportError:
78                 import re
79 else:
80         import re
81         
82 # Attempt to fix problems with limited stack size set by Python!
83 # Sets unlimited stack size. Note that the resource module only
84 # is available on UNIX.
85 try:
86        import resource
87        resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
88 except:
89        pass
90
91 localedir = '@localedir@'
92 try:
93         import gettext
94         gettext.bindtextdomain ('lilypond', localedir)
95         gettext.textdomain ('lilypond')
96         _ = gettext.gettext
97 except:
98         def _ (s):
99                 return s
100 underscore = _
101
102 program_version = '@TOPLEVEL_VERSION@'
103 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
104         program_version = '1.7.14'
105
106 def identify (port):
107         port.write ('%s (GNU LilyPond) %s\n' % (__main__.program_name, program_version))
108
109 def warranty ():
110         identify (sys.stdout)
111         sys.stdout.write ('\n')
112         sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998--2003'))
113         sys.stdout.write ('\n')
114         map (lambda x: sys.stdout.write ('  %s\n' % x), __main__.copyright)
115         sys.stdout.write ('\n')
116         sys.stdout.write (_ ("Distributed under terms of the GNU General Public License."))
117         sys.stdout.write ('\n')
118         sys.stdout.write (_ ("It comes with NO WARRANTY."))
119         sys.stdout.write ('\n')
120
121 def progress (s):
122         sys.stderr.write (s)
123
124 def warning (s):
125         sys.stderr.write (__main__.program_name + ": " + _ ("warning: ") + s + '\n')
126
127 def error (s):
128         sys.stderr.write (__main__.program_name + ": " + _ ("error: ") + s + '\n')
129         
130 def exit (i):
131         if __main__.verbose_p:
132                 raise _ ('Exiting (%d)...') % i
133         else:
134                 sys.exit (1)
135                 
136 def getopt_args (opts):
137         '''Construct arguments (LONG, SHORT) for getopt from  list of options.'''
138         short = ''
139         long = []
140         for o in opts:
141                 if o[1]:
142                         short = short + o[1]
143                         if o[0]:
144                                 short = short + ':'
145                 if o[2]:
146                         l = o[2]
147                         if o[0]:
148                                 l = l + '='
149                         long.append (l)
150         return (short, long)
151
152 def option_help_str (o):
153         '''Transform one option description (4-tuple ) into neatly formatted string'''
154         sh = '  '       
155         if o[1]:
156                 sh = '-%s' % o[1]
157
158         sep = ' '
159         if o[1] and o[2]:
160                 sep = ','
161                 
162         long = ''
163         if o[2]:
164                 long= '--%s' % o[2]
165
166         arg = ''
167         if o[0]:
168                 if o[2]:
169                         arg = '='
170                 arg = arg + o[0]
171         return '  ' + sh + sep + long + arg
172
173
174 def options_help_str (opts):
175         '''Convert a list of options into a neatly formatted string'''
176         w = 0
177         strs =[]
178         helps = []
179
180         for o in opts:
181                 s = option_help_str (o)
182                 strs.append ((s, o[3]))
183                 if len (s) > w:
184                         w = len (s)
185
186         str = ''
187         for s in strs:
188                 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0])  + 3), s[1])
189         return str
190
191 def help ():
192         ls = [(_ ("Usage: %s [OPTION]... FILE") % __main__.program_name),
193               ('\n\n'),
194               (__main__.help_summary),
195               ('\n\n'),
196               (_ ("Options:")),
197               ('\n'),
198               (options_help_str (__main__.option_definitions)),
199               ('\n\n'),
200               (_ ("Report bugs to %s") % 'bug-lilypond@gnu.org'),
201               ('\n')]
202         map (sys.stdout.write, ls)
203         
204 def setup_temp ():
205         
206         ''' Create a temporary directory, and return its name. '''
207         
208         if not __main__.keep_temp_dir_p:
209                 __main__.temp_dir = tempfile.mktemp (__main__.program_name)
210         try:
211                 os.mkdir (__main__.temp_dir, 0700)
212         except OSError:
213                 pass
214
215         return __main__.temp_dir
216
217 def command_name (cmd):
218         return re.match ('^[ \t]*([^ \t]*)', cmd).group (1)
219
220 def error_log (name):
221         return os.path.join (__main__.temp_dir, '%s.errorlog' % name)
222
223 def read_pipe (cmd, mode = 'r'):
224         redirect = ''
225         if __main__.verbose_p:
226                 progress (_ ("Opening pipe `%s\'") % cmd)
227                 redirect = ' 2>%s' % error_log (command_name (cmd))
228         pipe = os.popen (cmd + redirect, mode)
229         output = pipe.read ()
230         status = pipe.close ()
231         # successful pipe close returns 'None'
232         if not status:
233                 status = 0
234         signal = 0x0f & status
235         exit_status = status >> 8
236
237         if status:
238                 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
239                 if not __main__.verbose_p:
240                         error (_ ("The error log is as follows:"))
241                         sys.stderr.write (open (error_log (command_name (cmd)).read ()))
242                 exit (status)
243         if __main__.verbose_p:
244                 progress ('\n')
245         return output
246
247 def system (cmd, ignore_error = 0, progress_p = 0):
248         
249         '''System CMD.  If IGNORE_ERROR, do not complain when CMD
250 returns non zero.  If PROGRESS_P, always show progress.
251
252 RETURN VALUE
253
254 Exit status of CMD '''
255
256         name = command_name (cmd)
257
258         if __main__.verbose_p:
259                 progress_p = 1
260                 progress (_ ("Invoking `%s\'") % cmd)
261         else:
262                 progress ( _("Running %s...") % name)
263
264         redirect = ''
265         if not progress_p:
266                 redirect = ' 1>/dev/null 2>' + error_log (name)
267         elif __main__.pseudo_filter_p:
268                 redirect = ' 1>/dev/null'
269                         
270         status = os.system (cmd + redirect)
271         signal = 0x0f & status
272         exit_status = status >> 8
273         
274         if status:
275                 
276                 exit_type =  'status %d' % exit_status
277                 if signal:
278                         exit_type = 'signal %d' % signal 
279                 
280                 msg = _ ("`%s\' failed (%s)") % (name, exit_type)
281                 if ignore_error:
282                         if __main__.verbose_p:
283                                 warning (msg + ' ' + _ ("(ignored)"))
284                 else:
285                         error (msg)
286                         if not progress_p:
287                                 error (_ ("The error log is as follows:"))
288                                 sys.stderr.write (open (error_log (name)).read ())
289                         exit (status)
290
291         progress ('\n')
292         return status
293
294 def cleanup_temp ():
295         if not __main__.keep_temp_dir_p:
296                 if __main__.verbose_p:
297                         progress (_ ("Cleaning %s...") % __main__.temp_dir)
298                 shutil.rmtree (__main__.temp_dir)
299                 if __main__.verbose_p:
300                         progress ('\n')
301
302
303 def strip_extension (f, ext):
304         (p, e) = os.path.splitext (f)
305         if e == ext:
306                 e = ''
307         return p + e
308
309
310 def cp_to_dir (pattern, dir):
311         "Copy files matching re PATTERN from cwd to DIR"
312         # Duh.  Python style portable: cp *.EXT OUTDIR
313         # system ('cp *.%s %s' % (ext, outdir), 1)
314         files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
315         map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
316
317
318 # Python < 1.5.2 compatibility
319 #
320 # On most platforms, this is equivalent to
321 #`normpath(join(os.getcwd()), PATH)'.  *Added in Python version 1.5.2*
322 if os.path.__dict__.has_key ('abspath'):
323         abspath = os.path.abspath
324 else:
325         def abspath (path):
326                 return os.path.normpath (os.path.join (os.getcwd (), path))
327
328 if os.__dict__.has_key ('makedirs'):
329         makedirs = os.makedirs
330 else:
331         def makedirs (dir, mode=0777):
332                 system ('mkdir -p %s' % dir)
333
334
335 def mkdir_p (dir, mode=0777):
336         if not os.path.isdir (dir):
337                 makedirs (dir, mode)
338
339
340 environment = {}
341
342 # tex needs lots of memory, more than it gets by default on Debian
343 non_path_environment = {
344         'extra_mem_top' : '1000000',
345         'extra_mem_bottom' : '1000000',
346         'pool_size' : '250000',
347 }
348
349 def setup_environment ():
350         global environment
351
352         kpse = read_pipe ('kpsexpand \$TEXMF')
353         texmf = re.sub ('[ \t\n]+$','', kpse)
354         type1_paths = read_pipe ('kpsewhich -expand-path=\$T1FONTS')
355         
356         environment = {
357                 # TODO: * prevent multiple addition.
358                 #       * clean TEXINPUTS, MFINPUTS, TFMFONTS,
359                 #         as these take prevalence over $TEXMF
360                 #         and thus may break tex run?
361                 'TEXMF' : "{%s,%s}" % (datadir, texmf) ,
362                 'GS_FONTPATH' : type1_paths,
363                 'GS_LIB' : datadir + '/ps',
364                 }
365         
366         # $TEXMF is special, previous value is already taken care of
367         if os.environ.has_key ('TEXMF'):
368                 del os.environ['TEXMF']
369  
370         for key in environment.keys ():
371                 val = environment[key]
372                 if os.environ.has_key (key):
373                         val = os.environ[key] + os.pathsep + val 
374                 os.environ[key] = val
375
376         for key in non_path_environment.keys ():
377                 val = non_path_environment[key]
378                 os.environ[key] = val
379
380 def print_environment ():
381         for (k,v) in os.environ.items ():
382                 sys.stderr.write ("%s=\"%s\"\n" % (k, v)) 
383
384 def get_bbox (filename):
385         bbox = filename + '.bbox'
386         ## -sOutputFile does not work with bbox?
387         cmd = 'gs -sDEVICE=bbox -q -dNOPAUSE %s -c quit 2>%s' % \
388               (filename, bbox)
389         system (cmd, progress_p = 1)
390         box = open (bbox).read ()
391         m = re.match ('^%%BoundingBox: ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)',
392                       box)
393         gr = []
394         if m:
395                 gr = map (string.atoi, m.groups ())
396         
397         return gr
398
399 def make_preview (name):
400         ## ly2dvi/lilypond-book discrepancy
401         preview_ps = name + '.preview.ps'
402         if not os.path.isfile (preview_ps):
403                 preview_ps = name + '.eps'
404         bbox = get_bbox (preview_ps)
405         trans_ps = name + '.trans.ps'
406         png = name + '.png'
407         
408         margin = 0
409         fo = open (trans_ps, 'w')
410         fo.write ('%d %d translate\n' % (-bbox[0] + margin,
411                                          -bbox[1] + margin))
412         fo.close ()
413         
414         x = (2* margin + bbox[2] - bbox[0]) \
415             * __main__.preview_resolution / 72.0
416         y = (2* margin + bbox[3] - bbox[1]) \
417             * __main__.preview_resolution / 72.0
418         if x == 0:
419                 x = 1
420         if y == 0:
421                 y = 1
422
423         cmd = r'''gs -g%dx%d -sDEVICE=pnggray  -dTextAlphaBits=4 -dGraphicsAlphaBits=4  -q -sOutputFile=%s -r%d -dNOPAUSE %s %s -c quit ''' % \
424               (x, y, png, __main__.preview_resolution, trans_ps, preview_ps)
425         
426         status = system (cmd)
427         signal = 0xf & status
428         exit_status = status >> 8
429         
430         if status:
431                 os.unlink (png)
432                 error (_ ("Removing output file"))
433                 exit (1)
434
435 def make_page_images (name, resolution = 90):
436
437         """ Generate images for
438         all pages in the PS file NAME. NAME should be the basename
439         (not including the extension.).
440         """
441         
442         cmd = 'gs -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -sOutputFile="%s-page%%d.png" -r%d -dNOPAUSE %s -c quit'
443         cmd = cmd % (name, resolution, name + '.ps')
444         system (cmd)