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