]> git.donarmstrong.com Git - lilypond.git/blobdiff - python/lilylib.py
* Another grand 2003 update.
[lilypond.git] / python / lilylib.py
index 7caac5254c5925edf381806c0733349a46ee3941..67485321f750dc4b9765cb0f7c95aad922f9a16c 100644 (file)
@@ -3,7 +3,7 @@
 # 
 # source file of the GNU LilyPond music typesetter
 #
-# (c) 1998--2002  Han-Wen Nienhuys <hanwen@cs.uu.nl>
+# (c)  1998--2003  Han-Wen Nienhuys <hanwen@cs.uu.nl>
 #                 Jan Nieuwenhuizen <janneke@gnu.org>
 
 ###  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\) *(
@@ -13,6 +13,7 @@
 
 import __main__
 import shutil
+import string
 import sys
 import tempfile
 
@@ -38,13 +39,17 @@ if os.environ.has_key ('LILYPONDPREFIX') :
 
 sys.path.insert (0, os.path.join (datadir, 'python'))
 
+
+
 # Customize these
 if __name__ == '__main__':
        import lilylib as ly
        global _;_=ly._
+       global re;re = ly.re
 
        # lilylib globals
        program_name = 'unset'
+       pseudo_filter_p = 0
        original_dir = os.getcwd ()
        temp_dir = os.path.join (original_dir,  '%s.dir' % program_name)
        keep_temp_dir_p = 0
@@ -64,14 +69,16 @@ if __name__ == '__main__':
 # there are recursion limits for some patterns in Python 1.6 til 2.1. 
 # fix this by importing pre instead. Fix by Mats.
 
-# todo: should check Python version first.
-try:
-       import pre
-       re = pre
-       del pre
-except ImportError:
+if float (sys.version[0:3]) <= 2.1:
+       try:
+               import pre
+               re = pre
+               del pre
+       except ImportError:
+               import re
+else:
        import re
-
+       
 # Attempt to fix problems with limited stack size set by Python!
 # Sets unlimited stack size. Note that the resource module only
 # is available on UNIX.
@@ -81,45 +88,44 @@ try:
 except:
        pass
 
+localedir = '@localedir@'
 try:
        import gettext
        gettext.bindtextdomain ('lilypond', localedir)
        gettext.textdomain ('lilypond')
-       global _
        _ = gettext.gettext
 except:
        def _ (s):
                return s
 underscore = _
 
-program_version = '1.6.6'
+program_version = '@TOPLEVEL_VERSION@'
 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
-       program_version = '1.5.54'
+       program_version = '1.7.14'
 
 def identify (port):
        port.write ('%s (GNU LilyPond) %s\n' % (__main__.program_name, program_version))
 
-# hmm
 def warranty ():
        identify (sys.stdout)
        sys.stdout.write ('\n')
-       sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998--2002'))
+       sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998--2003'))
+       sys.stdout.write ('\n')
+       map (lambda x: sys.stdout.write ('  %s\n' % x), __main__.copyright)
        sys.stdout.write ('\n')
-       sys.stdout.write ('  Han-Wen Nienhuys')
-       sys.stdout.write ('  Jan Nieuwenhuizen')
-       sys.stdout.write ('\n\n')
+       sys.stdout.write (_ ("Distributed under terms of the GNU General Public License."))
        sys.stdout.write ('\n')
-       sys.stdout.write (_ ("Distributed under terms of the GNU General Public License.  It comes with NO WARRANTY."))
+       sys.stdout.write (_ ("It comes with NO WARRANTY."))
        sys.stdout.write ('\n')
 
 def progress (s):
        sys.stderr.write (s)
 
 def warning (s):
-       sys.stderr.write (__main__.program_name + ":" + _ ("warning: ") + s + '\n')
+       sys.stderr.write (__main__.program_name + ": " + _ ("warning: ") + s + '\n')
 
 def error (s):
-       sys.stderr.write (__main__.program_name + ":" + _ ("error: ") + s + '\n')
+       sys.stderr.write (__main__.program_name + ": " + _ ("error: ") + s + '\n')
        
 def exit (i):
        if __main__.verbose_p:
@@ -202,7 +208,7 @@ def setup_temp ():
        if not __main__.keep_temp_dir_p:
                __main__.temp_dir = tempfile.mktemp (__main__.program_name)
        try:
-               os.mkdir (__main__.temp_dir, 0777)
+               os.mkdir (__main__.temp_dir, 0700)
        except OSError:
                pass
 
@@ -238,10 +244,10 @@ def read_pipe (cmd, mode = 'r'):
                progress ('\n')
        return output
 
-def system (cmd, ignore_error = 0):
+def system (cmd, ignore_error = 0, progress_p = 0):
        
-       ''' Run CMD.  If IGNORE_ERROR is set, do not complain when CMD
-returns non zero.
+       '''System CMD.  If IGNORE_ERROR, do not complain when CMD
+returns non zero.  If PROGRESS_P, always show progress.
 
 RETURN VALUE
 
@@ -249,27 +255,35 @@ Exit status of CMD '''
 
        name = command_name (cmd)
 
-       redirect = ''
        if __main__.verbose_p:
+               progress_p = 1
                progress (_ ("Invoking `%s\'") % cmd)
-               if __main__.pseudo_filter_p:
-                       redirect = ' 1> /dev/null'
        else:
                progress ( _("Running %s...") % name)
-               redirect = ' 1> /dev/null 2>%s' % error_log (name)
 
+       redirect = ''
+       if not progress_p:
+               redirect = ' 1>/dev/null 2>' + error_log (name)
+       elif __main__.pseudo_filter_p:
+               redirect = ' 1>/dev/null'
+                       
        status = os.system (cmd + redirect)
        signal = 0x0f & status
        exit_status = status >> 8
        
        if status:
-               msg = _ ("`%s\' failed (%d)") % (name, status / exit_status)
+               
+               exit_type =  'status %d' % exit_status
+               if signal:
+                       exit_type = 'signal %d' % signal 
+               
+               msg = _ ("`%s\' failed (%s)") % (name, exit_type)
                if ignore_error:
                        if __main__.verbose_p:
                                warning (msg + ' ' + _ ("(ignored)"))
                else:
                        error (msg)
-                       if not __main__.verbose_p:
+                       if not progress_p:
                                error (_ ("The error log is as follows:"))
                                sys.stderr.write (open (error_log (name)).read ())
                        exit (status)
@@ -321,3 +335,110 @@ else:
 def mkdir_p (dir, mode=0777):
        if not os.path.isdir (dir):
                makedirs (dir, mode)
+
+
+environment = {}
+
+# tex needs lots of memory, more than it gets by default on Debian
+non_path_environment = {
+       'extra_mem_top' : '1000000',
+       'extra_mem_bottom' : '1000000',
+       'pool_size' : '250000',
+}
+
+def setup_environment ():
+       global environment
+
+       kpse = read_pipe ('kpsexpand \$TEXMF')
+       texmf = re.sub ('[ \t\n]+$','', kpse)
+       type1_paths = read_pipe ('kpsewhich -expand-path=\$T1FONTS')
+       
+       environment = {
+               # TODO: * prevent multiple addition.
+               #       * clean TEXINPUTS, MFINPUTS, TFMFONTS,
+               #         as these take prevalence over $TEXMF
+               #         and thus may break tex run?
+               'TEXMF' : "{%s,%s}" % (datadir, texmf) ,
+               'GS_FONTPATH' : type1_paths,
+               'GS_LIB' : datadir + '/ps',
+               }
+       
+       # $TEXMF is special, previous value is already taken care of
+       if os.environ.has_key ('TEXMF'):
+               del os.environ['TEXMF']
+       for key in environment.keys ():
+               val = environment[key]
+               if os.environ.has_key (key):
+                       val = os.environ[key] + os.pathsep + val 
+               os.environ[key] = val
+
+       for key in non_path_environment.keys ():
+               val = non_path_environment[key]
+               os.environ[key] = val
+
+def print_environment ():
+       for (k,v) in os.environ.items ():
+               sys.stderr.write ("%s=\"%s\"\n" % (k, v)) 
+
+def get_bbox (filename):
+       bbox = filename + '.bbox'
+       ## -sOutputFile does not work with bbox?
+       cmd = 'gs -sDEVICE=bbox -q -dNOPAUSE %s -c quit 2>%s' % \
+             (filename, bbox)
+       system (cmd, progress_p = 1)
+       box = open (bbox).read ()
+       m = re.match ('^%%BoundingBox: ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)',
+                     box)
+       gr = []
+       if m:
+               gr = map (string.atoi, m.groups ())
+       
+       return gr
+
+def make_preview (name):
+       ## ly2dvi/lilypond-book discrepancy
+       preview_ps = name + '.preview.ps'
+       if not os.path.isfile (preview_ps):
+               preview_ps = name + '.eps'
+       bbox = get_bbox (preview_ps)
+       trans_ps = name + '.trans.ps'
+       png = name + '.png'
+       
+       margin = 0
+       fo = open (trans_ps, 'w')
+       fo.write ('%d %d translate\n' % (-bbox[0] + margin,
+                                        -bbox[1] + margin))
+       fo.close ()
+       
+       x = (2* margin + bbox[2] - bbox[0]) \
+           * __main__.preview_resolution / 72.0
+       y = (2* margin + bbox[3] - bbox[1]) \
+           * __main__.preview_resolution / 72.0
+       if x == 0:
+               x = 1
+       if y == 0:
+               y = 1
+
+       cmd = r'''gs -g%dx%d -sDEVICE=pnggray  -dTextAlphaBits=4 -dGraphicsAlphaBits=4  -q -sOutputFile=%s -r%d -dNOPAUSE %s %s -c quit ''' % \
+             (x, y, png, __main__.preview_resolution, trans_ps, preview_ps)
+       
+       status = system (cmd)
+       signal = 0xf & status
+       exit_status = status >> 8
+       
+       if status:
+               os.unlink (png)
+               error (_ ("Removing output file"))
+               exit (1)
+
+def make_page_images (name, resolution = 90):
+
+       """ Generate images for
+       all pages in the PS file NAME. NAME should be the basename
+       (not including the extension.).
+       """
+       
+       cmd = 'gs -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -sOutputFile="%s-page%%d.png" -r%d -dNOPAUSE %s -c quit'
+       cmd = cmd % (name, resolution, name + '.ps')
+       system (cmd)