]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/mf-to-table.py
release: 1.1.47
[lilypond.git] / buildscripts / mf-to-table.py
1 #!@PYTHON@
2
3 # mf-to-table.py -- convert spacing info in  MF logs .afm and .tex
4
5 # source file of the GNU LilyPond music typesetter
6
7 # (c) 1997 Han-Wen Nienhuys <hanwen@cs.uu.nl>
8
9
10 #
11 # TODO: Should use RE.
12 #
13
14 import os
15 import sys
16 import getopt
17 from string import *
18 import regex
19 import regsub
20 import time
21
22
23 (options, files) = getopt.getopt(
24     sys.argv[1:], 'a:d:hl:o:p:t:', 
25     ['afm=', 'outdir=', 'dep=',  'tex=', 'debug', 'help', 'package='])
26
27 for opt in options:
28     o = opt[0]
29     a = opt[1]
30     if o == '-p' or o == '--package':
31         topdir = a
32
33 sys.path.append (topdir + '/stepmake/bin')
34 from packagepython import *
35 package = Package (topdir)
36 packager = Packager ()
37
38 from packagepython import *
39 from flower import *
40
41 begin_autometric_re = regex.compile('@{')
42 end_autometric_re = regex.compile('@}')
43 include_re = regex.compile ('(\([a-zA-Z_0-9-]+\.mf\)')
44 autometric_re = regex.compile('@{\(.*\)@}')
45 version = '0.7'
46 postfixes = ['log', 'dvi', '2602gf', 'tfm']
47
48 class Feta_file(File):
49     """Read Feta metrics from a metafont log-file."""
50
51     def include_scan (self, line):
52         include_pos =  include_re.search (line)
53         while include_pos <> -1:
54             self.dependencies.append (include_re.group (1))
55
56             line = line[include_pos + 1:]
57             include_pos =  include_re.search (line)
58
59     def read_autometricline(self):
60         line = ''
61         while end_autometric_re.search(line) == -1 and not self.eof():
62             suf = File.readline(self)
63             self.include_scan (suf)
64             if begin_autometric_re.search(line) == -1:
65                 line = ''
66             line = line + regsub.sub('\n','', suf)
67             line = regsub.sub('\r','', line)
68
69         if self.eof():
70            return ''
71
72         return line;
73     def readline(self):
74         """return what is enclosed in one @{ @} pair"""
75         line = '';
76         while autometric_re.search(line) == -1 and not self.eof():
77             line = self.read_autometricline()
78
79         if self.eof():
80             return '';
81
82         return autometric_re.group(1);
83     def __init__(self, nm):
84         File.__init__(self, nm)
85         self.dependencies = []
86     def do_file(infile_nm):
87         infile = readline();
88
89 #
90 # FIXME: should parse output for {} to do indenting.
91 #
92 class Indentable_file(File):
93     """Output file with support for indentation"""
94     def __init__(self,nm, mode):
95         File.__init__(self,nm,mode)
96         self.current_indent_ = 0
97         self.delta_indent_ = 4
98     def writeline (self, str):
99         File.write(self, str)
100     def writeeol(self):
101         File.write(self, '\n')
102         File.write(self, ' '* self.current_indent_)
103
104     def indent(self):
105         self.current_indent_ = self.delta_indent_ + self.current_indent_;
106     def dedent(self):
107         self.current_indent_ = self.current_indent_ - self.delta_indent_;
108         if self.current_indent_ < 0:
109             raise 'Nesting!'
110
111     def write(self, str):
112         lines = split(str, '\n')
113         for l in lines[:-1]:
114             self.writeline(l)
115             self.writeeol()
116         self.writeline (lines[-1])
117
118 class Afm_file (File):
119     def print_f_dimen(self, f):
120         f = f * 1000 / self.fontsize
121     
122         dimstr = '%.2f' % f
123
124         # try to mask rounding errors
125         if (dimstr == '-0.00'):
126                 dimstr = '0.00'
127         self.write( dimstr  +' ');
128
129     def neg_print_dimen(self, str):
130         self.print_f_dimen(-atof(str))
131     def print_dimen(self, str):
132         self.print_f_dimen(atof(str))
133     def def_symbol (self, code, lily_id, tex_id, xdim, ydim):
134         self.write ('C %s; N %s-%s; B ' % (code, self.groupname, lily_id))
135
136         self.neg_print_dimen(xdim [0])
137         self.neg_print_dimen(ydim [0])
138         self.print_dimen(xdim [1])
139         self.print_dimen(ydim [1])
140
141         self.write (';\n');
142         
143     def start (self,nm):
144         self.write ('Start%s\n' % nm)
145     def end (self,nm):
146         self.write ('End%s\n' % nm)
147
148         
149 class Log_reader:
150     """Read logs, destill info, and put into output files"""
151     def output_label(self, line):
152
153         if not line:
154             return;
155         tags = split(line, '@:')
156         label = tags[0]
157         name = tags[1]
158         afm = self.afmfile
159         if tags[0] == 'font':
160             self.texfile.write("% name\n")
161
162             afm.write ('FontName %s\n' % name)
163             afm.start ('FontMetrics')
164             afm.start ('CharMetrics')       
165             afm.fontsize = atof(tags[2])
166         elif label == "group":
167             self.texfile.write("% " + name + "\n")
168             afm.groupname = name
169         elif label == "puorg":
170             self.texfile.write("\n")
171         elif label == "tnof":
172             afm.end ('CharMetrics')
173             afm.end('FontMetrics');
174         elif label == "char":
175             code = tags[2]
176             id = tags [7]
177             texstr = tags [8]
178             xdim = tags[3:5]
179             ydim = tags[5:7]
180             
181             self.texfile.write("\\fetdef\\%s{%s}\n" % (texstr, code))
182             afm.def_symbol (code, id, texstr, xdim, ydim)
183         else:
184             raise 'unknown label: ' + label
185
186     def writedeps (self, deps):
187         if not len (deps):
188             sys.stderr.write  ('Huh, no main target??')
189             return
190         filename = deps[0]
191         split = os.path.splitext(filename)      
192         basename=split[0];
193
194         targets =  map (lambda x,y = basename, z = self.outdir: z + '/' + y + '.' + x, postfixes)
195         depstring = reduce(lambda x,y: x + ' ' + y, deps) 
196         dependencies = map (lambda x, y=depstring: x + ': ' + y, targets)
197         for x in dependencies: 
198             self.depfile.write (x + '\n')
199         
200     def do_file(self,filenm):
201         self.texfile.write ('\n% input from ' + filenm + '\n')
202         feta = Feta_file(filenm)
203         while not feta.eof():
204             line = feta.readline()
205             self.output_label(line)
206         feta.close()
207         
208         self.writedeps (feta.dependencies)
209
210     def __init__(self,  texfile_nm, depfile_nm, afmfile_nm):        
211         self.texfile = Indentable_file(texfile_nm, 'w')
212         self.depfile = File (depfile_nm, 'w')
213         self.afmfile = Afm_file (afmfile_nm, 'w')
214         headerstr = '%% Creator: %s\n%% Automatically generated on\n%% Do not edit' % \
215                    (program_id() )
216
217         self.texfile.write(headerstr)
218         self.depfile.write ('# automatically generated by %s\n' % program_id ())
219
220     def close(self):
221         self.texfile.close()
222         self.depfile.close ()
223
224     def __del__(self):
225         self.close()
226
227 def today_str():
228     return time.asctime(time.localtime(time.time()))
229         
230 def program_id():
231     return 'mf-to-table.py version ' + version;
232
233 def identify():
234     sys.stdout.write(program_id() + '\n')
235     
236 def help():
237     sys.stdout.write("Usage: mf-to-table [options] LOGFILEs\n"
238                  + "Generate mozarella metrics table from preparated feta log\n\n"
239                  + "Options:\n"
240                  + "  -a, --afm=FILE         .afm file\n"
241                  + "  -d, --dep=FILE         print dependency info to FILE\n"
242                  + "  -h, --help             print this help\n"
243                  + "  -l, --ly=FILE          name output table\n"
244                  + "  -o, --outdir=DIR       prefix for dependency info\n"
245                  + "  -p, --package=DIR      specify package\n"
246                  + "  -t, --tex=FILE         name output tex chardefs\n"
247                      )
248     sys.exit (0)
249
250
251 def main():
252     identify()
253
254     texfile_nm = '';
255     depfile_nm = ''
256     afmfile_nm = ''
257     outdir_prefix = '.'
258     for opt in options:
259         o = opt[0]
260         a = opt[1]
261         if o == '--dep' or o == '-d':
262             depfile_nm = a
263         elif o == '--outdir' or o == '-o':
264             outdir_prefix = a
265         elif o == '--tex' or o == '-t':
266             texfile_nm = a
267         elif o== '--help' or o == '-h':
268             help()
269         elif o=='--afm' or o == '-a':
270             afmfile_nm = a
271         elif o == '--debug':
272             debug_b = 1
273         elif o == '-p' or o == '--package':
274             topdir = a
275         else:
276             print o
277             raise getopt.error
278
279     log_reader = Log_reader( texfile_nm, depfile_nm, afmfile_nm)
280     log_reader.outdir = outdir_prefix
281     for filenm in files:
282         log_reader.do_file(filenm)
283     log_reader.close()
284
285
286 main()