make flat stem shorter
[lilypond.git] / python / lilylib.py
blob3f0b0e7302c3a5db5bf7cc07214dc32846643e4e
1 ################################################################
2 # lilylib.py -- options and stuff
3 #
4 # source file of the GNU LilyPond music typesetter
6 # (c) 1998--2002 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 # Jan Nieuwenhuizen <janneke@gnu.org>
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 (
12 ### subst: \(help_summary\|keep_temp_dir_p\|option_definitions\|original_dir\|program_name\|pseudo_filter_p\|temp_dir\|verbose_p\)
14 import __main__
15 import shutil
16 import string
17 import sys
18 import tempfile
20 ################################################################
21 # Users of python modules should include this snippet
22 # and customize variables below.
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)
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]
40 sys.path.insert (0, os.path.join (datadir, 'python'))
42 # Customize these
43 if __name__ == '__main__':
44 import lilylib as ly
45 global _;_=ly._
46 global re;re = ly.re
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
56 help_summary = _ ("lilylib module")
58 option_definitions = [
59 ('', 'h', 'help', _ ("this help")),
62 from lilylib import *
63 ################################################################
65 # Handle bug in Python 1.6-2.1
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.
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
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
89 localedir = '@localedir@'
90 try:
91 import gettext
92 gettext.bindtextdomain ('lilypond', localedir)
93 gettext.textdomain ('lilypond')
94 _ = gettext.gettext
95 except:
96 def _ (s):
97 return s
98 underscore = _
100 program_version = '@TOPLEVEL_VERSION@'
101 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
102 program_version = '1.7.5'
104 def identify (port):
105 port.write ('%s (GNU LilyPond) %s\n' % (__main__.program_name, program_version))
107 def warranty ():
108 identify (sys.stdout)
109 sys.stdout.write ('\n')
110 sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998--2002'))
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')
119 def progress (s):
120 sys.stderr.write (s)
122 def warning (s):
123 sys.stderr.write (__main__.program_name + ": " + _ ("warning: ") + s + '\n')
125 def error (s):
126 sys.stderr.write (__main__.program_name + ": " + _ ("error: ") + s + '\n')
128 def exit (i):
129 if __main__.verbose_p:
130 raise _ ('Exiting (%d)...') % i
131 else:
132 sys.exit (1)
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)
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]
156 sep = ' '
157 if o[1] and o[2]:
158 sep = ','
160 long = ''
161 if o[2]:
162 long= '--%s' % o[2]
164 arg = ''
165 if o[0]:
166 if o[2]:
167 arg = '='
168 arg = arg + o[0]
169 return ' ' + sh + sep + long + arg
172 def options_help_str (opts):
173 '''Convert a list of options into a neatly formatted string'''
174 w = 0
175 strs =[]
176 helps = []
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)
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
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)
202 def setup_temp ():
204 ''' Create a temporary directory, and return its name. '''
206 if not __main__.keep_temp_dir_p:
207 __main__.temp_dir = tempfile.mktemp (__main__.program_name)
208 try:
209 os.mkdir (__main__.temp_dir, 0777)
210 except OSError:
211 pass
213 return __main__.temp_dir
215 def command_name (cmd):
216 return re.match ('^[ \t]*([^ \t]*)', cmd).group (1)
218 def error_log (name):
219 return os.path.join (__main__.temp_dir, '%s.errorlog' % name)
221 def read_pipe (cmd, mode = 'r'):
222 redirect = ''
223 if __main__.verbose_p:
224 progress (_ ("Opening pipe `%s\'") % cmd)
225 redirect = ' 2>%s' % error_log (command_name (cmd))
226 pipe = os.popen (cmd + redirect, mode)
227 output = pipe.read ()
228 status = pipe.close ()
229 # successful pipe close returns 'None'
230 if not status:
231 status = 0
232 signal = 0x0f & status
233 exit_status = status >> 8
235 if status:
236 error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
237 if not __main__.verbose_p:
238 error (_ ("The error log is as follows:"))
239 sys.stderr.write (open (error_log (command_name (cmd)).read ()))
240 exit (status)
241 if __main__.verbose_p:
242 progress ('\n')
243 return output
245 def system (cmd, ignore_error = 0, progress_p = 0):
247 '''System CMD. If IGNORE_ERROR, do not complain when CMD
248 returns non zero. If PROGRESS_P, always show progress.
250 RETURN VALUE
252 Exit status of CMD '''
254 name = command_name (cmd)
256 if __main__.verbose_p:
257 progress_p = 1
258 progress (_ ("Invoking `%s\'") % cmd)
259 else:
260 progress ( _("Running %s...") % name)
262 redirect = ''
263 if not progress_p:
264 redirect = ' 1>/dev/null 2>' + error_log (name)
265 elif __main__.pseudo_filter_p:
266 redirect = ' 1>/dev/null'
268 status = os.system (cmd + redirect)
269 signal = 0x0f & status
270 exit_status = status >> 8
272 if status:
274 exit_type = 'status %d' % exit_status
275 if signal:
276 exit_type = 'signal %d' % signal
278 msg = _ ("`%s\' failed (%s)") % (name, exit_type)
279 if ignore_error:
280 if __main__.verbose_p:
281 warning (msg + ' ' + _ ("(ignored)"))
282 else:
283 error (msg)
284 if not progress_p:
285 error (_ ("The error log is as follows:"))
286 sys.stderr.write (open (error_log (name)).read ())
287 exit (status)
289 progress ('\n')
290 return status
292 def cleanup_temp ():
293 if not __main__.keep_temp_dir_p:
294 if __main__.verbose_p:
295 progress (_ ("Cleaning %s...") % __main__.temp_dir)
296 shutil.rmtree (__main__.temp_dir)
297 if __main__.verbose_p:
298 progress ('\n')
301 def strip_extension (f, ext):
302 (p, e) = os.path.splitext (f)
303 if e == ext:
304 e = ''
305 return p + e
308 def cp_to_dir (pattern, dir):
309 "Copy files matching re PATTERN from cwd to DIR"
310 # Duh. Python style portable: cp *.EXT OUTDIR
311 # system ('cp *.%s %s' % (ext, outdir), 1)
312 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
313 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
316 # Python < 1.5.2 compatibility
318 # On most platforms, this is equivalent to
319 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
320 if os.path.__dict__.has_key ('abspath'):
321 abspath = os.path.abspath
322 else:
323 def abspath (path):
324 return os.path.normpath (os.path.join (os.getcwd (), path))
326 if os.__dict__.has_key ('makedirs'):
327 makedirs = os.makedirs
328 else:
329 def makedirs (dir, mode=0777):
330 system ('mkdir -p %s' % dir)
333 def mkdir_p (dir, mode=0777):
334 if not os.path.isdir (dir):
335 makedirs (dir, mode)
338 environment = {}
340 # tex needs lots of memory, more than it gets by default on Debian
341 non_path_environment = {
342 'extra_mem_top' : '1000000',
343 'extra_mem_bottom' : '1000000',
344 'pool_size' : '250000',
347 def setup_environment ():
348 global environment
350 kpse = read_pipe ('kpsexpand \$TEXMF')
351 texmf = re.sub ('[ \t\n]+$','', kpse)
352 type1_paths = read_pipe ('kpsewhich -expand-path=\$T1FONTS')
354 environment = {
355 # TODO: * prevent multiple addition.
356 # * clean TEXINPUTS, MFINPUTS, TFMFONTS,
357 # as these take prevalence over $TEXMF
358 # and thus may break tex run?
359 'TEXMF' : "{%s,%s}" % (datadir, texmf) ,
360 'GS_FONTPATH' : type1_paths,
361 'GS_LIB' : datadir + '/ps',
364 # $TEXMF is special, previous value is already taken care of
365 if os.environ.has_key ('TEXMF'):
366 del os.environ['TEXMF']
368 for key in environment.keys ():
369 val = environment[key]
370 if os.environ.has_key (key):
371 val = os.environ[key] + os.pathsep + val
372 os.environ[key] = val
374 for key in non_path_environment.keys ():
375 val = non_path_environment[key]
376 os.environ[key] = val
378 def print_environment ():
379 for (k,v) in os.environ.items ():
380 sys.stderr.write ("%s=\"%s\"\n" % (k, v))
382 def get_bbox (filename):
383 bbox = filename + '.bbox'
384 ## -sOutputFile does not work with bbox?
385 cmd = 'gs -sDEVICE=bbox -q -dNOPAUSE %s -c quit 2>%s' % \
386 (filename, bbox)
387 system (cmd, progress_p = 1)
388 box = open (bbox).read ()
389 m = re.match ('^%%BoundingBox: ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)',
390 box)
391 gr = []
392 if m:
393 gr = map (string.atoi, m.groups ())
395 return gr
397 def make_preview (name):
398 ## ly2dvi/lilypond-book discrepancy
399 preview_ps = name + '.preview.ps'
400 if not os.path.isfile (preview_ps):
401 preview_ps = name + '.eps'
402 bbox = get_bbox (preview_ps)
403 trans_ps = name + '.trans.ps'
404 png = name + '.png'
406 margin = 0
407 fo = open (trans_ps, 'w')
408 fo.write ('%d %d translate\n' % (-bbox[0] + margin,
409 -bbox[1] + margin))
410 fo.close ()
412 x = (2* margin + bbox[2] - bbox[0]) \
413 * __main__.preview_resolution / 72.0
414 y = (2* margin + bbox[3] - bbox[1]) \
415 * __main__.preview_resolution / 72.0
416 if x == 0:
417 x = 1
418 if y == 0:
419 y = 1
421 cmd = r'''gs -g%dx%d -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -q -sOutputFile=%s -r%d -dNOPAUSE %s %s -c quit ''' % \
422 (x, y, png, __main__.preview_resolution, trans_ps, preview_ps)
424 system (cmd)
426 status = system (cmd)
427 signal = 0xf & status
428 exit_status = status >> 8
430 if status:
431 os.unlink (png)
432 error (_ ("Removing output file"))
433 exit (1)