]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/mf-to-table.py
365dedb02afd1112a7815f5092e7f7f21df3ef1d
[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--2004 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  + (long (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[9],
76                                 'tex': tags[10],
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                                 'wx': string.atof (tags[7]),
83                                 'wy':string.atof (tags[8]),
84                                 }
85                         charmetrics.append (m)
86                 elif tags[0] == 'font':
87                         global font_family
88                         font_family = (tags[3])
89                         # To omit 'GNU' (foundry) from font name proper:
90                         # name = tags[2:]
91                         #urg
92                         if 0: #testing
93                                 tags.append ('Regular')
94
95                         
96                         encoding = re.sub (' ','-', tags[5])
97                         tags = tags[:-1]
98                         name = tags[1:]
99                         global_info['DesignSize'] = string.atof (tags[4])
100                         global_info['FontName'] = string.join (name,'-')
101                         global_info['FullName'] = string.join (name,' ')
102                         global_info['FamilyName'] = string.join (name[1:-1],
103                                                                  '-')
104                         if 1:
105                                 global_info['Weight'] = tags[4]
106                         else: #testing
107                                 global_info['Weight'] = tags[-1]
108                                 
109                         global_info['FontBBox'] = '0 0 1000 1000'
110                         global_info['Ascender'] = '0'
111                         global_info['Descender'] = '0'
112                         global_info['EncodingScheme'] = encoding
113         
114         return (global_info, charmetrics, deps)
115
116
117 def write_afm_char_metric(file, charmetric):
118
119         f = 1000;
120         tup = (charmetric['code'],
121                 charmetric['name'],
122                 -charmetric['breapth'] *f,
123                 -charmetric['depth']*f,
124                 charmetric['width']*f,
125                 charmetric['height']*f,
126                charmetric['wx'] * f,
127                charmetric['wy'] * f)
128         
129         file.write ('C %d ; N %s ; B %d %d %d %d ; W %d %d ;\n'% tup)
130
131 def write_afm_header (file):
132         file.write ("StartFontMetrics 2.0\n")
133         file.write ("Comment Automatically generated by mf-to-table.py\n")
134
135 def write_afm_metric (file, global_info, charmetrics):
136         for (k,v) in global_info.items():
137                 file.write ("%s %s\n" % (k,v))
138         file.write ('StartCharMetrics %d\n' % len(charmetrics ))
139         for m in charmetrics:
140                 write_afm_char_metric (file,m)
141         file.write ('EndCharMetrics\n')
142         file.write ('EndFontMetrics\n')
143
144
145 def write_tex_defs (file, global_info, charmetrics):
146         ##nm = global_info['FontFamily']
147         nm = font_family
148         for m in charmetrics:
149                 file.write (r'''\gdef\%s%s{\char%d}%%%s''' % (nm, m['tex'], m['code'],'\n'))
150         file.write ('\\endinput\n')
151
152 def write_ps_encoding (name, file, global_info, charmetrics):
153         encs = ['.notdef'] * 256
154         for m in charmetrics:
155                 encs[m['code']] = m['tex']
156
157         file.write ('/%s [\n' % name)
158         for m in range(0,256):
159                 file.write ('  /%s %% %d\n' % (encs[m], m))
160         file.write ('] def\n')
161         
162 def write_fontlist (file, global_info, charmetrics):
163         ##nm = global_info['FontFamily']
164         nm = font_family
165         per_line = 3
166         file.write (r"""
167 %% LilyPond file to list all font symbols and the corresponding names
168 %% Automatically generated by mf-to-table.py
169 \score{ \lyrics \new Lyrics { \time %d/8
170 """ % (2*per_line+1))
171
172         count = 0
173         for m in charmetrics:
174
175                 count += 1
176                 
177 ## \musicglyph and \markup require "_" to be escaped differently:
178                 
179
180                 scm_string = re.sub('_', r'_', m['name'])
181                 tex_string = re.sub ('_', r'\\_' , m['name'])
182                 
183 ## prevent TeX from interpreting "--" as long dash:
184                 tex_string=re.sub('--','-{}-', tex_string)
185
186                 file.write ('  \\markup { \\raise #0.75 \\vcenter \\musicglyph #"%s" " %s" } 4 \n' % (scm_string, tex_string))
187
188                 if (count % 3) ==0:
189                         file.write ('\skip 8  \\break\n')
190         file.write (r"""
191 }
192   \paper{
193     interscoreline = 1.0
194     indent = 0.0 \cm
195     \context {
196       \LyricsContext
197       \override SeparationItem #'padding = #2
198       minimumVerticalExtent = ##f
199     }
200     \context {
201         \ScoreContext
202         \remove "Bar_number_engraver"
203         }
204         }
205         }
206 """)
207
208 def write_deps (file, deps, targets):
209         
210         
211         for t in targets:
212                 t = re.sub ( '^\\./', '', t)
213                 file.write ('%s '% t)
214         file.write (": ")
215         for d in deps:
216                 file.write ('%s ' % d)
217         file.write ('\n')
218
219 def help():
220     sys.stdout.write(r"""Usage: mf-to-table [OPTIONS] LOGFILEs
221 Generate feta metrics table from preparated feta log.
222
223 Options:
224   -a, --afm=FILE         specify .afm file
225   -d, --dep=FILE         print dependency info to FILE
226   -h, --help             print this help
227   -l, --ly=FILE          name output table
228   -o, --outdir=DIR       prefix for dependency info
229   -p, --package=DIR      specify package
230   -t, --tex=FILE         name output tex chardefs
231
232   """
233 )
234     sys.exit (0)
235
236
237
238 (options, files) = getopt.getopt(
239     sys.argv[1:], 'a:d:hl:o:p:t:', 
240     ['enc=', 'afm=', 'outdir=', 'dep=',  'tex=', 'ly=', 'debug', 'help', 'package='])
241
242
243 enc_nm = ''
244 texfile_nm = ''
245 depfile_nm = ''
246 afmfile_nm = ''
247 lyfile_nm = ''
248 outdir_prefix = '.'
249
250 for opt in options:
251         o = opt[0]
252         a = opt[1]
253         if o == '--dep' or o == '-d':
254                 depfile_nm = a
255         elif o == '--outdir' or o == '-o':
256                 outdir_prefix = a
257         elif o == '--tex' or o == '-t':
258                 texfile_nm = a
259         elif o == '--enc':
260                 enc_nm = a
261         elif o == '--ly' or o == '-':
262                 lyfile_nm = a
263         elif o== '--help' or o == '-h':
264                 help()
265         elif o=='--afm' or o == '-a':
266                 afmfile_nm = a
267         elif o == '--debug':
268                 debug_b = 1
269         elif o == '-p' or o == '--package':
270                 topdir = a
271         else:
272                 print o
273                 raise getopt.error
274
275 base = re.sub ('.tex$', '', texfile_nm)
276
277 for filenm in files:
278         (g,m, deps) =  parse_logfile (filenm)
279         cs = tfm_checksum (re.sub ('.log$', '.tfm', filenm))
280         afm = open (afmfile_nm, 'w')
281
282         write_afm_header (afm)
283         afm.write ("Comment TfmCheckSum %d\n" % cs)
284         afm.write ("Comment DesignSize %.2f\n" % g['DesignSize'])
285
286         del g['DesignSize']
287         
288         write_afm_metric (afm, g, m)
289         
290         write_tex_defs (open (texfile_nm, 'w'), g, m)
291         enc_name = 'FetaEncoding'
292         if re.search ('parmesan', filenm) :
293                 enc_name = 'ParmesanEncoding'
294         elif re.search ('feta-brace', filenm) :
295                 enc_name = 'FetaBraceEncoding'
296
297                 
298         write_ps_encoding (enc_name, open (enc_nm, 'w'), g, m)
299
300         write_deps (open (depfile_nm, 'wb'), deps, [base + '.dvi', base + '.pfa', base + '.pfb',  texfile_nm, afmfile_nm])
301         if lyfile_nm != '':
302                 write_fontlist(open (lyfile_nm, 'w'), g, m)
303
304
305