]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/mf-to-table.py
e2e5e4579f95e3ffb1e6697b4fb17b41cb9bc2be
[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 import os
10 import sys
11 import getopt
12 import string
13 import re
14 import time
15
16
17 postfixes = ['log', 'dvi', '2602gf', 'tfm']
18
19 def read_log_file (fn):
20         str = open (fn).read ()
21         str = re.sub ('\n', '', str)    
22         str = re.sub ('[\t ]+', ' ', str) 
23
24         deps = []
25         autolines = []
26         def include_func (match, d = deps):
27                 d.append (match.group (1))
28                 return ''
29
30         def auto_func (match, a = autolines):
31                 a.append (match.group (1))
32                 return ''
33
34         str = re.sub ('\(([a-zA-Z_0-9-]+\.mf)', include_func, str)
35         str = re.sub ('@{(.*?)@}', auto_func, str)
36
37         return (autolines, deps)
38
39
40
41 class Char_metric:
42         def __init__ (self):
43                 pass
44
45
46 def tfm_checksum (fn):
47         sys.stderr.write ("Reading checksum from `%s'\n" % fn) 
48         s = open (fn).read ()
49         s = s[ 12 * 2 : ]
50         cs_bytes = s[:4]
51
52         shift = 24
53         cs = 0
54         for b in cs_bytes:
55                 cs = cs  + (ord (b) << shift)
56                 shift = shift - 8
57
58         return cs
59
60 ## ugh.  What's font_family supposed to be?  It's not an afm thing.
61 font_family = 'feta'
62 def parse_logfile (fn):
63         (autolines, deps) = read_log_file (fn)
64         charmetrics = []
65         global_info = {}
66         group = ''
67
68         for l in autolines:
69                 tags = string.split(l, '@:')
70                 if tags[0] == 'group':
71                         group = tags[1]
72                 elif tags[0] == 'char':
73                         m = {
74                                 'description':  tags[1],
75                                 'name': group + '-' + tags[7],
76                                 'tex': tags[8],
77                                 'code': string.atoi (tags[2]),
78                                 'breapth':string.atof (tags[3]),
79                                 'width': string.atof (tags[4]),
80                                 'depth':string.atof (tags[5]),
81                                 'height':string.atof (tags[6])
82                                 }
83                         charmetrics.append (m)
84                 elif tags[0] == 'font':
85                         global font_family
86                         font_family = (tags[3])
87                         # To omit 'GNU' (foundry) from font name proper:
88                         # name = tags[2:]
89                         #urg
90                         if 0: #testing
91                                 tags.append ('Regular')
92                         name = tags[1:]
93                         global_info['FontName'] = string.join (name,'-')
94                         global_info['FullName'] = string.join (name,' ')
95                         global_info['FamilyName'] = string.join (name[1:-1],
96                                                                  '-')
97                         if 1:
98                                 global_info['Weight'] = tags[4]
99                         else: #testing
100                                 global_info['Weight'] = tags[-1]
101                         global_info['FontBBox'] = '0 0 1000 1000'
102                         global_info['Ascender'] = '0'
103                         global_info['Descender'] = '0'
104                         global_info['EncodingScheme'] = 'FontSpecific'
105         
106         return (global_info, charmetrics, deps)
107
108
109 def write_afm_char_metric(file, charmetric):
110
111         f = 1000;
112         tup = (charmetric['code'],
113                (charmetric['width'] + charmetric['breapth'])*f,
114                 charmetric['name'],
115                 -charmetric['breapth'] *f,
116                 -charmetric['depth']*f,
117                 charmetric['width']*f,
118                 charmetric['height']*f)
119         
120         
121         file.write ('C %d ; WX %d ; N  %s ;  B %d %d %d %d ;\n'% tup)
122
123 def write_afm_header (file):
124         file.write ("StartFontMetrics 2.0\n")
125         file.write ("Comment Automatically generated by mf-to-table.py\n")
126
127 def write_afm_metric (file, global_info, charmetrics):
128         for (k,v) in global_info.items():
129                 file.write ("%s %s\n" % (k,v))
130         file.write ('StartCharMetrics %d\n' % len(charmetrics ))
131         for m in charmetrics:
132                 write_afm_char_metric (file,m)
133         file.write ('EndCharMetrics\n')
134         file.write ('EndFontMetrics\n')
135
136
137 def write_tex_defs (file, global_info, charmetrics):
138         ##nm = global_info['FontFamily']
139         nm = font_family
140         for m in charmetrics:
141                 file.write (r'''\gdef\%s%s{\char%d}%%%s''' % (nm, m['tex'], m['code'],'\n'))
142         file.write ('\\endinput\n')
143
144 def write_ps_encoding (file, global_info, charmetrics):
145         encs = ['.notdef'] * 256
146         for m in charmetrics:
147                 encs[m['code']] = m['tex']
148                 
149         file.write ('/FetaEncoding [\n')
150         for m in range(0,256):
151                 file.write ('  /%s %% %d\n' % (encs[m], m))
152         file.write ('] def\n')
153         
154 def write_fontlist (file, global_info, charmetrics):
155         ##nm = global_info['FontFamily']
156         nm = font_family
157         file.write (r"""
158 % Lilypond file to list all font symbols and the corresponding names
159 % Automatically generated by mf-to-table.py
160 \score{\notes{\fatText
161 """)
162         for m in charmetrics:
163
164 ## \musicglyph and \markup require "_" to be escaped differently:
165                 musicglyphname=re.sub('_','\\\\_', m['name'])
166                 markupname=re.sub('_','\\\\_', musicglyphname)
167
168 ## prevent TeX from interpreting "--" as long dash:
169                 markupname=re.sub('--','-{}-', markupname)
170
171                 file.write ('  s^\\markup { \\musicglyph #"%s" "%s" }\n' % (musicglyphname, markupname))
172         file.write (r"""
173 }
174   \paper{
175     interscoreline=1
176     \translator{
177       \ScoreContext
178       \remove "Bar_number_engraver"
179       TextScript \override #'extra-X-extent = #'(-1 . 1)
180     }
181     \translator{
182       \StaffContext
183       \remove "Clef_engraver"
184       \remove "Key_engraver"
185       \remove "Time_signature_engraver"
186       \remove "Staff_symbol_engraver"
187       minimumVerticalExtent = ##f
188     }
189   }
190 }
191 """)
192
193 def write_deps (file, deps, targets):
194         
195         
196         for t in targets:
197                 t = re.sub ( '^\\./', '', t)
198                 file.write ('%s '% t)
199         file.write (": ")
200         for d in deps:
201                 file.write ('%s ' % d)
202         file.write ('\n')
203
204 def help():
205     sys.stdout.write(r"""Usage: mf-to-table [options] LOGFILEs
206 Generate feta metrics table from preparated feta log\n
207 Options:
208   -a, --afm=FILE         .afm file
209   -d, --dep=FILE         print dependency info to FILE
210   -h, --help             print this help
211   -l, --ly=FILE          name output table
212   -o, --outdir=DIR       prefix for dependency info
213   -p, --package=DIR      specify package
214   -t, --tex=FILE         name output tex chardefs"""
215 )
216     sys.exit (0)
217
218
219
220 (options, files) = getopt.getopt(
221     sys.argv[1:], 'a:d:hl:o:p:t:', 
222     ['enc=', 'afm=', 'outdir=', 'dep=',  'tex=', 'ly=', 'debug', 'help', 'package='])
223
224
225 enc_nm = ''
226 texfile_nm = ''
227 depfile_nm = ''
228 afmfile_nm = ''
229 lyfile_nm = ''
230 outdir_prefix = '.'
231
232 for opt in options:
233         o = opt[0]
234         a = opt[1]
235         if o == '--dep' or o == '-d':
236                 depfile_nm = a
237         elif o == '--outdir' or o == '-o':
238                 outdir_prefix = a
239         elif o == '--tex' or o == '-t':
240                 texfile_nm = a
241         elif o == '--enc':
242                 enc_nm = a
243         elif o == '--ly' or o == '-':
244                 lyfile_nm = a
245         elif o== '--help' or o == '-h':
246                 help()
247         elif o=='--afm' or o == '-a':
248                 afmfile_nm = a
249         elif o == '--debug':
250                 debug_b = 1
251         elif o == '-p' or o == '--package':
252                 topdir = a
253         else:
254                 print o
255                 raise getopt.error
256
257 base = re.sub ('.tex$', '', texfile_nm)
258
259 for filenm in files:
260         (g,m, deps) =  parse_logfile (filenm)
261         cs = tfm_checksum (re.sub ('.log$', '.tfm', filenm))
262         afm = open (afmfile_nm, 'w')
263
264         write_afm_header (afm)
265         afm.write ("Comment TfmCheckSum %u\n" % cs)
266         write_afm_metric (afm, g, m)
267         
268         write_tex_defs (open (texfile_nm, 'w'), g, m)
269         write_ps_encoding (open (enc_nm, 'w'), g, m)
270
271         write_deps (open (depfile_nm, 'wb'), deps, [base + '.dvi', base + '.pfa', base + '.pfb',  texfile_nm, afmfile_nm])
272         if lyfile_nm != '':
273                 write_fontlist(open (lyfile_nm, 'w'), g, m)
274
275
276