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