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