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