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