]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/mf-to-table.py
* lily/open-type-font.cc (load_scheme_table): new function
[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                                 'tex': tags[10],
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['DesignSize'] = 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 def write_afm_char_metric (file, charmetric):
128         f = 1000;
129         tup = (charmetric['code'],
130                charmetric['name'],
131                -charmetric['breapth'] * f,
132                -charmetric['depth'] * f,
133                charmetric['width'] * f,
134                charmetric['height'] * f,
135                charmetric['wx'] * f,
136                charmetric['wy'] * f)
137
138         file.write ('C %d ; N %s ; B %d %d %d %d ; W %d %d ;\n' % tup)
139
140
141 def write_afm_header (file):
142         file.write ("StartFontMetrics 2.0\n")
143         file.write ("Comment Automatically generated by mf-to-table.py\n")
144
145
146 def write_afm_metric (file, global_info, charmetrics):
147         for (k, v) in global_info.items():
148                 file.write ("%s %s\n" % (k, v))
149         file.write ('StartCharMetrics %d\n' % len(charmetrics ))
150         for m in charmetrics:
151                 write_afm_char_metric (file, m)
152         file.write ('EndCharMetrics\n')
153         file.write ('EndFontMetrics\n')
154
155
156 def write_tex_defs (file, global_info, charmetrics):
157         ## nm = global_info['FontFamily']
158         nm = font_family
159         for m in charmetrics:
160                 file.write (r'''\gdef\%s%s{\char%d}%%%s''' % \
161                             (nm, m['tex'], m['code'],'\n'))
162         file.write ('\\endinput\n')
163
164
165 def write_character_lisp_table (file, global_info, charmetrics):
166
167         def conv_char_metric (charmetric):
168                 f = 1.0
169                 s = """(%s .
170 ((bbox . (%f %f %f %f))
171  (attachment . (%f . %f))))
172 """ %(charmetric['name'],
173                  -charmetric['breapth'] * f,
174                  -charmetric['depth'] * f,
175                  charmetric['width'] * f,
176                  charmetric['height'] * f,
177                  charmetric['wx'],
178                  charmetric['wy'])
179
180                 return s
181
182         for c in charmetrics:
183                 file.write (conv_char_metric (c))
184
185
186 def write_global_lisp_table (file, global_info):
187         str = ''
188
189         keys = ['staffsize', 'stafflinethickness', 'staff_space',
190                 'linethickness', 'black_notehead_width', 'ledgerlinethickness',
191                 'blot_diameter'
192                 ]
193         for k in keys:
194                 if global_info.has_key (k):
195                         str = str + "(%s . %s)\n" % (k,global_info[k])
196
197         file.write (str)
198
199         
200 def write_ps_encoding (name, file, global_info, charmetrics):
201         encs = ['.notdef'] * 256
202         for m in charmetrics:
203                 encs[m['code']] = m['name']
204
205         file.write ('/%s [\n' % name)
206         for m in range (0, 256):
207                 file.write ('  /%s %% %d\n' % (encs[m], m))
208         file.write ('] def\n')
209
210
211 def write_fontlist (file, global_info, charmetrics):
212         ## nm = global_info['FontFamily']
213         nm = font_family
214         per_line = 2
215         file.write (
216 r"""%% LilyPond file to list all font symbols and the corresponding names
217 %% Automatically generated by mf-to-table.py
218
219 \score {
220   \lyrics { \time %d/8
221 """ % (2 * per_line + 1))
222
223         count = 0
224         for m in charmetrics:
225                 count += 1
226
227                 ## \musicglyph and \markup require "_" to be escaped
228                 ## differently
229                 scm_string = re.sub ('_', r'_', m['name'])
230                 tex_string = re.sub ('_', r'\\_' , m['name'])
231
232                 ## prevent TeX from interpreting "--" as long dash
233                 tex_string = re.sub ('--','-{}-', tex_string)
234
235                 file.write ('''    \\markup { \\raise #0.75 \\vcenter
236               \\musicglyph #"%s"
237               \\typewriter " %s" } 4\n''' % (scm_string, tex_string))
238
239                 if (count % per_line) == 0:
240                         file.write ('    \\skip 8 \\break\n')
241         file.write (r"""  }
242
243   \layout {
244     interscoreline = 1.0
245     indent = 0.0 \cm
246     \context {
247       \Lyrics
248       \override SeparationItem #'padding = #2
249       minimumVerticalExtent = ##f
250     }
251     \context {
252       \Score
253       \remove "Bar_number_engraver"
254     }
255   }
256 }
257 """)
258
259
260 def write_deps (file, deps, targets):
261         for t in targets:
262                 t = re.sub ( '^\\./', '', t)
263                 file.write ('%s '% t)
264         file.write (": ")
265         for d in deps:
266                 file.write ('%s ' % d)
267         file.write ('\n')
268
269
270 def help ():
271         sys.stdout.write(r"""Usage: mf-to-table [OPTIONS] LOGFILEs
272
273 Generate feta metrics table from preparated feta log.
274
275 Options:
276   -a, --afm=FILE         specify .afm file
277   -d, --dep=FILE         print dependency info to FILE
278   -h, --help             print this help
279   -l, --ly=FILE          name output table
280   -o, --outdir=DIR       prefix for dependency info
281   -p, --package=DIR      specify package
282   -t, --tex=FILE         name output tex chardefs
283
284   """)
285         sys.exit (0)
286
287
288 (options, files) = \
289   getopt.getopt (sys.argv[1:],
290                  'a:d:hl:o:p:t:',
291                  ['enc=', 'afm=', 'outdir=', 'dep=', 'lisp=',
292                   'global-lisp=',
293                   'tex=', 'ly=', 'debug', 'help', 'package='])
294
295 global_lisp_nm = ''
296 char_lisp_nm = ''
297 enc_nm = ''
298 texfile_nm = ''
299 depfile_nm = ''
300 afmfile_nm = ''
301 lyfile_nm = ''
302 outdir_prefix = '.'
303
304 for opt in options:
305         o = opt[0]
306         a = opt[1]
307         if o == '--dep' or o == '-d':
308                 depfile_nm = a
309         elif o == '--outdir' or o == '-o':
310                 outdir_prefix = a
311         elif o == '--tex' or o == '-t':
312                 texfile_nm = a
313         elif o == '--lisp': 
314                 char_lisp_nm = a
315         elif o == '--global-lisp': 
316                 global_lisp_nm = a
317         elif o == '--enc':
318                 enc_nm = a
319         elif o == '--ly' or o == '-l':
320                 lyfile_nm = a
321         elif o== '--help' or o == '-h':
322                 help()
323         elif o=='--afm' or o == '-a':
324                 afmfile_nm = a
325         elif o == '--debug':
326                 debug_b = 1
327         else:
328                 print o
329                 raise getopt.error
330
331 base = re.sub ('.tex$', '', texfile_nm)
332
333 for filenm in files:
334         (g, m, deps) = parse_logfile (filenm)
335         cs = tfm_checksum (re.sub ('.log$', '.tfm', filenm))
336         afm = open (afmfile_nm, 'w')
337
338         write_afm_header (afm)
339         afm.write ("Comment TfmCheckSum %d\n" % cs)
340         afm.write ("Comment DesignSize %.2f\n" % g['DesignSize'])
341
342         del g['DesignSize']
343
344         write_afm_metric (afm, g, m)
345
346         write_tex_defs (open (texfile_nm, 'w'), g, m)
347         enc_name = 'FetaEncoding'
348         if re.search ('parmesan', filenm):
349                 enc_name = 'ParmesanEncoding'
350         elif re.search ('feta-brace', filenm):
351                 enc_name = 'FetaBraceEncoding'
352
353         write_ps_encoding (enc_name, open (enc_nm, 'w'), g, m)
354         write_character_lisp_table (open (char_lisp_nm, 'w'), g, m)  
355         write_global_lisp_table (open (global_lisp_nm, 'w'), g)  
356         if depfile_nm:
357                 write_deps (open (depfile_nm, 'wb'), deps,
358                             [base + '.dvi', base + '.pfa', base + '.pfb',
359                              texfile_nm, afmfile_nm])
360         if lyfile_nm:
361                 write_fontlist (open (lyfile_nm, 'w'), g, m)