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