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