]> git.donarmstrong.com Git - lilypond.git/blobdiff - scripts/ly2dvi.py
2002-07-13 Han-Wen <hanwen@cs.uu.nl>
[lilypond.git] / scripts / ly2dvi.py
index 4e8a5322532f044ea290b63e2e4f11d22ffa57cb..bdd9f4ac5a3fb8c18cfdac074862582b0dea21d3 100644 (file)
@@ -50,9 +50,6 @@ TODO:
 '''
 
 
-
-
-
 import os
 import stat
 import string
@@ -66,6 +63,11 @@ import tempfile
 import traceback
 
 
+################################################################
+# lilylib.py -- options and stuff
+# 
+# source file of the GNU LilyPond music typesetter
+
 # Handle bug in Python 1.6-2.1
 #
 # there are recursion limits for some patterns in Python 1.6 til 2.1. 
@@ -79,11 +81,14 @@ try:
 except ImportError:
        import re
 
-
-################################################################
-# lilylib.py -- options and stuff
-# 
-# source file of the GNU LilyPond music typesetter
+# 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.
+try:
+       import resource
+       resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
+except:
+       pass
 
 try:
        import gettext
@@ -96,7 +101,7 @@ except:
 
 program_version = '@TOPLEVEL_VERSION@'
 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
-       program_version = '1.5.17'
+       program_version = '1.5.54'
 
 def identify ():
        sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
@@ -125,8 +130,6 @@ def user_error (s, e=1):
        sys.exit (e)
        
 def error (s):
-
-
        '''Report the error S.  Exit by raising an exception. Please
        do not abuse by trying to catch this error. If you do not want
        a stack trace, write to the output directly.
@@ -223,7 +226,7 @@ def setup_temp ():
        return temp_dir
 
 
-def system (cmd, ignore_error = 0):
+def system (cmd, ignore_error = 0, quiet =0):
        """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
 
        RETURN VALUE
@@ -239,7 +242,8 @@ def system (cmd, ignore_error = 0):
                name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
                msg = name + ': ' + _ ("command exited with value %d") % st
                if ignore_error:
-                       warning (msg + ' ' + _ ("(ignored)") + ' ')
+                       if not quiet:
+                               warning (msg + ' ' + _ ("(ignored)") + ' ')
                else:
                        error (msg)
 
@@ -259,19 +263,41 @@ def strip_extension (f, ext):
                e = ''
        return p + e
 
-################################################################
-# END Library
 
+def cp_to_dir (pattern, dir):
+       "Copy files matching re PATTERN from cwd to DIR"
+       # Duh.  Python style portable: cp *.EXT OUTDIR
+       # system ('cp *.%s %s' % (ext, outdir), 1)
+       files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
+       map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
+
+
+# Python < 1.5.2 compatibility
+#
+# On most platforms, this is equivalent to
+#`normpath(join(os.getcwd()), PATH)'.  *Added in Python version 1.5.2*
+if os.path.__dict__.has_key ('abspath'):
+       abspath = os.path.abspath
+else:
+       def abspath (path):
+               return os.path.normpath (os.path.join (os.getcwd (), path))
 
+if os.__dict__.has_key ('makedirs'):
+       makedirs = os.makedirs
+else:
+       def makedirs (dir, mode=0777):
+               system ('mkdir -p %s' % dir)
 
 
+def mkdir_p (dir, mode=0777):
+       if not os.path.isdir (dir):
+               makedirs (dir, mode)
 
 
 # if set, LILYPONDPREFIX must take prevalence
 # if datadir is not set, we're doing a build and LILYPONDPREFIX 
 datadir = '@datadir@'
 
-
 if os.environ.has_key ('LILYPONDPREFIX') :
        datadir = os.environ['LILYPONDPREFIX']
 else:
@@ -281,6 +307,12 @@ else:
 while datadir[-1] == os.sep:
        datadir= datadir[:-1]
 
+sys.path.insert (0, os.path.join (datadir, 'python'))
+
+################################################################
+# END Library
+
+
 program_name = 'ly2dvi'
 
 original_dir = os.getcwd ()
@@ -289,24 +321,7 @@ errorport = sys.stderr
 keep_temp_dir_p = 0
 verbose_p = 0
 preview_p = 0
-
-try:
-       import gettext
-       gettext.bindtextdomain ('lilypond', '@localedir@')
-       gettext.textdomain ('lilypond')
-       _ = gettext.gettext
-except:
-       def _ (s):
-               return s
-
-# 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.
-try:
-       import resource
-       resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
-except:
-       pass
+preview_resolution = 90
 
 help_summary = _ ("Generate .dvi with LaTeX for LilyPond")
 
@@ -321,6 +336,7 @@ option_definitions = [
        (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
        # why capital P?
        ('', '', 'preview', _("Make a picture of the first system.")),
+       (_ ('RES'), '', 'preview-resolution', _("Set the resolution of the preview to RES.")),
        ('', 'P', 'postscript', _ ("generate PostScript output")),
        (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
        ('', 'V', 'verbose', _ ("verbose")),
@@ -371,7 +387,10 @@ kpse = re.sub('[ \t\n]+$','', kpse)
 type1_paths = os.popen ('kpsewhich -expand-path=\$T1FONTS').read ()
 
 environment = {
-       ## todo: prevent multiple addition.
+       # TODO: * prevent multiple addition.
+       #       * clean TEXINPUTS, MFINPUTS, TFMFONTS,
+       #         as these take prevalence over $TEXMF
+       #         and thus may break tex run?
        'TEXMF' : "{%s,%s}" % (datadir, kpse) ,
        'GS_FONTPATH' : type1_paths,
        'GS_LIB' : datadir + '/ps',
@@ -386,10 +405,9 @@ non_path_environment = {
 
 def setup_environment ():
        # $TEXMF is special, previous value is already taken care of
-       if os.environ.has_key ('TEXM'):
+       if os.environ.has_key ('TEXMF'):
                del os.environ['TEXMF']
  
-
        for key in environment.keys ():
                val = environment[key]
                if os.environ.has_key (key):
@@ -419,12 +437,12 @@ def print_environment ():
        for (k,v) in os.environ.items ():
                sys.stderr.write ("%s=\"%s\"\n" % (k,v)) 
 
-def quiet_system (cmd, name):
+def quiet_system (cmd, name, ignore_error = 0):
        if not verbose_p:
                progress ( _("Running %s...") % name)
                cmd = cmd + ' 1> /dev/null 2> /dev/null'
 
-       return system (cmd)
+       return system (cmd, ignore_error, quiet = 1)
 
 
 def run_lilypond (files, outbase, dep_prefix):
@@ -453,8 +471,22 @@ def run_lilypond (files, outbase, dep_prefix):
 
                # for better debugging!
                print_environment ()
-       print opts, fs  
-       system ('lilypond %s %s ' % (opts, fs), 'lilypond')
+
+       cmd = 'lilypond %s %s ' % (opts, fs)
+       if  verbose_p:
+               progress ("Invoking `%s'"% cmd)
+       status = os.system (cmd)
+
+       signal = 0x0f & status
+       exit_status = status >> 8
+
+       # 2 == user interrupt.
+       if signal <> 2:
+               error("\n\nLilyPond crashed (signal %d). Please submit a bugreport to bug-lilypond@gnu.org\n" % signal)
+
+       if status:
+               error ("\n\nLilyPond failed on the input file. (exit status %d)\n" % exit_status)
+               
 
 def analyse_lilypond_output (filename, extra):
        
@@ -652,8 +684,22 @@ None
        f.close ()
 
        cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
-       quiet_system (cmd, 'LaTeX')
+       status = quiet_system (cmd, 'LaTeX', ignore_error = 1)
+
+       signal = 0xf & status
+       exit_stat = status >> 8
 
+       if exit_stat:
+               logstr = open (outbase + '.log').read()
+               m = re.search ("\n!", logstr)
+               start = m.start (0)
+               logstr = logstr[start:start+200]
+               
+               sys.stderr.write(_("""LaTeX failed on the output file.
+The error log is as follows:
+%s...\n""" % logstr))
+               raise 'LaTeX error'
+       
        if preview_p:
                # make a preview by rendering only the 1st line.
                preview_fn = outbase + '.preview.tex'
@@ -719,14 +765,12 @@ def make_preview (name, extra):
        fo.write ('%d %d translate\n' % (-bbox[0]+margin, -bbox[1]+margin))
        fo.close ()
        
-       res = 90
-
-       x = (2* margin + bbox[2] - bbox[0]) * res / 72.
-       y = (2* margin + bbox[3] - bbox[1]) * res / 72.
+       x = (2* margin + bbox[2] - bbox[0]) * preview_resolution / 72.
+       y = (2* margin + bbox[3] - bbox[1]) * preview_resolution / 72.
 
        cmd = r'''gs -g%dx%d -sDEVICE=pgm  -dTextAlphaBits=4 -dGraphicsAlphaBits=4  -q -sOutputFile=- -r%d -dNOPAUSE %s %s -c quit | pnmtopng > %s'''
        
-       cmd = cmd % (x, y, res, name + '.trans.eps', name + '.preview.ps',name + '.png')
+       cmd = cmd % (x, y, preview_resolution, name + '.trans.eps', name + '.preview.ps',name + '.png')
        quiet_system (cmd, 'gs')
 
        try:
@@ -817,9 +861,9 @@ for opt in options:
        elif o == '--preview':
                preview_p = 1
                targets.append ('PNG')
-               
+       elif o == '--preview-resolution':
+               preview_resolution = string.atoi (a)
        elif o == '--no-paper' or o == '-m':
-
                targets = ['MIDI'] 
                paper_p = 0
        elif o == '--output' or o == '-o':
@@ -841,34 +885,6 @@ for opt in options:
 
                sys.exit (0)
 
-
-def cp_to_dir (pattern, dir):
-       "Copy files matching re PATTERN from cwd to DIR"
-       # Duh.  Python style portable: cp *.EXT OUTDIR
-       # system ('cp *.%s %s' % (ext, outdir), 1)
-       files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
-       map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
-
-# Python < 1.5.2 compatibility
-#
-# On most platforms, this is equivalent to
-#`normpath(join(os.getcwd()), PATH)'.  *Added in Python version 1.5.2*
-if os.path.__dict__.has_key ('abspath'):
-       abspath = os.path.abspath
-else:
-       def abspath (path):
-               return os.path.normpath (os.path.join (os.getcwd (), path))
-
-if os.__dict__.has_key ('makedirs'):
-       makedirs = os.makedirs
-else:
-       def makedirs (dir, mode=0777):
-               system ('mkdir -p %s' % dir)
-
-def mkdir_p (dir, mode=0777):
-       if not os.path.isdir (dir):
-               makedirs (dir, mode)
-
 include_path = map (abspath, include_path)
 
 original_output = output_name