-
Notifications
You must be signed in to change notification settings - Fork 7
/
mftrace.py
executable file
·1424 lines (1143 loc) · 40.8 KB
/
mftrace.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!@PYTHON@
#
# this file is part of mftrace - a tool to generate scalable fonts from MF sources
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# Copyright (c) 2001--2006 by
# Han-Wen Nienhuys, Jan Nieuwenhuizen
import os
import optparse
import sys
import re
import tempfile
import shutil
prefix = '@prefix@'
bindir = '@bindir@'
datadir = '@datadir@'
localedir = datadir + '/locale'
libdir = '@libdir@'
exec_prefix = '@exec_prefix@'
def interpolate (strng):
strng = strng.replace ('{', '(')
strng = strng.replace ('}', ')s')
strng = strng.replace ('$', '%')
return strng
if prefix != '@' + 'prefix@':
exec_prefix = interpolate (exec_prefix) % vars ()
bindir = interpolate (bindir) % vars ()
datadir = os.path.join (interpolate (datadir) % vars (), 'mftrace')
libdir = interpolate (libdir) % vars ()
if datadir == '@' + "datadir" + "@":
datadir = os.getcwd ()
bindir = os.getcwd ()
sys.path.append (datadir)
import afm
import tfm
errorport = sys.stderr
################################################################
# lilylib.py -- options and stuff
#
# source file of the GNU LilyPond music typesetter
try:
import gettext
gettext.bindtextdomain ('mftrace', localedir)
gettext.textdomain ('mftrace')
_ = gettext.gettext
except:
def _ (s):
return s
def shell_escape_filename (strng):
strng = re.sub ('([\'" ])', r'\\\1', strng)
return strng
def identify (port):
port.write ('%s %s\n' % (program_name, program_version))
def warranty ():
identify (sys.stdout)
sys.stdout.write ('\n')
sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001--2004'))
sys.stdout.write ('\n')
sys.stdout.write (' Han-Wen Nienhuys')
sys.stdout.write (' Jan Nieuwenhuizen')
sys.stdout.write ('\n')
sys.stdout.write (_ (r'''
Distributed under terms of the GNU General Public License. It comes with
NO WARRANTY.'''))
sys.stdout.write ('\n')
def progress (s):
errorport.write (s)
def warning (s):
errorport.write (_ ("warning: ") + s)
def error (s):
'''Report the error S and exit with an error status of 1.
RETURN VALUE
None
'''
errorport.write (_ ("error: ") + s + '\n')
errorport.write (_ ("Exiting ...") + '\n')
sys.exit(1)
temp_dir = None
class TempDirectory:
def __init__ (self, name=None):
import tempfile
if name:
if not os.path.isdir (name):
os.makedirs (name)
self.dir = name
else:
self.dir = tempfile.mkdtemp ()
os.chdir (self.dir)
def clean (self):
import shutil
shutil.rmtree (self.dir)
def __del__ (self):
self.clean ()
def __call__ (self):
return self.dir
def __repr__ (self):
return self.dir
def __str__ (self):
return self.dir
def setup_temp (name):
global temp_dir
if not temp_dir:
temp_dir = TempDirectory (name)
else:
os.chdir(temp_dir ())
return temp_dir ()
def popen (cmd, mode = 'r', ignore_error = 0):
if options.verbose:
progress (_ ("Opening pipe `%s\'") % cmd)
pipe = os.popen (cmd, mode)
if options.verbose:
progress ('\n')
return pipe
def system (cmd, ignore_error = 0):
"""Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
RETURN VALUE
Exit status of CMD
"""
if options.verbose:
progress (_ ("Invoking `%s\'\n") % cmd)
st = os.system (cmd)
if st:
name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
msg = name + ': ' + _ ("command exited with value %d") % st
if ignore_error:
warning (msg + ' ' + _ ("(ignored)") + ' ')
else:
error (msg)
if options.verbose:
progress ('\n')
return st
def strip_extension (f, ext):
(p, e) = os.path.splitext (f)
if e == ext:
e = ''
return p + e
################################################################
# END Library
options = None
exit_value = 0
backend_options = ''
program_name = 'mftrace'
temp_dir = None
program_version = '@VERSION@'
origdir = os.getcwd ()
coding_dict = {
# from TeTeX
'TeX typewriter text': '09fbbfac.enc', # cmtt10
'TeX math symbols': '10037936.enc', # cmbsy
'ASCII caps and digits': '1b6d048e', # cminch
'TeX math italic': 'aae443f0.enc', # cmmi10
'TeX extended ASCII': 'd9b29452.enc',
'TeX text': 'f7b6d320.enc',
'TeX text without f-ligatures': '0ef0afca.enc',
'Extended TeX Font Encoding - Latin': 'tex256.enc',
# LilyPond.
'fetaBraces': 'feta-braces-a.enc',
'fetaNumber': 'feta-nummer10.enc',
'fetaMusic': 'feta20.enc',
'parmesanMusic': 'parmesan20.enc',
}
def find_file (nm):
for d in include_dirs:
p = os.path.join (d, nm)
try:
open (p)
return os.path.abspath (p)
except IOError:
pass
p = popen ('kpsewhich %s' % shell_escape_filename (nm)).read ()
p = p.strip ()
if options.dos_kpath:
orig = p
p = p.lower ()
p = re.sub ('^([a-z]):', '/cygdrive/\\1', p)
p = re.sub ('\\\\', '/', p)
sys.stderr.write ("Got `%s' from kpsewhich, using `%s'\n" % (orig, p))
return p
def flag_error ():
global exit_value
exit_value = 1
################################################################
# TRACING.
################################################################
def autotrace_command (fn, opts):
opts = " " + opts + " --background-color=FFFFFF --output-format=eps --input-format=pbm "
return options.trace_binary + opts + backend_options \
+ " --output-file=char.eps %s " % fn
def potrace_command (fn, opts):
return options.trace_binary + opts \
+ ' -u %d ' % options.grid_scale \
+ backend_options \
+ " -q -c --eps --output=char.eps %s " % (fn)
trace_command = None
path_to_type1_ops = None
def trace_one (pbmfile, id):
"""
Run tracer, do error handling
"""
status = system (trace_command (pbmfile, ''), 1)
if status == 2:
sys.stderr.write ("\nUser interrupt. Exiting\n")
sys.exit (2)
if status == 0 and options.keep_temp_dir:
shutil.copy2 (pbmfile, '%s.pbm' % id)
shutil.copy2 ('char.eps', '%s.eps' % id)
if status != 0:
error_file = os.path.join (origdir, 'trace-bug-%s.pbm' % id)
shutil.copy2 (pbmfile, error_file)
msg = """Trace failed on bitmap. Bitmap left in `%s\'
Failed command was:
%s
Please submit a bugreport to %s development.""" \
% (error_file, trace_command (error_file, ''), options.trace_binary)
if options.keep_trying:
warning (msg)
sys.stderr.write ("\nContinuing trace...\n")
flag_error ()
else:
msg = msg + '\nRun mftrace with --keep-trying to produce a font anyway\n'
error (msg)
else:
return 1
if status != 0:
warning ("Failed, skipping character.\n")
return 0
else:
return 1
def make_pbm (filename, outname, char_number):
""" Extract bitmap from the PK file FILENAME (absolute) using `gf2pbm'.
Return FALSE if the glyph is not valid.
"""
command = "%s/gf2pbm -n %d -o %s %s" % (bindir, char_number, outname, filename)
status = system (command, ignore_error = 1)
return (status == 0)
def read_encoding (file):
sys.stderr.write (_ ("Using encoding file: `%s'\n") % file)
strng = open (file).read ()
strng = re.sub ("%.*", '', strng)
strng = re.sub ("[\n\t \f]+", ' ', strng)
m = re.search ('/([^ ]+) \[([^\]]+)\] def', strng)
if not m:
error ("Encoding file is invalid")
name = m.group (1)
cod = m.group (2)
cod = re.sub ('[ /]+', ' ', cod)
cods = cod.split ()
return (name, cods)
def zip_to_pairs (xs):
r = []
while xs:
r.append ((xs[0], xs[1]))
xs = xs[2:]
return r
def unzip_pairs (tups):
lst = []
while tups:
lst = lst + list (tups[0])
tups = tups[1:]
return lst
def autotrace_path_to_type1_ops (at_file, bitmap_metrics, tfm_wid, magnification):
inv_scale = 1000.0 / magnification
(size_y, size_x, off_x, off_y) = list(map (lambda m, s = inv_scale: m * s,
bitmap_metrics))
ls = open (at_file).readlines ()
bbox = (10000, 10000, -10000, -10000)
while ls and ls[0] != '*u\n':
ls = ls[1:]
if ls == []:
return (bbox, '')
ls = ls[1:]
commands = []
while ls[0] != '*U\n':
ell = ls[0]
ls = ls[1:]
toks = ell.split ()
if len (toks) < 1:
continue
cmd = toks[-1]
args = list(map (lambda m, s = inv_scale: s * float (m),
toks[:-1]))
if options.round_to_int:
args = zip_to_pairs (list(map (round, args)))
else:
args = zip_to_pairs (args)
commands.append ((cmd, args))
expand = {
'l': 'rlineto',
'm': 'rmoveto',
'c': 'rrcurveto',
'f': 'closepath',
}
cx = 0
cy = size_y - off_y - inv_scale
# t1asm seems to fuck up when using sbw. Oh well.
t1_outline = ' %d %d hsbw\n' % (- off_x, tfm_wid)
bbox = (10000, 10000, -10000, -10000)
for (c, args) in commands:
na = []
for a in args:
(nx, ny) = a
if c == 'l' or c == 'c':
bbox = update_bbox_with_point (bbox, a)
na.append ((nx - cx, ny - cy))
(cx, cy) = (nx, ny)
a = na
c = expand[c]
if options.round_to_int:
a = ['%d' % int (round (x)) for x in unzip_pairs (a)]
else:
a = ['%d %d div' \
% (int (round (x * options.grid_scale/inv_scale)),
int (round (options.grid_scale/inv_scale))) for x in unzip_pairs (a)]
t1_outline = t1_outline + ' %s %s\n' % (' '.join (a), c)
t1_outline = t1_outline + ' endchar '
t1_outline = '{\n %s } |- \n' % t1_outline
return (bbox, t1_outline)
# FIXME: Cut and paste programming
def potrace_path_to_type1_ops (at_file, bitmap_metrics, tfm_wid, magnification):
inv_scale = 1000.0 / magnification
(size_y, size_x, off_x, off_y) = list(map (lambda m,
s = inv_scale: m * s,
bitmap_metrics))
ls = open (at_file).readlines ()
bbox = (10000, 10000, -10000, -10000)
while ls and ls[0] != '0 setgray\n':
ls = ls[1:]
if ls == []:
return (bbox, '')
ls = ls[1:]
commands = []
while ls and ls[0] != 'grestore\n':
ell = ls[0]
ls = ls[1:]
if ell == 'fill\n':
continue
toks = ell.split ()
if len (toks) < 1:
continue
cmd = toks[-1]
args = list(map (lambda m, s = inv_scale: s * float (m),
toks[:-1]))
args = zip_to_pairs (args)
commands.append ((cmd, args))
# t1asm seems to fuck up when using sbw. Oh well.
t1_outline = ' %d %d hsbw\n' % (- off_x, tfm_wid)
bbox = (10000, 10000, -10000, -10000)
# Type1 fonts have relative coordinates (doubly relative for
# rrcurveto), so must convert moveto and rcurveto.
z = (0.0, size_y - off_y - 1.0)
for (c, args) in commands:
args = [(x[0] * (1.0 / options.grid_scale),
x[1] * (1.0 / options.grid_scale)) for x in args]
if c == 'moveto':
args = [(args[0][0] - z[0], args[0][1] - z[1])]
zs = []
for a in args:
lz = (z[0] + a[0], z[1] + a[1])
bbox = update_bbox_with_point (bbox, lz)
zs.append (lz)
if options.round_to_int:
last_discr_z = (int (round (z[0])), int (round (z[1])))
else:
last_discr_z = (z[0], z[1])
args = []
for a in zs:
if options.round_to_int:
a = (int (round (a[0])), int (round (a[1])))
else:
a = (a[0], a[1])
args.append ((a[0] - last_discr_z[0],
a[1] - last_discr_z[1]))
last_discr_z = a
if zs:
z = zs[-1]
c = {
'closepath': 'closepath',
'moveto': 'rmoveto',
'rcurveto': 'rrcurveto',
# Potrace 1.9
'restore': '',
'rlineto': 'rlineto',
'%%EOF': '',
}[c]
if c == 'rmoveto':
t1_outline += ' closepath '
if options.round_to_int:
args = ['%d' % int (round (x)) for x in unzip_pairs (args)]
else:
args = ['%d %d div' \
% (int (round (x*options.grid_scale/inv_scale)),
int (round (options.grid_scale/inv_scale))) for x in unzip_pairs (args)]
t1_outline = t1_outline + ' %s %s\n' % (' '.join (args), c)
t1_outline = t1_outline + ' endchar '
t1_outline = '{\n %s } |- \n' % t1_outline
return (bbox, t1_outline)
def read_gf_dims (name, c):
strng = popen ('%s/gf2pbm -n %d -s %s' % (bindir, c, name)).read ()
m = re.search ('size: ([0-9]+)+x([0-9]+), offset: \(([0-9-]+),([0-9-]+)\)', strng)
return tuple (map (int, m.groups ()))
def trace_font (fontname, gf_file, metric, glyphs, encoding,
magnification, fontinfo):
t1os = []
font_bbox = (10000, 10000, -10000, -10000)
progress (_ ("Tracing bitmaps..."))
if options.verbose:
progress ('\n')
else:
progress (' ')
# for single glyph testing.
# glyphs = []
for a in glyphs:
if encoding[a] == ".notavail":
continue
valid = metric.has_char (a)
if not valid:
encoding[a] = ".notavail"
continue
valid = make_pbm (gf_file, 'char.pbm', a)
if not valid:
encoding[a] = ".notavail"
continue
(w, h, xo, yo) = read_gf_dims (gf_file, a)
if not options.verbose:
sys.stderr.write ('[%d' % a)
sys.stderr.flush ()
# this wants the id, not the filename.
success = trace_one ("char.pbm", '%s-%d' % (options.gffile, a))
if not success:
sys.stderr.write ("(skipping character)]")
sys.stderr.flush ()
encoding[a] = ".notavail"
continue
if not options.verbose:
sys.stderr.write (']')
sys.stderr.flush ()
metric_width = metric.get_char (a).width
tw = int (round (metric_width / metric.design_size * 1000))
(bbox, t1o) = path_to_type1_ops ("char.eps", (h, w, xo, yo),
tw, magnification)
if t1o == '':
encoding[a] = ".notavail"
continue
font_bbox = update_bbox_with_bbox (font_bbox, bbox)
t1os.append ('\n/%s %s ' % (encoding[a], t1o))
if not options.verbose:
progress ('\n')
to_type1 (t1os, font_bbox, fontname, encoding, magnification, fontinfo)
def ps_encode_encoding (encoding):
strng = ' %d array\n0 1 %d {1 index exch /.notdef put} for\n' \
% (len (encoding), len (encoding)-1)
for i in range (0, len (encoding)):
if encoding[i] != ".notavail":
strng = strng + 'dup %d /%s put\n' % (i, encoding[i])
return strng
def gen_unique_id (dict):
nm = 'FullName'
return 4000000 + (hash (nm) % 1000000)
def to_type1 (outlines, bbox, fontname, encoding, magnification, fontinfo):
"""
Fill in the header template for the font, append charstrings,
and shove result through t1asm
"""
template = r"""%%!PS-AdobeFont-1.0: %(FontName)s %(VVV)s.%(WWW)s
13 dict begin
/FontInfo 16 dict dup begin
/version (%(VVV)s.%(WWW)s) readonly def
/Notice (%(Notice)s) readonly def
/FullName (%(FullName)s) readonly def
/FamilyName (%(FamilyName)s) readonly def
/Weight (%(Weight)s) readonly def
/ItalicAngle %(ItalicAngle)s def
/isFixedPitch %(isFixedPitch)s def
/UnderlinePosition %(UnderlinePosition)s def
/UnderlineThickness %(UnderlineThickness)s def
end readonly def
/FontName /%(FontName)s def
/FontType 1 def
/PaintType 0 def
/FontMatrix [%(xrevscale)f 0 0 %(yrevscale)f 0 0] readonly def
/FontBBox {%(llx)d %(lly)d %(urx)d %(ury)d} readonly def
/Encoding %(Encoding)s readonly def
currentdict end
currentfile eexec
dup /Private 20 dict dup begin
/-|{string currentfile exch readstring pop}executeonly def
/|-{noaccess def}executeonly def
/|{noaccess put}executeonly def
/lenIV 4 def
/password 5839 def
/MinFeature {16 16} |-
/BlueValues [] |-
/OtherSubrs [ {} {} {} {} ] |-
/ForceBold false def
/Subrs 1 array
dup 0 { return } |
|-
2 index
/CharStrings %(CharStringsLen)d dict dup begin
%(CharStrings)s
/.notdef { 0 0 hsbw endchar } |-
end
end
readonly put
noaccess put
dup/FontName get exch definefont
pop mark currentfile closefile
cleartomark
"""
## apparently, some fonts end the file with cleartomark. Don't know why.
copied_fields = ['FontName', 'FamilyName', 'FullName', 'DesignSize',
'ItalicAngle', 'isFixedPitch', 'Weight']
vars = {
'VVV': '001',
'WWW': '001',
'Notice': 'Generated from MetaFont bitmap by mftrace %s, http://www.xs4all.nl/~hanwen/mftrace/ ' % program_version,
'UnderlinePosition': '-100',
'UnderlineThickness': '50',
'xrevscale': 1.0/1000.0,
'yrevscale': 1.0/1000.0,
'llx': bbox[0],
'lly': bbox[1],
'urx': bbox[2],
'ury': bbox[3],
'Encoding': ps_encode_encoding (encoding),
# need one extra entry for .notdef
'CharStringsLen': len (outlines) + 1,
'CharStrings': ' '.join (outlines),
'CharBBox': '0 0 0 0',
}
for k in copied_fields:
vars[k] = fontinfo[k]
open ('mftrace.t1asm', 'w').write (template % vars)
def update_bbox_with_point (bbox, pt):
(llx, lly, urx, ury) = bbox
llx = min (pt[0], llx)
lly = min (pt[1], lly)
urx = max (pt[0], urx)
ury = max (pt[1], ury)
return (llx, lly, urx, ury)
def update_bbox_with_bbox (bb, dims):
(llx, lly, urx, ury) = bb
llx = min (llx, dims[0])
lly = min (lly, dims[1])
urx = max (urx, dims[2])
ury = max (ury, dims[3])
return (llx, lly, urx, ury)
def get_binary (name):
search_path = os.environ['PATH'].split (':')
for p in search_path:
nm = os.path.join (p, name)
if os.path.exists (nm):
return nm
return ''
def get_fontforge_command ():
if get_binary('fontforge'):
pass
else:
return ''
stat = system ("fontforge --help > pfv 2>&1 ",
ignore_error = 1)
if stat != 0:
warning ("Command `fontforge --help' failed. Cannot simplify or convert to TTF.\n")
return ''
return 'fontforge'
def tfm2kpx (tfmname, encoding):
kpx_lines = []
pl = popen ("tftopl %s" % (tfmname))
label_pattern = re.compile (
"\A \(LABEL ([DOHC]{1}) ([A-Za-z0-9]*)\)")
krn_pattern = re.compile (
"\A \(KRN ([DOHC]{1}) ([A-Za-z0-9]*) R (-?[\d\.]+)\)")
first = 0
second = 0
for line in pl.readlines ():
label_match = label_pattern.search (line)
if not (label_match is None):
if label_match.group (1) == "D":
first = int (label_match.group (2))
elif label_match.group (1) == "O":
first = int (label_match.group (2), 8)
elif label_match.group (1) == "C":
first = ord (label_match.group (2))
krn_match = krn_pattern.search (line)
if not (krn_match is None):
if krn_match.group (1) == "D":
second = int (krn_match.group (2))
elif krn_match.group (1) == "O":
second = int (krn_match.group (2), 8)
elif krn_match.group (1) == "C":
second = ord (krn_match.group (2))
krn = round (float (krn_match.group (3)) * 1000)
if (encoding[first] != '.notavail' and
encoding[first] != '.notdef' and
encoding[second] != '.notavail' and
encoding[second] != '.notdef'):
kpx_lines.append ("KPX %s %s %d\n" % (
encoding[first], encoding[second], krn))
return kpx_lines
def get_afm (t1_path, tfmname, encoding, out_path):
afm_stream = popen ("printafm %s" % (t1_path))
afm_lines = []
kpx_lines = tfm2kpx (tfmname, encoding)
for line in afm_stream.readlines ():
afm_lines.append (line)
if re.match (r"^EndCharMetrics", line, re.I):
afm_lines.append ("StartKernData\n")
afm_lines.append ("StartKernPairs %d\n" % len (kpx_lines))
for kpx_line in kpx_lines:
afm_lines.append (kpx_line)
afm_lines.append ("EndKernPairs\n")
afm_lines.append ("EndKernData\n")
progress (_ ("Writing metrics to `%s'... ") % out_path)
afm_file = open (out_path, 'w')
afm_file.writelines (afm_lines)
afm_file.flush ()
afm_file.close ()
progress ('\n')
def assemble_font (fontname, format, is_raw):
ext = '.' + format
asm_opt = '--pfa'
if format == 'pfb':
asm_opt = '--pfb'
if is_raw:
ext = ext + '.raw'
outname = fontname + ext
progress (_ ("Assembling raw font to `%s'... ") % outname)
if options.verbose:
progress ('\n')
system ('t1asm %s mftrace.t1asm %s' % (asm_opt, shell_escape_filename (outname)))
progress ('\n')
return outname
def make_outputs (fontname, formats, encoding):
"""
run fontforge to convert to other formats
"""
ff_needed = 0
ff_command = ""
if (options.simplify or options.round_to_int or 'ttf' in formats or 'svg' in formats or 'afm' in formats):
ff_needed = 1
if ff_needed:
ff_command = get_fontforge_command ()
if ff_needed and ff_command:
raw_name = assemble_font (fontname, 'pfa', 1)
simplify_cmd = ''
if options.round_to_int:
simplify_cmd = 'RoundToInt ();'
generate_cmds = ''
for f in formats:
generate_cmds += 'Generate("%s");' % (fontname + '.' + f)
if options.simplify:
simplify_cmd ='''SelectAll ();
AddExtrema();
Simplify ();
%(simplify_cmd)s
AutoHint ();''' % vars()
pe_script = ('''#!/usr/bin/env %(ff_command)s
Open ($1);
MergeKern($2);
%(simplify_cmd)s
%(generate_cmds)s
Quit (0);
''' % vars())
open ('to-ttf.pe', 'w').write (pe_script)
if options.verbose:
print('Fontforge script', pe_script)
system ("fontforge -quiet -script to-ttf.pe %s %s" %
(shell_escape_filename (raw_name), shell_escape_filename (options.tfm_file)))
elif ff_needed and (options.simplify or options.round_to_int or 'ttf' in formats or 'svg' in formats):
error(_ ("fontforge is not installed; could not perform requested command"))
else:
t1_path = ''
if ('pfa' in formats):
t1_path = assemble_font (fontname, 'pfa', 0)
if ('pfb' in formats):
t1_path = assemble_font (fontname, 'pfb', 0)
if (t1_path != '' and 'afm' in formats):
if get_binary("printafm"):
get_afm (t1_path, options.tfm_file, encoding, fontname + '.afm')
else:
error(_ ("Neither fontforge nor ghostscript is installed; could not perform requested command"))
def getenv (var, default):
if var in os.environ:
return os.environ[var]
else:
return default
def gen_pixel_font (filename, metric, magnification):
"""
Generate a GF file for FILENAME, such that `magnification'*mfscale
(default 1000 * 1.0) pixels fit on the designsize.
"""
base_dpi = 1200
size = metric.design_size
size_points = size * 1/72.27 * base_dpi
mag = magnification / size_points
prod = mag * base_dpi
try:
open ('%s.%dgf' % (filename, prod))
except IOError:
## MFINPUTS/TFMFONTS take kpathsea specific values;
## we should analyse them any further.
os.environ['MFINPUTS'] = '%s:%s' % (origdir,
getenv ('MFINPUTS', ''))
os.environ['TFMFONTS'] = '%s:%s' % (origdir,
getenv ('TFMINPUTS', ''))
progress (_ ("Running Metafont..."))
cmdstr = r"mf '\mode:=lexmarks; mag:=%f; nonstopmode; input %s'" % (mag, filename)
if not options.verbose:
cmdstr = cmdstr + ' 1>/dev/null 2>/dev/null'
st = system (cmdstr, ignore_error = 1)
progress ('\n')
logfile = '%s.log' % filename
log = ''
prod = 0
if os.path.exists (logfile):
log = open (logfile).read ()
m = re.search ('Output written on %s.([0-9]+)gf' % re.escape (filename), log)
prod = int (m.group (1))
if st:
sys.stderr.write ('\n\nMetafont failed. Excerpt from the log file: \n\n*****')
m = re.search ("\n!", log)
start = m.start (0)
short_log = log[start:start+200]
sys.stderr.write (short_log)
sys.stderr.write ('\n*****\n')
if re.search ('Arithmetic overflow', log):
sys.stderr.write ("""
Apparently, some numbers overflowed. Try using --magnification with a
lower number. (Current magnification: %d)
""" % magnification)
if not options.keep_trying or prod == 0:
sys.exit (1)
else:
sys.stderr.write ('\n\nTrying to proceed despite of the Metafont errors...\n')
return "%s.%d" % (filename, prod)
def parse_command_line ():
p = optparse.OptionParser (version="""mftrace @VERSION@
This program is free software. It is covered by the GNU General Public
License and you are welcome to change it and/or distribute copies of it
under certain conditions. Invoke as `mftrace --warranty' for more
information.
Copyright (c) 2005--2006 by
Han-Wen Nienhuys <[email protected]>
""")
p.usage = "mftrace [OPTION]... FILE..."
p.description = _ ("Generate Type1 or TrueType font from Metafont source.")
p.add_option ('-k', '--keep',
action="store_true",
dest="keep_temp_dir",
help=_ ("Keep all output in directory %s.dir") % program_name)
p.add_option ('--magnification',
dest="magnification",
metavar="MAG",
default=1000.0,
type="float",
help=_("Set magnification for MF to MAG (default: 1000)"))
p.add_option ('-V', '--verbose',
action='store_true',
default=False,
help=_ ("Be verbose"))
p.add_option ('-f', '--formats',
action="append",
dest="formats",
default=[],
help=_("Which formats to generate (choices: AFM, PFA, PFB, TTF, SVG)"))
p.add_option ('--simplify',
action="store_true",
dest="simplify",
default=False,
help=_ ("Simplify using fontforge"))
p.add_option ('--gffile',
dest="gffile",
help= _("Use gf FILE instead of running Metafont"))
p.add_option ('-I', '--include',
dest="include_dirs",
action="append",
default=[],
help=_("Add to path for searching files"))
p.add_option ('--glyphs',
default=[],
action="append",
dest="glyphs",
metavar="LIST",