]> git.donarmstrong.com Git - lilypond.git/blob - python/lilylib.py
(make_ps_images): return list of output files.
[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
34 import os
35 import sys
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 # Customize these
49 if __name__ == '__main__':
50         import lilylib as ly
51         global _;_=ly._
52         global re;re = ly.re
53
54         # lilylib globals
55         program_name = 'unset'
56         pseudo_filter_p = 0
57         original_dir = os.getcwd ()
58         temp_dir = os.path.join (original_dir,  '%s.dir' % program_name)
59         keep_temp_dir_p = 0
60         verbose_p = 0
61
62         help_summary = _ ("lilylib module")
63
64         option_definitions = [
65                 ('', 'h', 'help', _ ("print this help")),
66                 ]
67
68         from lilylib import *
69 ################################################################
70
71 # Handle bug in Python 1.6-2.1
72 #
73 # there are recursion limits for some patterns in Python 1.6 til 2.1. 
74 # fix this by importing pre instead. Fix by Mats.
75
76 if float (sys.version[0:3]) <= 2.1:
77         try:
78                 import pre
79                 re = pre
80                 del pre
81         except ImportError:
82                 import re
83 else:
84         import re
85         
86 # Attempt to fix problems with limited stack size set by Python!
87 # Sets unlimited stack size. Note that the resource module only
88 # is available on UNIX.
89 try:
90        import resource
91        resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
92 except:
93        pass
94
95 localedir = '@localedir@'
96 try:
97         import gettext
98         gettext.bindtextdomain ('lilypond', localedir)
99         gettext.textdomain ('lilypond')
100         _ = gettext.gettext
101 except:
102         def _ (s):
103                 return s
104 underscore = _
105
106 def identify (port):
107         port.write ('%s (GNU LilyPond) %s\n' % (__main__.program_name, __main__.program_version))
108
109 def warranty ():
110         identify (sys.stdout)
111         sys.stdout.write ('\n')
112         sys.stdout.write (_ ("Copyright (c) %s by") % '1998--2004')
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") % s + '\n')
126
127 def error (s):
128         sys.stderr.write (__main__.program_name + ": " + _ ("error: %s") % s + '\n')
129         
130 def exit (i):
131         if __main__.verbose_p:
132                 raise _ ('Exiting (%d)...') % i
133         else:
134                 sys.exit (i)
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 [OPTIONS]... 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 lilypond_version (binary):
205         p = read_pipe ('%s --version ' % binary)
206
207         ls = p.split ('\n')
208         v= '<not found>'
209         for l in ls:
210                 m = re.search ('GNU LilyPond ([0-9a-z.]+)', p)
211                 if m:
212                         v = m.group (1)
213                         
214         return v
215         
216 def lilypond_version_check (binary, req):
217         if req[0] <> '@' :
218                 v = lilypond_version (binary)
219                 if v <> req:
220                         error (_("Binary %s has version %s, looking for version %s") % \
221                                (binary, v, req))
222                         sys.exit (1)
223         
224         
225 def setup_temp ():
226         
227         ''' Create a temporary directory, and return its name. '''
228         
229         if not __main__.keep_temp_dir_p:
230                 __main__.temp_dir = tempfile.mktemp (__main__.program_name)
231         try:
232                 os.mkdir (__main__.temp_dir, 0700)
233         except OSError:
234                 pass
235
236         return __main__.temp_dir
237
238 def command_name (cmd):
239
240         # deal with "((latex ) >& 1 ) .." too
241         cmd = re.match ("([\(\)]*)([^ ]*)", cmd).group(2)
242         return os.path.basename (cmd)
243
244 def error_log (name):
245         name = re.sub('[^a-z]','x', name)
246         return tempfile.mktemp ('%s.errorlog' % name)
247
248 def read_pipe (cmd, mode = 'r'):
249         
250         
251         redirect = ''
252         error_log_file = ''
253         if __main__.verbose_p:
254                 progress (_ ("Opening pipe `%s\'") % cmd)
255         else:
256                 error_log_file = error_log (command_name (cmd))
257                 redirect = ' 2>%s' % error_log_file
258                 
259         pipe = os.popen (cmd + redirect, mode)
260         output = pipe.read ()
261         status = pipe.close ()
262         # successful pipe close returns 'None'
263         if not status:
264                 status = 0
265         signal = 0x0f & status
266         exit_status = status >> 8
267
268         if status:
269                 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
270                 
271                 if not __main__.verbose_p:
272                         contents = open (error_log_file).read ()
273                         if contents:
274                                 error (_ ("The error log is as follows:"))
275                                 sys.stderr.write (contents)
276
277                 # Ugh. code dup
278                 if error_log_file:
279                         os.unlink (error_log_file)
280
281                 exit (1)
282                 
283         if __main__.verbose_p:
284                 progress ('\n')
285
286         if error_log_file:
287                 os.unlink (error_log_file)
288                 
289         return output
290
291 def system (cmd, ignore_error = 0, progress_p = 0):
292         
293         '''System CMD.  If IGNORE_ERROR, do not complain when CMD
294 returns non zero.  If PROGRESS_P, always show progress.
295
296 RETURN VALUE
297
298 Exit status of CMD '''
299
300         name = command_name (cmd)
301         error_log_file = ''
302         
303         if __main__.verbose_p:
304                 progress_p = 1
305                 progress (_ ("Invoking `%s\'") % cmd)
306         else:
307                 progress ( _("Running %s...") % name)
308
309         redirect = ''
310         if not progress_p:
311                 error_log_file = error_log (name)
312                 redirect = ' 1>/dev/null 2>' + error_log_file
313         elif __main__.pseudo_filter_p:
314                 redirect = ' 1>/dev/null'
315
316         status = os.system (cmd + redirect)
317         signal = 0x0f & status
318         exit_status = status >> 8
319         
320         if status:
321                 
322                 exit_type =  'status %d' % exit_status
323                 if signal:
324                         exit_type = 'signal %d' % signal 
325                 
326                 msg = _ ("`%s\' failed (%s)") % (name, exit_type)
327                 if ignore_error:
328                         if __main__.verbose_p:
329                                 warning (msg + ' ' + _ ("(ignored)"))
330                 else:
331                         error (msg)
332                         if not progress_p and error_log_file:
333                                 error (_ ("The error log is as follows:"))
334                                 sys.stderr.write (open (error_log_file).read ())
335                         if error_log_file:
336                                 os.unlink (error_log_file)
337                         exit (1)
338
339         if error_log_file:
340                 os.unlink (error_log_file)
341         progress ('\n')
342         return status
343
344 def cleanup_temp ():
345         if not __main__.keep_temp_dir_p:
346                 if __main__.verbose_p:
347                         progress (_ ("Cleaning %s...") % __main__.temp_dir)
348                 shutil.rmtree (__main__.temp_dir)
349                 if __main__.verbose_p:
350                         progress ('\n')
351
352
353 def strip_extension (f, ext):
354         (p, e) = os.path.splitext (f)
355         if e == ext:
356                 e = ''
357         return p + e
358
359
360 def cp_to_dir (pattern, dir):
361         "Copy files matching re PATTERN from cwd to DIR"
362         
363         # Duh.  Python style portable: cp *.EXT OUTDIR
364         # system ('cp *.%s %s' % (ext, outdir), 1)
365
366         files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
367         map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
368
369
370 # Python < 1.5.2 compatibility
371 #
372 # On most platforms, this is equivalent to
373 #`normpath(join(os.getcwd()), PATH)'.  *Added in Python version 1.5.2*
374
375 if os.path.__dict__.has_key ('abspath'):
376         abspath = os.path.abspath
377 else:
378         def abspath (path):
379                 return os.path.normpath (os.path.join (os.getcwd (), path))
380
381 if os.__dict__.has_key ('makedirs'):
382         makedirs = os.makedirs
383 else:
384         def makedirs (dir, mode=0777):
385                 system ('mkdir -p %s' % dir)
386
387
388 def mkdir_p (dir, mode=0777):
389         if not os.path.isdir (dir):
390                 makedirs (dir, mode)
391
392
393 environment = {}
394
395 # tex needs lots of memory, more than it gets by default on Debian
396 non_path_environment = {
397         'extra_mem_top' : '1000000',
398         'extra_mem_bottom' : '1000000',
399         'pool_size' : '250000',
400 }
401
402 def setup_environment ():
403         global environment
404
405         kpse = read_pipe ('kpsexpand \$TEXMF')
406         texmf = re.sub ('[ \t\n]+$','', kpse)
407         type1_paths = read_pipe ('kpsewhich -expand-path=\$T1FONTS')
408         
409         environment = {
410                 # TODO: * prevent multiple addition.
411                 #       * clean TEXINPUTS, MFINPUTS, TFMFONTS,
412                 #         as these take prevalence over $TEXMF
413                 #         and thus may break tex run?
414                 
415                 'TEXMF' : "{%s,%s}" % (datadir, texmf) ,
416                 'GS_FONTPATH' : type1_paths,
417                 'GS_LIB' : datadir + '/ps',
418                 }
419         
420         # $TEXMF is special, previous value is already taken care of
421         if os.environ.has_key ('TEXMF'):
422                 del os.environ['TEXMF']
423  
424         for key in environment.keys ():
425                 val = environment[key]
426                 if os.environ.has_key (key):
427                         val = os.environ[key] + os.pathsep + val 
428                 os.environ[key] = val
429
430         for key in non_path_environment.keys ():
431                 val = non_path_environment[key]
432                 os.environ[key] = val
433
434 def print_environment ():
435         for (k,v) in os.environ.items ():
436                 sys.stderr.write ("%s=\"%s\"\n" % (k, v)) 
437
438 BOUNDING_BOX_RE = '^%%BoundingBox: (-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)'
439 def get_bbox (filename):
440         bbox = filename + '.bbox'
441         ## -sOutputFile does not work with bbox?
442         cmd = 'gs -sDEVICE=bbox -q -dNOPAUSE %s -c quit 2>%s' % \
443               (filename, bbox)
444         system (cmd, progress_p = 1)
445         box = open (bbox).read ()
446         m = re.match (BOUNDING_BOX_RE, box)
447         gr = []
448         if m:
449                 gr = map (string.atoi, m.groups ())
450         
451         return gr
452
453
454 def make_ps_images (ps_name, resolution = 90):
455         ## todo:
456         ## have better algorithm for deciding when to crop page,
457         ## and when to show full page
458         base = re.sub (r'\.e?ps', '', ps_name)
459         
460         header = open (ps_name).read (1024)
461
462         match = re.match (BOUNDING_BOX_RE, header)
463         bbox = []
464         if match:
465                 bbox = map (string.atoi, match.groups ())
466
467         multi_page = re.search ('\n%%Pages: ', header)
468         cmd = ''
469
470         if multi_page == None:
471
472                 if bbox == []:
473                         bbox = get_bbox (ps_name)
474                         
475                 trans_ps = ps_name + '.trans.ps'
476                 output_file = re.sub (r'\.e?ps', '.png', ps_name)
477
478                 # need to have margin, otherwise edges of letters will
479                 # be cropped off.
480
481                 margin = 3 
482                 fo = open (trans_ps, 'w')
483                 fo.write ('%d %d translate\n' % (-bbox[0] + margin,
484                                                  -bbox[1] + margin))
485                 fo.close ()
486
487                 x = (2* margin + bbox[2] - bbox[0]) \
488                     * resolution / 72.0
489                 y = (2* margin + bbox[3] - bbox[1]) \
490                     * resolution / 72.0
491                 if x == 0:
492                         x = 1
493                 if y == 0:
494                         y = 1
495
496                 cmd = r'''gs -g%dx%d -sDEVICE=pnggray  -dTextAlphaBits=4 -dGraphicsAlphaBits=4  -q -sOutputFile=%s -r%d -dNOPAUSE %s %s -c quit ''' % \
497                       (x, y, output_file, resolution, trans_ps, ps_name)
498
499                 rms = glob.glob (base + '-page*.png')
500                 map (os.unlink, rms)
501         else:
502                 output_file = re.sub (r'\.e?ps', '-page%d.png', ps_name)
503
504                 rmfile = base + '.png'
505                 if os.path.isfile (rmfile):
506                         os.unlink (rmfile)
507                 
508                 cmd = r'''gs -s  -sDEVICE=pnggray  -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -q -sOutputFile=%s -dNOPAUSE -r%d %s -c quit''' % (output_file,
509                                                                                                                                       resolution, ps_name)
510
511         status = system (cmd)
512         signal = 0xf & status
513         exit_status = status >> 8
514
515         
516         if status:
517                 os.unlink (png)
518                 error (_ ("Removing output file"))
519                 exit (1)
520
521
522         cmd = r'''gs -s  -sDEVICE=pnggray  -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -q -sOutputFile=%s -dNOPAUSE -r%d %s -c quit''' % (output_file,
523                                                                                                                                       resolution, ps_name)
524
525         files = glob.glob (re.sub ('%d', '*', output_file))
526         return files
527