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