]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/mf-to-table.py
(code): remove tex name from fet_beginchar.
[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 class Char_metric:
41         def __init__ (self):
42                 pass
43
44
45 def tfm_checksum (fn):
46         sys.stderr.write ("Reading checksum from `%s'\n" % fn)
47         s = open (fn).read ()
48         s = s[ 12 * 2 : ]
49         cs_bytes = s[:4]
50
51         shift = 24
52         cs = 0
53         for b in cs_bytes:
54                 cs = cs  + (long (ord (b)) << shift)
55                 shift = shift - 8
56
57         return cs
58
59
60 ## ugh.  What's font_family supposed to be?  It's not an afm thing.
61 font_family = 'feta'
62
63 def parse_logfile (fn):
64         (autolines, deps) = read_log_file (fn)
65         charmetrics = []
66         global_info = {}
67         group = ''
68
69         for l in autolines:
70                 tags = string.split (l, '@:')
71                 if tags[0] == 'group':
72                         group = tags[1]
73                 elif tags[0] == 'puorg':
74                         group = ''
75                 elif tags[0] == 'char':
76                         name = tags[9]
77
78                         name = re.sub ('-', 'M', name)
79                         if group:
80                                 name = group + '.' + name
81                         m = {
82                                 'description': tags[1],
83                                 'name': name,
84                                 'code': string.atoi (tags[2]),
85                                 'breapth': string.atof (tags[3]),
86                                 'width': string.atof (tags[4]),
87                                 'depth': string.atof (tags[5]),
88                                 'height': string.atof (tags[6]),
89                                 'wx': string.atof (tags[7]),
90                                 'wy': string.atof (tags[8]),
91                         }
92                         charmetrics.append (m)
93                 elif tags[0] == 'font':
94                         global font_family
95                         font_family = (tags[3])
96                         # To omit 'GNU' (foundry) from font name proper:
97                         # name = tags[2:]
98                         #urg
99                         if 0: # testing
100                                 tags.append ('Regular')
101
102                         encoding = re.sub (' ','-', tags[5])
103                         tags = tags[:-1]
104                         name = tags[1:]
105                         global_info['DesignSize'] = string.atof (tags[4])
106                         global_info['FontName'] = string.join (name,'-')
107                         global_info['FullName'] = string.join (name,' ')
108                         global_info['FamilyName'] = string.join (name[1:-1],
109                                                                  '-')
110                         if 1:
111                                 global_info['Weight'] = tags[4]
112                         else: # testing
113                                 global_info['Weight'] = tags[-1]
114
115                         global_info['FontBBox'] = '0 0 1000 1000'
116                         global_info['Ascender'] = '0'
117                         global_info['Descender'] = '0'
118                         global_info['EncodingScheme'] = encoding
119
120                 elif tags[0] == 'parameter':
121                         global_info[tags[1]] = tags[2];
122                         
123         return (global_info, charmetrics, deps)
124
125
126 def write_afm_char_metric (file, charmetric):
127         f = 1000;
128         tup = (charmetric['code'],
129                charmetric['name'],
130                -charmetric['breapth'] * f,
131                -charmetric['depth'] * f,
132                charmetric['width'] * f,
133                charmetric['height'] * f,
134                charmetric['wx'] * f,
135                charmetric['wy'] * f)
136
137         file.write ('C %d ; N %s ; B %d %d %d %d ; W %d %d ;\n' % tup)
138
139
140 def write_afm_header (file):
141         file.write ("StartFontMetrics 2.0\n")
142         file.write ("Comment Automatically generated by mf-to-table.py\n")
143
144
145 def write_afm_metric (file, global_info, charmetrics):
146         for (k, v) in global_info.items():
147                 file.write ("%s %s\n" % (k, v))
148         file.write ('StartCharMetrics %d\n' % len(charmetrics ))
149         for m in charmetrics:
150                 write_afm_char_metric (file, m)
151         file.write ('EndCharMetrics\n')
152         file.write ('EndFontMetrics\n')
153
154
155 def write_tex_defs (file, global_info, charmetrics):
156         ## nm = global_info['FontFamily']
157         nm = font_family
158         for m in charmetrics:
159                 
160                 texname = re.sub ('[_.]', 'X',  m['name'])
161                 def digit_to_letter (match):
162                         return chr (ord (match.group(1)) - ord ('0') + ord ('A'))
163                 texname = re.sub ('([0-9])', digit_to_letter, texname)
164                 file.write (r'''\gdef\%s%s{\char%d}%%%s''' % \
165                             (nm, texname, m['code'],'\n'))
166         file.write ('\\endinput\n')
167
168
169 def write_character_lisp_table (file, global_info, charmetrics):
170
171         def conv_char_metric (charmetric):
172                 f = 1.0
173                 s = """(%s .
174 ((bbox . (%f %f %f %f))
175  (attachment . (%f . %f))))
176 """ %(charmetric['name'],
177                  -charmetric['breapth'] * f,
178                  -charmetric['depth'] * f,
179                  charmetric['width'] * f,
180                  charmetric['height'] * f,
181                  charmetric['wx'],
182                  charmetric['wy'])
183
184                 return s
185
186         for c in charmetrics:
187                 file.write (conv_char_metric (c))
188
189
190 def write_global_lisp_table (file, global_info):
191         str = ''
192
193         keys = ['staffsize', 'stafflinethickness', 'staff_space',
194                 'linethickness', 'black_notehead_width', 'ledgerlinethickness',
195                 'blot_diameter'
196                 ]
197         for k in keys:
198                 if global_info.has_key (k):
199                         str = str + "(%s . %s)\n" % (k,global_info[k])
200
201         file.write (str)
202
203         
204 def write_ps_encoding (name, file, global_info, charmetrics):
205         encs = ['.notdef'] * 256
206         for m in charmetrics:
207                 encs[m['code']] = m['name']
208
209         file.write ('/%s [\n' % name)
210         for m in range (0, 256):
211                 file.write ('  /%s %% %d\n' % (encs[m], m))
212         file.write ('] def\n')
213
214
215 def write_fontlist (file, global_info, charmetrics):
216         ## nm = global_info['FontFamily']
217         nm = font_family
218         per_line = 2
219         file.write (
220 r"""%% LilyPond file to list all font symbols and the corresponding names
221 %% Automatically generated by mf-to-table.py
222
223 \score {
224   \lyrics { \time %d/8
225 """ % (2 * per_line + 1))
226
227         count = 0
228         for m in charmetrics:
229                 count += 1
230
231                 ## \musicglyph and \markup require "_" to be escaped
232                 ## differently
233                 scm_string = re.sub ('_', r'_', m['name'])
234                 tex_string = re.sub ('_', r'\\_' , m['name'])
235
236                 ## prevent TeX from interpreting "--" as long dash
237                 tex_string = re.sub ('--','-{}-', tex_string)
238
239                 file.write ('''    \\markup { \\raise #0.75 \\vcenter
240               \\musicglyph #"%s"
241               \\typewriter " %s" } 4\n''' % (scm_string, tex_string))
242
243                 if (count % per_line) == 0:
244                         file.write ('    \\skip 8 \\break\n')
245         file.write (r"""  }
246
247   \layout {
248     interscoreline = 1.0
249     indent = 0.0 \cm
250     \context {
251       \Lyrics
252       \override SeparationItem #'padding = #2
253       minimumVerticalExtent = ##f
254     }
255     \context {
256       \Score
257       \remove "Bar_number_engraver"
258     }
259   }
260 }
261 """)
262
263
264 def write_deps (file, deps, targets):
265         for t in targets:
266                 t = re.sub ( '^\\./', '', t)
267                 file.write ('%s '% t)
268         file.write (": ")
269         for d in deps:
270                 file.write ('%s ' % d)
271         file.write ('\n')
272
273
274 def help ():
275         sys.stdout.write(r"""Usage: mf-to-table [OPTIONS] LOGFILEs
276
277 Generate feta metrics table from preparated feta log.
278
279 Options:
280   -a, --afm=FILE         specify .afm file
281   -d, --dep=FILE         print dependency info to FILE
282   -h, --help             print this help
283   -l, --ly=FILE          name output table
284   -o, --outdir=DIR       prefix for dependency info
285   -p, --package=DIR      specify package
286   -t, --tex=FILE         name output tex chardefs
287
288   """)
289         sys.exit (0)
290
291
292 (options, files) = \
293   getopt.getopt (sys.argv[1:],
294                  'a:d:hl:o:p:t:',
295                  ['enc=', 'afm=', 'outdir=', 'dep=', 'lisp=',
296                   'global-lisp=',
297                   'tex=', 'ly=', 'debug', 'help', 'package='])
298
299 global_lisp_nm = ''
300 char_lisp_nm = ''
301 enc_nm = ''
302 texfile_nm = ''
303 depfile_nm = ''
304 afmfile_nm = ''
305 lyfile_nm = ''
306 outdir_prefix = '.'
307
308 for opt in options:
309         o = opt[0]
310         a = opt[1]
311         if o == '--dep' or o == '-d':
312                 depfile_nm = a
313         elif o == '--outdir' or o == '-o':
314                 outdir_prefix = a
315         elif o == '--tex' or o == '-t':
316                 texfile_nm = a
317         elif o == '--lisp': 
318                 char_lisp_nm = a
319         elif o == '--global-lisp': 
320                 global_lisp_nm = a
321         elif o == '--enc':
322                 enc_nm = a
323         elif o == '--ly' or o == '-l':
324                 lyfile_nm = a
325         elif o== '--help' or o == '-h':
326                 help()
327         elif o=='--afm' or o == '-a':
328                 afmfile_nm = a
329         elif o == '--debug':
330                 debug_b = 1
331         else:
332                 print o
333                 raise getopt.error
334
335 base = re.sub ('.tex$', '', texfile_nm)
336
337 for filenm in files:
338         (g, m, deps) = parse_logfile (filenm)
339         cs = tfm_checksum (re.sub ('.log$', '.tfm', filenm))
340         afm = open (afmfile_nm, 'w')
341
342         write_afm_header (afm)
343         afm.write ("Comment TfmCheckSum %d\n" % cs)
344         afm.write ("Comment DesignSize %.2f\n" % g['DesignSize'])
345
346         del g['DesignSize']
347
348         write_afm_metric (afm, g, m)
349
350         write_tex_defs (open (texfile_nm, 'w'), g, m)
351         enc_name = 'FetaEncoding'
352         if re.search ('parmesan', filenm):
353                 enc_name = 'ParmesanEncoding'
354         elif re.search ('feta-brace', filenm):
355                 enc_name = 'FetaBraceEncoding'
356
357         write_ps_encoding (enc_name, open (enc_nm, 'w'), g, m)
358         write_character_lisp_table (open (char_lisp_nm, 'w'), g, m)  
359         write_global_lisp_table (open (global_lisp_nm, 'w'), g)  
360         if depfile_nm:
361                 write_deps (open (depfile_nm, 'wb'), deps,
362                             [base + '.dvi', base + '.pfa', base + '.pfb',
363                              texfile_nm, afmfile_nm])
364         if lyfile_nm:
365                 write_fontlist (open (lyfile_nm, 'w'), g, m)