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