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