4 # this file is part of mftrace - a tool to generate scalable fonts from MF sources
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License version 2
9 # as published by the Free Software Foundation
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU Library General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 # Copyright (c) 2001--2006 by
22 # Han-Wen Nienhuys, Jan Nieuwenhuizen
35 localedir
= datadir
+ '/locale'
37 exec_prefix
= '@exec_prefix@'
39 def interpolate (str):
40 str = string
.replace (str, '{', '(')
41 str = string
.replace (str, '}', ')s')
42 str = string
.replace (str, '$', '%')
45 if prefix
!= '@' + 'prefix@':
46 exec_prefix
= interpolate (exec_prefix
) % vars ()
47 bindir
= interpolate (bindir
) % vars ()
48 datadir
= os
.path
.join (interpolate (datadir
) % vars (), 'mftrace')
49 libdir
= interpolate (libdir
) % vars ()
51 if datadir
== '@' + "datadir" + "@":
52 datadir
= os
.getcwd ()
55 sys
.path
.append (datadir
)
60 errorport
= sys
.stderr
62 ################################################################
63 # lilylib.py -- options and stuff
65 # source file of the GNU LilyPond music typesetter
69 gettext
.bindtextdomain ('mftrace', localedir
)
70 gettext
.textdomain ('mftrace')
76 def shell_escape_filename (str):
77 str = re
.sub ('([\'" ])', r
'\\\1', str)
81 port
.write ('%s %s\n' % (program_name
, program_version
))
85 sys
.stdout
.write ('\n')
86 sys
.stdout
.write (_ ('Copyright (c) %s by' % ' 2001--2004'))
87 sys
.stdout
.write ('\n')
88 sys
.stdout
.write (' Han-Wen Nienhuys')
89 sys
.stdout
.write (' Jan Nieuwenhuizen')
90 sys
.stdout
.write ('\n')
91 sys
.stdout
.write (_ (r
'''
92 Distributed under terms of the GNU General Public License. It comes with
94 sys
.stdout
.write ('\n')
100 errorport
.write (_ ("warning: ") + s
)
103 '''Report the error S. Exit by raising an exception. Please
104 do not abuse by trying to catch this error. If you do not want
105 a stack trace, write to the output directly.
113 errorport
.write (_ ("error: ") + s
+ '\n')
114 raise _ ("Exiting ... ")
118 Create a temporary directory, and return its name.
121 if not options
.keep_temp_dir
:
122 temp_dir
= tempfile
.mkdtemp (program_name
)
125 os
.mkdir (temp_dir
, 0700)
131 def popen (cmd
, mode
= 'r', ignore_error
= 0):
133 progress (_ ("Opening pipe `%s\'") % cmd
)
134 pipe
= os
.popen (cmd
, mode
)
139 def system (cmd
, ignore_error
= 0):
140 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
148 progress (_ ("Invoking `%s\'\n") % cmd
)
151 name
= re
.match ('[ \t]*([^ \t]*)', cmd
).group (1)
152 msg
= name
+ ': ' + _ ("command exited with value %d") % st
154 warning (msg
+ ' ' + _ ("(ignored)") + ' ')
162 if not options
.keep_temp_dir
:
164 progress (_ ("Cleaning %s...") % temp_dir
)
165 shutil
.rmtree (temp_dir
)
168 def strip_extension (f
, ext
):
169 (p
, e
) = os
.path
.splitext (f
)
175 ################################################################
183 program_name
= 'mftrace'
184 temp_dir
= os
.path
.join (os
.getcwd (), program_name
+ '.dir')
185 program_version
= '@VERSION@'
186 origdir
= os
.getcwd ()
191 'TeX typewriter text': '09fbbfac.enc', # cmtt10
192 'TeX math symbols':'10037936.enc ', # cmbsy
193 'ASCII caps and digits':'1b6d048e', # cminch
194 'TeX math italic': 'aae443f0.enc ', # cmmi10
195 'TeX extended ASCII':'d9b29452.enc',
196 'TeX text': 'f7b6d320.enc',
197 'TeX text without f-ligatures': '0ef0afca.enc',
199 'Extended TeX Font Encoding - Latin': 'tex256.enc',
202 'fetaBraces': 'feta-braces-a.enc',
203 'fetaNumber': 'feta-nummer10.enc',
204 'fetaMusic': 'feta20.enc',
205 'parmesanMusic': 'parmesan20.enc',
210 for d
in include_dirs
:
211 p
= os
.path
.join (d
, nm
)
214 return os
.path
.abspath (p
)
218 p
= popen ('kpsewhich %s' % shell_escape_filename (nm
)).read ()
221 if options
.dos_kpath
:
224 p
= re
.sub ('^([a-z]):', '/cygdrive/\\1', p
)
225 p
= re
.sub ('\\\\', '/', p
)
226 sys
.stderr
.write ("Got `%s' from kpsewhich, using `%s'\n" % (orig
, p
))
234 ################################################################
236 ################################################################
238 def autotrace_command (fn
, opts
):
239 opts
= " " + opts
+ " --background-color=FFFFFF --output-format=eps --input-format=pbm "
240 return options
.trace_binary
+ opts
+ backend_options \
241 + " --output-file=char.eps %s " % fn
243 def potrace_command (fn
, opts
):
244 return options
.trace_binary
+ opts \
245 + ' -u %d ' % options
.grid_scale \
247 + " -q -c --eps --output=char.eps %s " % (fn
)
250 path_to_type1_ops
= None
252 def trace_one (pbmfile
, id):
254 Run tracer, do error handling
257 status
= system (trace_command (pbmfile
, ''), 1)
260 sys
.stderr
.write ("\nUser interrupt. Exiting\n")
263 if status
== 0 and options
.keep_temp_dir
:
264 shutil
.copy2 (pbmfile
, '%s.pbm' % id)
265 shutil
.copy2 ('char.eps', '%s.eps' % id)
268 error_file
= os
.path
.join (origdir
, 'trace-bug-%s.pbm' % id)
269 shutil
.copy2 (pbmfile
, error_file
)
270 msg
= """Trace failed on bitmap. Bitmap left in `%s\'
275 Please submit a bugreport to %s development.""" \
276 % (error_file
, trace_command (error_file
, ''), options
.trace_binary
)
278 if options
.keep_trying
:
280 sys
.stderr
.write ("\nContinuing trace...\n")
283 msg
= msg
+ '\nRun mftrace with --keep-trying to produce a font anyway\n'
289 warning ("Failed, skipping character.\n")
294 def make_pbm (filename
, outname
, char_number
):
295 """ Extract bitmap from the PK file FILENAME (absolute) using `gf2pbm'.
296 Return FALSE if the glyph is not valid.
299 command
= "%s/gf2pbm -n %d -o %s %s" % (bindir
, char_number
, outname
, filename
)
300 status
= system (command
, ignore_error
= 1)
303 def read_encoding (file):
304 sys
.stderr
.write (_ ("Using encoding file: `%s'\n") % file)
306 str = open (file).read ()
307 str = re
.sub ("%.*", '', str)
308 str = re
.sub ("[\n\t \f]+", ' ', str)
309 m
= re
.search ('/([^ ]+) \[([^\]]+)\] def', str)
311 error ("Encoding file is invalid")
315 cod
= re
.sub ('[ /]+', ' ', cod
)
316 cods
= string
.split (cod
)
320 def zip_to_pairs (as):
323 r
.append ((as[0], as[1]))
327 def unzip_pairs (tups
):
330 lst
= lst
+ list (tups
[0])
334 def autotrace_path_to_type1_ops (at_file
, bitmap_metrics
, tfm_wid
, magnification
):
335 inv_scale
= 1000.0 / magnification
337 (size_y
, size_x
, off_x
, off_y
) = map (lambda m
, s
= inv_scale
: m
* s
,
339 ls
= open (at_file
).readlines ()
340 bbox
= (10000, 10000, -10000, -10000)
342 while ls
and ls
[0] != '*u\n':
353 while ls
[0] != '*U\n':
357 toks
= string
.split (ell
)
362 args
= map (lambda m
, s
= inv_scale
: s
* float (m
),
364 if options
.round_to_int
:
365 args
= zip_to_pairs (map (round, args
))
367 args
= zip_to_pairs (args
)
368 commands
.append ((cmd
, args
))
378 cy
= size_y
- off_y
- inv_scale
380 # t1asm seems to fuck up when using sbw. Oh well.
381 t1_outline
= ' %d %d hsbw\n' % (- off_x
, tfm_wid
)
382 bbox
= (10000, 10000, -10000, -10000)
384 for (c
, args
) in commands
:
389 if c
== 'l' or c
== 'c':
390 bbox
= update_bbox_with_point (bbox
, a
)
392 na
.append ((nx
- cx
, ny
- cy
))
397 if options
.round_to_int
:
398 a
= map (lambda x
: '%d' % int (round (x
)),
401 a
= map (lambda x
: '%d %d div' \
402 % (int (round (x
* options
.grid_scale
/inv_scale
)),
403 int (round (options
.grid_scale
/inv_scale
))),
406 t1_outline
= t1_outline
+ ' %s %s\n' % (string
.join (a
), c
)
408 t1_outline
= t1_outline
+ ' endchar '
409 t1_outline
= '{\n %s } |- \n' % t1_outline
411 return (bbox
, t1_outline
)
413 # FIXME: Cut and paste programming
414 def potrace_path_to_type1_ops (at_file
, bitmap_metrics
, tfm_wid
, magnification
):
415 inv_scale
= 1000.0 / magnification
417 (size_y
, size_x
, off_x
, off_y
) = map (lambda m
,
418 s
= inv_scale
: m
* s
,
420 ls
= open (at_file
).readlines ()
421 bbox
= (10000, 10000, -10000, -10000)
423 while ls
and ls
[0] != '0 setgray\n':
431 while ls
and ls
[0] != 'grestore\n':
438 toks
= string
.split (ell
)
443 args
= map (lambda m
, s
= inv_scale
: s
* float (m
),
445 args
= zip_to_pairs (args
)
446 commands
.append ((cmd
, args
))
448 # t1asm seems to fuck up when using sbw. Oh well.
449 t1_outline
= ' %d %d hsbw\n' % (- off_x
, tfm_wid
)
450 bbox
= (10000, 10000, -10000, -10000)
452 # Type1 fonts have relative coordinates (doubly relative for
453 # rrcurveto), so must convert moveto and rcurveto.
455 z
= (0.0, size_y
- off_y
- 1.0)
456 for (c
, args
) in commands
:
457 args
= map (lambda x
: (x
[0] * (1.0 / options
.grid_scale
),
458 x
[1] * (1.0 / options
.grid_scale
)), args
)
461 args
= [(args
[0][0] - z
[0], args
[0][1] - z
[1])]
465 lz
= (z
[0] + a
[0], z
[1] + a
[1])
466 bbox
= update_bbox_with_point (bbox
, lz
)
469 if options
.round_to_int
:
470 last_discr_z
= (int (round (z
[0])), int (round (z
[1])))
472 last_discr_z
= (z
[0], z
[1])
475 if options
.round_to_int
:
476 a
= (int (round (a
[0])), int (round (a
[1])))
479 args
.append ((a
[0] - last_discr_z
[0],
480 a
[1] - last_discr_z
[1]))
486 c
= { 'rcurveto': 'rrcurveto',
488 'closepath': 'closepath',
489 'rlineto': 'rlineto'}[c
]
492 t1_outline
+= ' closepath '
494 if options
.round_to_int
:
495 args
= map (lambda x
: '%d' % int (round (x
)),
498 args
= map (lambda x
: '%d %d div' \
499 % (int (round (x
*options
.grid_scale
/inv_scale
)),
500 int (round (options
.grid_scale
/inv_scale
))),
503 t1_outline
= t1_outline
+ ' %s %s\n' % (string
.join (args
), c
)
505 t1_outline
= t1_outline
+ ' endchar '
506 t1_outline
= '{\n %s } |- \n' % t1_outline
508 return (bbox
, t1_outline
)
510 def read_gf_dims (name
, c
):
511 str = popen ('%s/gf2pbm -n %d -s %s' % (bindir
, c
, name
)).read ()
512 m
= re
.search ('size: ([0-9]+)+x([0-9]+), offset: \(([0-9-]+),([0-9-]+)\)', str)
514 return tuple (map (int, m
.groups ()))
516 def trace_font (fontname
, gf_file
, metric
, glyphs
, encoding
,
517 magnification
, fontinfo
):
519 font_bbox
= (10000, 10000, -10000, -10000)
521 progress (_ ("Tracing bitmaps... "))
523 # for single glyph testing.
526 if encoding
[a
] == ".notavail":
528 valid
= metric
.has_char (a
)
530 encoding
[a
] = ".notavail"
533 valid
= make_pbm (gf_file
, 'char.pbm', a
)
535 encoding
[a
] = ".notavail"
538 (w
, h
, xo
, yo
) = read_gf_dims (gf_file
, a
)
540 if not options
.verbose
:
541 sys
.stderr
.write ('[%d' % a
)
544 # this wants the id, not the filename.
545 success
= trace_one ("char.pbm", '%s-%d' % (options
.gffile
, a
))
547 sys
.stderr
.write ("(skipping character)]")
549 encoding
[a
] = ".notavail"
552 if not options
.verbose
:
553 sys
.stderr
.write (']')
555 metric_width
= metric
.get_char (a
).width
556 tw
= int (round (metric_width
/ metric
.design_size
* 1000))
557 (bbox
, t1o
) = path_to_type1_ops ("char.eps", (h
, w
, xo
, yo
),
561 encoding
[a
] = ".notavail"
564 font_bbox
= update_bbox_with_bbox (font_bbox
, bbox
)
566 t1os
.append ('\n/%s %s ' % (encoding
[a
], t1o
))
569 to_type1 (t1os
, font_bbox
, fontname
, encoding
, magnification
, fontinfo
)
571 def ps_encode_encoding (encoding
):
572 str = ' %d array\n0 1 %d {1 index exch /.notdef put} for\n' \
573 % (len (encoding
), len (encoding
)-1)
575 for i
in range (0, len (encoding
)):
576 if encoding
[i
] != ".notavail":
577 str = str + 'dup %d /%s put\n' % (i
, encoding
[i
])
582 def gen_unique_id (dict):
584 return 4000000 + (hash (nm
) % 1000000)
586 def to_type1 (outlines
, bbox
, fontname
, encoding
, magnification
, fontinfo
):
589 Fill in the header template for the font, append charstrings,
590 and shove result through t1asm
592 template
= r
"""%%!PS-AdobeFont-1.0: %(FontName)s %(VVV)s.%(WWW)s
594 /FontInfo 16 dict dup begin
595 /version (%(VVV)s.%(WWW)s) readonly def
596 /Notice (%(Notice)s) readonly def
597 /FullName (%(FullName)s) readonly def
598 /FamilyName (%(FamilyName)s) readonly def
599 /Weight (%(Weight)s) readonly def
600 /ItalicAngle %(ItalicAngle)s def
601 /isFixedPitch %(isFixedPitch)s def
602 /UnderlinePosition %(UnderlinePosition)s def
603 /UnderlineThickness %(UnderlineThickness)s def
605 /FontName /%(FontName)s def
608 /FontMatrix [%(xrevscale)f 0 0 %(yrevscale)f 0 0] readonly def
609 /FontBBox {%(llx)d %(lly)d %(urx)d %(ury)d} readonly def
610 /Encoding %(Encoding)s readonly def
613 dup /Private 20 dict dup begin
614 /-|{string currentfile exch readstring pop}executeonly def
615 /|-{noaccess def}executeonly def
616 /|{noaccess put}executeonly def
619 /MinFeature {16 16} |-
621 /OtherSubrs [ {} {} {} {} ] |-
627 /CharStrings %(CharStringsLen)d dict dup begin
631 /.notdef { 0 0 hsbw endchar } |-
636 dup/FontName get exch definefont
637 pop mark currentfile closefile
640 ## apparently, some fonts end the file with cleartomark. Don't know why.
642 copied_fields
= ['FontName', 'FamilyName', 'FullName', 'DesignSize',
643 'ItalicAngle', 'isFixedPitch', 'Weight']
648 'Notice': 'Generated from MetaFont bitmap by mftrace %s, http://www.xs4all.nl/~hanwen/mftrace/ ' % program_version
,
649 'UnderlinePosition': '-100',
650 'UnderlineThickness': '50',
651 'xrevscale': 1.0/1000.0,
652 'yrevscale': 1.0/1000.0,
657 'Encoding': ps_encode_encoding (encoding
),
659 # need one extra entry for .notdef
660 'CharStringsLen': len (outlines
) + 1,
661 'CharStrings': string
.join (outlines
),
662 'CharBBox': '0 0 0 0',
665 for k
in copied_fields
:
666 vars[k
] = fontinfo
[k
]
668 open ('mftrace.t1asm', 'w').write (template
% vars)
670 def update_bbox_with_point (bbox
, pt
):
671 (llx
, lly
, urx
, ury
) = bbox
672 llx
= min (pt
[0], llx
)
673 lly
= min (pt
[1], lly
)
674 urx
= max (pt
[0], urx
)
675 ury
= max (pt
[1], ury
)
677 return (llx
, lly
, urx
, ury
)
679 def update_bbox_with_bbox (bb
, dims
):
680 (llx
, lly
, urx
, ury
) = bb
681 llx
= min (llx
, dims
[0])
682 lly
= min (lly
, dims
[1])
683 urx
= max (urx
, dims
[2])
684 ury
= max (ury
, dims
[3])
686 return (llx
, lly
, urx
, ury
)
688 def get_binary (name
):
689 search_path
= string
.split (os
.environ
['PATH'], ':')
690 for p
in search_path
:
691 nm
= os
.path
.join (p
, name
)
692 if os
.path
.exists (nm
):
697 def get_fontforge_command ():
699 for ff
in ['fontforge', 'pfaedit']:
705 stat
= system ("%s -usage > pfv 2>&1 " % fontforge_cmd
,
709 warning ("Command `%s -usage' failed. Cannot simplify or convert to TTF.\n" % fontforge_cmd
)
711 if fontforge_cmd
== 'pfaedit' \
712 and re
.search ("-script", open ('pfv').read ()) == None:
713 warning ("pfaedit does not support -script. Install 020215 or later.\nCannot simplify or convert to TTF.\n")
717 def tfm2kpx (tfmname
, encoding
):
719 pl
= popen ("tftopl %s" % (tfmname
))
721 label_pattern
= re
.compile (
722 "\A \(LABEL ([DOHC]{1}) ([A-Za-z0-9]*)\)")
723 krn_pattern
= re
.compile (
724 "\A \(KRN ([DOHC]{1}) ([A-Za-z0-9]*) R (-?[\d\.]+)\)")
729 for line
in pl
.readlines ():
731 label_match
= label_pattern
.search (line
)
732 if not (label_match
is None):
733 if label_match
.group (1) == "D":
734 first
= int (label_match
.group (2))
735 elif label_match
.group (1) == "O":
736 first
= int (label_match
.group (2), 8)
737 elif label_match
.group (1) == "C":
738 first
= ord (label_match
.group (2))
740 krn_match
= krn_pattern
.search (line
)
741 if not (krn_match
is None):
742 if krn_match
.group (1) == "D":
743 second
= int (krn_match
.group (2))
744 elif krn_match
.group (1) == "O":
745 second
= int (krn_match
.group (2), 8)
746 elif krn_match
.group (1) == "C":
747 second
= ord (krn_match
.group (2))
749 krn
= round (float (krn_match
.group (3)) * 1000)
751 if (encoding
[first
] != '.notavail' and
752 encoding
[first
] != '.notdef' and
753 encoding
[second
] != '.notavail' and
754 encoding
[second
] != '.notdef'):
756 kpx_lines
.append ("KPX %s %s %d\n" % (
757 encoding
[first
], encoding
[second
], krn
))
761 def get_afm (t1_path
, tfmname
, encoding
, out_path
):
762 afm_stream
= popen ("printafm %s" % (t1_path
))
764 kpx_lines
= tfm2kpx (tfmname
, encoding
)
766 for line
in afm_stream
.readlines ():
767 afm_lines
.append (line
)
769 if re
.match (r
"^EndCharMetrics", line
, re
.I
):
770 afm_lines
.append ("StartKernData\n")
771 afm_lines
.append ("StartKernPairs %d\n" % len (kpx_lines
))
773 for kpx_line
in kpx_lines
:
774 afm_lines
.append (kpx_line
)
776 afm_lines
.append ("EndKernPairs\n")
777 afm_lines
.append ("EndKernData\n")
779 progress (_ ("Writing metrics to `%s'... ") % out_path
)
780 afm_file
= open (out_path
, 'w')
781 afm_file
.writelines (afm_lines
)
787 def assemble_font (fontname
, format
, is_raw
):
797 outname
= fontname
+ ext
799 progress (_ ("Assembling raw font to `%s'... ") % outname
)
800 system ('t1asm %s mftrace.t1asm %s' % (asm_opt
, shell_escape_filename (outname
)))
804 def make_outputs (fontname
, formats
, encoding
):
806 run pfaedit to convert to other formats
812 if (options
.simplify
or options
.round_to_int
or 'ttf' in formats
or 'svg' in formats
):
815 ff_command
= get_fontforge_command ()
817 if ff_needed
and ff_command
:
818 raw_name
= assemble_font (fontname
, 'pfa', 1)
821 if options
.round_to_int
:
822 simplify_cmd
= 'RoundToInt ();'
825 generate_cmds
+= 'Generate("%s");' % (fontname
+ '.' + f
)
828 simplify_cmd
='''SelectAll ();
833 AutoHint ();''' % vars()
835 pe_script
= ('''#!/usr/bin/env %(ff_command)s
843 open ('to-ttf.pe', 'w').write (pe_script
)
845 print 'Fontforge script', pe_script
846 system ("%s -script to-ttf.pe %s %s" % (ff_command
,
847 shell_escape_filename (raw_name
), shell_escape_filename (options
.tfm_file
)))
851 if ('pfa' in formats
):
852 t1_path
= assemble_font (fontname
, 'pfa', 0)
854 if ('pfb' in formats
):
855 t1_path
= assemble_font (fontname
, 'pfb', 0)
857 if (t1_path
!= '' and 'afm' in formats
):
858 get_afm (t1_path
, options
.tfm_file
, encoding
, fontname
+ '.afm')
861 def getenv (var
, default
):
862 if os
.environ
.has_key (var
):
863 return os
.environ
[var
]
867 def gen_pixel_font (filename
, metric
, magnification
):
869 Generate a GF file for FILENAME, such that `magnification'*mfscale
870 (default 1000 * 1.0) pixels fit on the designsize.
874 size
= metric
.design_size
876 size_points
= size
* 1/72.27 * base_dpi
878 mag
= magnification
/ size_points
880 prod
= mag
* base_dpi
882 open ('%s.%dgf' % (filename
, prod
))
884 os
.environ
['KPSE_DOT'] = '%s:' % origdir
886 os
.environ
['MFINPUTS'] = '%s:%s' % (origdir
,
887 getenv ('MFINPUTS', ''))
888 os
.environ
['TFMFONTS'] = '%s:%s' % (origdir
,
889 getenv ('TFMINPUTS', ''))
891 # FIXME: we should not change to another (tmp) dir?
892 # or else make all relavitive dirs in paths absolute.
893 def abs_dir (x
, dir):
894 if x
and os
.path
.abspath (x
) != x
:
895 return os
.path
.join (dir, x
)
898 def abs_path (path
, dir):
899 # Python's ABSPATH means ABSDIR
900 dir = os
.path
.abspath (dir)
901 return string
.join (map (lambda x
: abs_dir (x
, dir),
906 os
.environ
['MFINPUTS'] = abs_path (os
.environ
['MFINPUTS'],
908 os
.environ
['TFMFONTS'] = abs_path (os
.environ
['TFMFONTS'],
911 progress (_ ("Running Metafont..."))
913 cmdstr
= r
"mf '\mode:=lexmarks; mag:=%f; nonstopmode; input %s'" % (mag
, filename
)
914 if not options
.verbose
:
915 cmdstr
= cmdstr
+ ' 1>/dev/null 2>/dev/null'
916 st
= system (cmdstr
, ignore_error
= 1)
919 logfile
= '%s.log' % filename
922 if os
.path
.exists (logfile
):
923 log
= open (logfile
).read ()
924 m
= re
.search ('Output written on %s.([0-9]+)gf' % re
.escape (filename
), log
)
925 prod
= int (m
.group (1))
928 sys
.stderr
.write ('\n\nMetafont failed. Excerpt from the log file: \n\n*****')
929 m
= re
.search ("\n!", log
)
931 short_log
= log
[start
:start
+200]
932 sys
.stderr
.write (short_log
)
933 sys
.stderr
.write ('\n*****\n')
934 if re
.search ('Arithmetic overflow', log
):
935 sys
.stderr
.write ("""
937 Apparently, some numbers overflowed. Try using --magnification with a
938 lower number. (Current magnification: %d)
941 if not options
.keep_trying
or prod
== 0:
944 sys
.stderr
.write ('\n\nTrying to proceed despite of the Metafont errors...\n')
948 return "%s.%d" % (filename
, prod
)
950 def parse_command_line ():
951 p
= optparse
.OptionParser (version
="""mftrace @VERSION@
953 This program is free software. It is covered by the GNU General Public
954 License and you are welcome to change it and/or distribute copies of it
955 under certain conditions. Invoke as `mftrace --warranty' for more
958 Copyright (c) 2005--2006 by
959 Han-Wen Nienhuys <hanwen@xs4all.nl>
962 p
.usage
= "mftrace [OPTION]... FILE..."
963 p
.description
= _ ("Generate Type1 or TrueType font from Metafont source.")
965 p
.add_option ('-k', '--keep',
967 dest
="keep_temp_dir",
968 help=_ ("Keep all output in directory %s.dir") % program_name
)
969 p
.add_option ('','--magnification',
970 dest
="magnification",
974 help=_("Set magnification for MF to MAG (default: 1000)"))
975 p
.add_option ('-V', '--verbose',
978 help=_ ("Be verbose"))
979 p
.add_option ('-f', '--formats',
983 help=_("Which formats to generate (choices: AFM, PFA, PFB, TTF, SVG)"))
984 p
.add_option ('', '--simplify',
987 help=_ ("Simplify using fontforge"))
988 p
.add_option ('', '--gffile',
990 help= _("Use gf FILE instead of running Metafont"))
991 p
.add_option ('-I', '--include',
995 help=_("Add to path for searching files"))
996 p
.add_option ('','--glyphs',
1001 help= _('Process only these glyphs. LIST is comma separated'))
1002 p
.add_option ('', '--tfmfile',
1007 p
.add_option ('-e', '--encoding',
1010 dest
="encoding_file",
1012 help= _ ("Use encoding file FILE"))
1013 p
.add_option ('','--keep-trying',
1016 action
="store_true",
1017 help= _ ("Don't stop if tracing fails"))
1018 p
.add_option ('-w', '--warranty',
1019 action
="store_true",
1020 help=_ ("show warranty and copyright"))
1021 p
.add_option ('','--dos-kpath',
1023 help=_("try to use Miktex kpsewhich"))
1024 p
.add_option ('', '--potrace',
1026 help=_ ("Use potrace"))
1027 p
.add_option ('', '--autotrace',
1029 help=_ ("Use autotrace"))
1030 p
.add_option ('', '--no-afm',
1031 action
='store_false',
1034 help=_("Don't read AFM file"))
1035 p
.add_option ('','--noround',
1036 action
="store_false",
1037 dest
='round_to_int',
1039 help= ("Do not round coordinates of control points to integer values (use with --grid)"))
1040 p
.add_option ('','--grid',
1045 help=_ ("Set reciprocal grid size in em units"))
1046 p
.add_option ('-D','--define',
1047 metavar
="SYMBOL=VALUE",
1050 action
='append',help=_("Set the font info SYMBOL to VALUE"))
1053 (options
, files
) = p
.parse_args ()
1056 sys
.stderr
.write ('Need argument on command line \n')
1060 if options
.warranty
:
1064 options
.font_info
= {}
1065 for d
in options
.defs
:
1068 options
.font_info
[kv
] = 'true'
1070 options
.font_info
[kv
[0]] = '='.join (kv
[1:])
1072 def comma_sepped_to_list (x
):
1075 fs
+= f
.lower ().split (',')
1078 options
.formats
= comma_sepped_to_list (options
.formats
)
1081 for r
in options
.glyphs
:
1082 new_glyphs
+= r
.split (',')
1083 options
.glyphs
= new_glyphs
1086 for r
in options
.glyphs
:
1087 glyph_subrange
= map (int, string
.split (r
, '-'))
1088 if len (glyph_subrange
) == 2 and glyph_subrange
[0] < glyph_subrange
[1] + 1:
1089 glyph_range
+= range (glyph_subrange
[0], glyph_subrange
[1] + 1)
1091 glyph_range
.append (glyph_subrange
[0])
1093 options
.glyphs
= glyph_range
1095 options
.trace_binary
= ''
1097 options
.trace_binary
= 'potrace'
1098 elif options
.autotrace
:
1099 options
.trace_binary
= 'autotrace'
1101 if options
.formats
== []:
1102 options
.formats
= ['pfa']
1106 global trace_command
1107 global path_to_type1_ops
1109 stat
= os
.system ('potrace --version > /dev/null 2>&1 ')
1110 if options
.trace_binary
!= 'autotrace' and stat
== 0:
1111 options
.trace_binary
= 'potrace'
1113 trace_command
= potrace_command
1114 path_to_type1_ops
= potrace_path_to_type1_ops
1116 stat
= os
.system ('autotrace --version > /dev/null 2>&1 ')
1117 if options
.trace_binary
!= 'potrace' and stat
== 0:
1118 options
.trace_binary
= 'autotrace'
1119 trace_command
= autotrace_command
1120 path_to_type1_ops
= autotrace_path_to_type1_ops
1122 if not options
.trace_binary
:
1123 error (_ ("No tracing program found.\nInstall potrace or autotrace."))
1128 def derive_font_name (family
, fullname
):
1129 fullname
= re
.sub (family
, '', fullname
)
1130 family
= re
.sub (' ', '', family
)
1131 fullname
= re
.sub ('Oldstyle Figures', 'OsF', fullname
)
1132 fullname
= re
.sub ('Small Caps', 'SC', fullname
)
1133 fullname
= re
.sub ('[Mm]edium', '', fullname
)
1134 fullname
= re
.sub ('[^A-Za-z0-9]', '', fullname
)
1135 return '%s-%s' % (family
, fullname
)
1137 def cm_guess_font_info (filename
, fontinfo
):
1139 filename
= re
.sub ("cm(.*)tt", r
"cmtt\1", filename
)
1140 m
= re
.search ("([0-9]+)$", filename
)
1143 design_size
= int (m
.group (1))
1144 fontinfo
['DesignSize'] = design_size
1146 prefixes
= [("cmtt", "Computer Modern Typewriter"),
1147 ("cmvtt", "Computer Modern Variable Width Typewriter"),
1148 ("cmss", "Computer Modern Sans"),
1149 ("cm", "Computer Modern")]
1152 for (k
, v
) in prefixes
:
1153 if re
.search (k
, filename
):
1156 fontinfo
['isFixedPitch'] = 'true'
1157 filename
= re
.sub (k
, '', filename
)
1161 prefixes
= [("r", "Roman"),
1162 ("mi", "Math italic"),
1163 ("u", "Unslanted italic"),
1165 ("csc", "Small Caps"),
1166 ("ex", "Math extension"),
1167 ("ti", "Text italic"),
1170 for (k
, v
) in prefixes
:
1171 if re
.search (k
, filename
):
1173 filename
= re
.sub (k
, '', filename
)
1175 prefixes
= [("b", "Bold"),
1178 for (k
, v
) in prefixes
:
1179 if re
.search (k
, filename
):
1181 filename
= re
.sub (k
, '', filename
)
1183 prefixes
= [("c", "Condensed"),
1186 for (k
, v
) in prefixes
:
1187 if re
.search (k
, filename
):
1189 filename
= re
.sub (k
, '', filename
)
1191 fontinfo
['ItalicAngle'] = 0
1192 if re
.search ('[Ii]talic', shape
) or re
.search ('[Oo]blique', shape
):
1194 if re
.search ("Sans", family
):
1197 fontinfo
["ItalicAngle"] = a
1199 fontinfo
['Weight'] = weight
1200 fontinfo
['FamilyName'] = family
1201 full
= '%s %s %s %s %dpt' \
1202 % (family
, shape
, weight
, stretch
, design_size
)
1203 full
= re
.sub (" +", ' ', full
)
1205 fontinfo
['FullName'] = full
1206 fontinfo
['FontName'] = derive_font_name (family
, full
)
1210 def ec_guess_font_info (filename
, fontinfo
):
1212 m
= re
.search ("([0-9]+)$", filename
)
1214 design_size
= int (m
.group (1))
1215 fontinfo
['DesignSize'] = design_size
1217 prefixes
= [("ecss", "European Computer Modern Sans"),
1218 ("ectt", "European Computer Modern Typewriter"),
1219 ("ec", "European Computer Modern")]
1222 for (k
, v
) in prefixes
:
1223 if re
.search (k
, filename
):
1225 fontinfo
['isFixedPitch'] = 'true'
1227 filename
= re
.sub (k
, '', filename
)
1231 prefixes
= [("r", "Roman"),
1232 ("mi", "Math italic"),
1233 ("u", "Unslanted italic"),
1235 ("cc", "Small caps"),
1236 ("ex", "Math extension"),
1241 for (k
, v
) in prefixes
:
1242 if re
.search (k
, filename
):
1244 filename
= re
.sub (k
, '', filename
)
1246 prefixes
= [("b", "Bold"),
1249 for (k
, v
) in prefixes
:
1250 if re
.search (k
, filename
):
1252 filename
= re
.sub (k
, '', filename
)
1254 prefixes
= [("c", "Condensed"),
1257 for (k
, v
) in prefixes
:
1258 if re
.search (k
, filename
):
1260 filename
= re
.sub (k
, '', filename
)
1262 fontinfo
['ItalicAngle'] = 0
1263 if re
.search ('[Ii]talic', shape
) or re
.search ('[Oo]blique', shape
):
1265 if re
.search ("Sans", family
):
1268 fontinfo
["ItalicAngle"] = a
1270 fontinfo
['Weight'] = weight
1271 fontinfo
['FamilyName'] = family
1272 full
= '%s %s %s %s %dpt' \
1273 % (family
, shape
, weight
, stretch
, design_size
)
1274 full
= re
.sub (" +", ' ', full
)
1276 fontinfo
['FontName'] = derive_font_name (family
, full
)
1277 fontinfo
['FullName'] = full
1282 def guess_fontinfo (filename
):
1284 'FontName': filename
,
1285 'FamilyName': filename
,
1286 'Weight': 'Regular',
1289 'isFixedPitch' : 'false',
1290 'FullName': filename
,
1293 if re
.search ('^cm', filename
):
1294 fi
.update (cm_guess_font_info (filename
, fi
))
1295 elif re
.search ("^ec", filename
):
1296 fi
.update (ec_guess_font_info (filename
, fi
))
1297 elif options
.read_afm
:
1300 afmfile
= find_file (filename
+ '.afm')
1303 afmfile
= os
.path
.abspath (afmfile
)
1304 afm_struct
= afm
.read_afm_file (afmfile
)
1305 fi
.update (afm_struct
.__dict
__)
1308 sys
.stderr
.write ("Warning: no extra font information for this font.\n"
1309 + "Consider writing a XX_guess_font_info() routine.\n")
1313 def do_file (filename
):
1314 encoding_file
= options
.encoding_file
1316 include_dirs
= options
.include_dirs
1317 include_dirs
.append (origdir
)
1319 basename
= strip_extension (filename
, '.mf')
1320 progress (_ ("Font `%s'..." % basename
))
1324 if encoding_file
and not os
.path
.exists (encoding_file
):
1325 encoding_file
= find_file (encoding_file
)
1327 encoding_file
= os
.path
.abspath (encoding_file
)
1330 if options
.tfm_file
:
1331 options
.tfm_file
= os
.path
.abspath (options
.tfm_file
)
1333 ## must change dir before calling mktextfm.
1336 progress ('Temporary directory is `%s\'\n' % temp_dir
)
1338 if not options
.tfm_file
:
1339 options
.tfm_file
= popen ("mktextfm %s 2>/dev/null" % shell_escape_filename (basename
)).read ()
1340 if options
.tfm_file
:
1341 options
.tfm_file
= options
.tfm_file
.strip ()
1342 options
.tfm_file
= os
.path
.abspath (options
.tfm_file
)
1344 if not options
.tfm_file
:
1345 error (_ ("Can not find a TFM file to match `%s'") % basename
)
1347 metric
= tfm
.read_tfm_file (options
.tfm_file
)
1349 fontinfo
= guess_fontinfo (basename
)
1350 fontinfo
.update (options
.font_info
)
1352 if not encoding_file
:
1353 codingfile
= 'tex256.enc'
1354 if not coding_dict
.has_key (metric
.coding
):
1355 sys
.stderr
.write ("Unknown encoding `%s'; assuming tex256.\n" % metric
.coding
)
1357 codingfile
= coding_dict
[metric
.coding
]
1359 encoding_file
= find_file (codingfile
)
1360 if not encoding_file
:
1361 error (_ ("can't find file `%s'" % codingfile
))
1363 (enc_name
, encoding
) = read_encoding (encoding_file
)
1365 if not len (options
.glyphs
):
1366 options
.glyphs
= range (0, len (encoding
))
1368 if not options
.gffile
:
1370 base
= gen_pixel_font (basename
, metric
, options
.magnification
)
1371 options
.gffile
= base
+ 'gf'
1373 options
.gffile
= find_file (options
.gffile
)
1375 # the heart of the program:
1376 trace_font (basename
, options
.gffile
, metric
, options
.glyphs
, encoding
,
1377 options
.magnification
, fontinfo
)
1379 make_outputs (basename
, options
.formats
, encoding
)
1380 for format
in options
.formats
:
1381 shutil
.copy2 (basename
+ '.' + format
, origdir
)
1391 backend_options
= getenv ('MFTRACE_BACKEND_OPTIONS', '')
1393 files
= parse_command_line ()
1394 identify (sys
.stderr
)
1396 for filename
in files
:
1398 sys
.exit (exit_value
)
1400 if __name__
=='__main__':