Debian Codegraph @

texk/texlive/linked_scripts/mf2pt1/mf2pt1.pl

raw
1 #! /usr/bin/env perl
2
3 ##################################################
4 # Convert stylized Metafont to PostScript Type 1 #
5 # By Scott Pakin <[email protected]> #
6 ##################################################
7
8 ########################################################################
9 # mf2pt1 #
10 # Copyright (C) 2005-2024 Scott Pakin #
11 # #
12 # This program may be distributed and/or modified under the conditions #
13 # of the LaTeX Project Public License, either version 1.3c of this #
14 # license or (at your option) any later version. #
15 # #
16 # The latest version of this license is in: #
17 # #
18 # http://www.latex-project.org/lppl.txt #
19 # #
20 # and version 1.3c or later is part of all distributions of LaTeX #
21 # version 2006/05/20 or later. #
22 ########################################################################
23
24 our $VERSION = "2.8"; # mf2pt1 version number
25 require 5.6.1; # I haven't tested mf2pt1 with older Perl versions
26
27 use Cwd;
28 use File::Basename;
29 use File::Spec;
30 use Getopt::Long;
31 use Pod::Usage;
32 use Math::Trig;
33 use warnings;
34 use strict;
35
36 # Define some common encoding vectors.
37 my @standardencoding =
38 ((map {"_a$_"} (0..31)),
39 qw (space exclam quotedbl numbersign dollar percent ampersand
40 quoteright parenleft parenright asterisk plus comma hyphen
41 period slash zero one two three four five six seven eight
42 nine colon semicolon less equal greater question at A B C D E
43 F G H I J K L M N O P Q R S T U V W X Y Z bracketleft
44 backslash bracketright asciicircum underscore quoteleft a b c
45 d e f g h i j k l m n o p q r s t u v w x y z braceleft bar
46 braceright asciitilde),
47 (map {"_a$_"} (127..160)),
48 qw (exclamdown cent sterling fraction yen florin section currency
49 quotesingle quotedblleft guillemotleft guilsinglleft
50 guilsinglright fi fl _a176 endash dagger daggerdbl
51 periodcentered _a181 paragraph bullet quotesinglbase
52 quotedblbase quotedblright guillemotright ellipsis
53 perthousand _a190 questiondown _a192 grave acute circumflex
54 tilde macron breve dotaccent dieresis _a201 ring cedilla
55 _a204 hungarumlaut ogonek caron emdash),
56 (map {"_a$_"} (209..224)),
57 qw (AE _a226 ordfeminine _a228 _a229 _a230 _a231 Lslash Oslash OE
58 ordmasculine _a236 _a237 _a238 _a239 _a240 ae _a242 _a243
59 _a244 dotlessi _a246 _a247 lslash oslash oe germandbls _a252
60 _a253 _a254 _a255));
61 my @isolatin1encoding =
62 ((map {"_a$_"} (0..31)),
63 qw (space exclam quotedbl numbersign dollar percent ampersand
64 quoteright parenleft parenright asterisk plus comma minus
65 period slash zero one two three four five six seven eight
66 nine colon semicolon less equal greater question at A B C D E
67 F G H I J K L M N O P Q R S T U V W X Y Z bracketleft
68 backslash bracketright asciicircum underscore quoteleft a b c
69 d e f g h i j k l m n o p q r s t u v w x y z braceleft bar
70 braceright asciitilde),
71 (map {"_a$_"} (128..143)),
72 qw (dotlessi grave acute circumflex tilde macron breve dotaccent
73 dieresis _a153 ring cedilla _a156 hungarumlaut ogonek
74 caron space exclamdown cent sterling currency yen brokenbar
75 section dieresis copyright ordfeminine guillemotleft
76 logicalnot hyphen registered macron degree plusminus
77 twosuperior threesuperior acute mu paragraph periodcentered
78 cedilla onesuperior ordmasculine guillemotright onequarter
79 onehalf threequarters questiondown Agrave Aacute Acircumflex
80 Atilde Adieresis Aring AE Ccedilla Egrave Eacute Ecircumflex
81 Edieresis Igrave Iacute Icircumflex Idieresis Eth Ntilde
82 Ograve Oacute Ocircumflex Otilde Odieresis multiply Oslash
83 Ugrave Uacute Ucircumflex Udieresis Yacute Thorn germandbls
84 agrave aacute acircumflex atilde adieresis aring ae ccedilla
85 egrave eacute ecircumflex edieresis igrave iacute icircumflex
86 idieresis eth ntilde ograve oacute ocircumflex otilde
87 odieresis divide oslash ugrave uacute ucircumflex udieresis
88 yacute thorn ydieresis));
89 my @ot1encoding =
90 qw (Gamma Delta Theta Lambda Xi Pi Sigma Upsilon Phi
91 Psi Omega ff fi fl ffi ffl dotlessi dotlessj grave acute caron
92 breve macron ring cedilla germandbls ae oe oslash AE OE Oslash
93 suppress exclam quotedblright numbersign dollar percent
94 ampersand quoteright parenleft parenright asterisk plus comma
95 hyphen period slash zero one two three four five six seven
96 eight nine colon semicolon exclamdown equal questiondown
97 question at A B C D E F G H I J K L M N O P Q R S T U V W X Y
98 Z bracketleft quotedblleft bracketright circumflex dotaccent
99 quoteleft a b c d e f g h i j k l m n o p q r s t u v w x y z
100 endash emdash hungarumlaut tilde dieresis);
101 my @t1encoding =
102 qw (grave acute circumflex tilde dieresis hungarumlaut ring caron
103 breve macron dotaccent cedilla ogonek quotesinglbase
104 guilsinglleft guilsinglright quotedblleft quotedblright
105 quotedblbase guillemotleft guillemotright endash emdash cwm
106 perthousand dotlessi dotlessj ff fi fl ffi ffl space exclam
107 quotedbl numbersign dollar percent ampersand quoteright
108 parenleft parenright asterisk plus comma hyphen period slash
109 zero one two three four five six seven eight nine colon
110 semicolon less equal greater question at A B C D E F G H I J K L
111 M N O P Q R S T U V W X Y Z bracketleft backslash bracketright
112 asciicircum underscore quoteleft a b c d e f g h i j k l m n o p
113 q r s t u v w x y z braceleft bar braceright asciitilde
114 sfthyphen Abreve Aogonek Cacute Ccaron Dcaron Ecaron Eogonek
115 Gbreve Lacute Lcaron Lslash Nacute Ncaron Eng Ohungarumlaut
116 Racute Rcaron Sacute Scaron Scedilla Tcaron Tcedilla
117 Uhungarumlaut Uring Ydieresis Zacute Zcaron Zdotaccent IJ
118 Idotaccent dcroat section abreve aogonek cacute ccaron dcaron
119 ecaron eogonek gbreve lacute lcaron lslash nacute ncaron eng
120 ohungarumlaut racute rcaron sacute scaron scedilla tcaron
121 tcedilla uhungarumlaut uring ydieresis zacute zcaron zdotaccent
122 ij exclamdown questiondown sterling Agrave Aacute Acircumflex
123 Atilde Adieresis Aring AE Ccedilla Egrave Eacute Ecircumflex
124 Edieresis Igrave Iacute Icircumflex Idieresis Eth Ntilde Ograve
125 Oacute Ocircumflex Otilde Odieresis OE Oslash Ugrave Uacute
126 Ucircumflex Udieresis Yacute Thorn SS agrave aacute acircumflex
127 atilde adieresis aring ae ccedilla egrave eacute ecircumflex
128 edieresis igrave iacute icircumflex idieresis eth ntilde ograve
129 oacute ocircumflex otilde odieresis oe oslash ugrave uacute
130 ucircumflex udieresis yacute thorn germandbls);
131
132 # Define font parameters that the user can override.
133 my $fontversion;
134 my $creationdate;
135 my $comment;
136 my $familyname;
137 my $weight;
138 my $fullname;
139 my $fixedpitch;
140 my $italicangle;
141 my $underlinepos;
142 my $underlinethick;
143 my $fontname;
144 my $uniqueID;
145 my $designsize;
146 my ($mffile, $pt1file, $pfbfile, $ffscript);
147 my $encoding;
148 my $rounding;
149 my $bpppix;
150
151 # Define all of our other global variables.
152 my $progname = basename $0, ".pl";
153 my $mag;
154 my @fontbbox;
155 my @charbbox;
156 my @charwd;
157 my @glyphname;
158 my @charfiles;
159 my $filebase;
160 my $filedir;
161 my $filenoext;
162 my $versionmsg = "mf2pt1 version $VERSION
163
164 Copyright (C) 2005-2024 Scott Pakin
165
166 This program may be distributed and/or modified under the conditions
167 of the LaTeX Project Public License, either version 1.3c of this
168 license or (at your option) any later version.
169
170 The latest version of this license is in:
171
172 http://www.latex-project.org/lppl.txt
173
174 and version 1.3c or later is part of all distributions of LaTeX
175 version 2006/05/20 or later.
176 ";
177
178
179 ######################################################################
180
181 # The routines to compute the fractional approximation of a real number
182 # are heavily based on code posted by Ben Tilly
183 # <http://www.perlmonks.org/?node_id=26179> on Nov 16th, 2000, to the
184 # PerlMonks list. See <http://www.perlmonks.org/index.pl?node_id=41961>.
185
186
187 # Takes numerator/denominator pairs.
188 # Returns a PS fraction string representation (with a trailing space).
189 sub frac_string (@)
190 {
191 my $res = "";
192
193 while (@_) {
194 my $n = shift;
195 my $d = shift;
196 $res .= $n . " ";
197 $res .= $d . " div " if $d > 1;
198 }
199
200 return $res;
201 }
202
203
204 # Takes a number.
205 # Returns a numerator and denominator with the smallest denominator
206 # so that the difference of the resulting fraction to the number is
207 # smaller or equal to $rounding.
208 sub frac_approx ($)
209 {
210 my $num = shift;
211 my $f = ret_frac_iter ($num);
212
213 while (1) {
214 my ($n, $m) = $f->();
215 my $approx = $n / $m;
216 my $delta = abs ($num - $approx);
217 return ($n, $m) if ($delta <= $rounding);
218 }
219 }
220
221
222 # Takes a number, returns the best integer approximation and (in list
223 # context) the error.
224 sub best_int ($)
225 {
226 my $x = shift;
227 my $approx = sprintf '%.0f', $x;
228 if (wantarray) {
229 return ($approx, $x - $approx);
230 }
231 else {
232 return $approx;
233 }
234 }
235
236
237 # Takes a numerator and denominator, in scalar context returns
238 # the best fraction describing them, in list the numerator and
239 # denominator.
240 sub frac_standard ($$)
241 {
242 my $n = best_int(shift);
243 my $m = best_int(shift);
244 my $k = gcd($n, $m);
245 $n /= $k;
246 $m /= $k;
247 if ($m < 0) {
248 $n *= -1;
249 $m *= -1;
250 }
251 if (wantarray) {
252 return ($n, $m);
253 }
254 else {
255 return "$n/$m";
256 }
257 }
258
259
260 # Euclidean algorithm for calculating a GCD.
261 # Takes two integers, returns the greatest common divisor.
262 sub gcd ($$)
263 {
264 my ($n, $m) = @_;
265 while ($m) {
266 my $k = $n % $m;
267 ($n, $m) = ($m, $k);
268 }
269 return $n;
270 }
271
272
273 # Takes a list of terms in a continued fraction, and converts it
274 # into a fraction.
275 sub ints_to_frac (@)
276 {
277 my ($n, $m) = (0, 1); # Start with 0
278 while (@_) {
279 my $k = pop;
280 if ($n) {
281 # Want frac for $k + 1/($n/$m)
282 ($n, $m) = frac_standard($k*$n + $m, $n);
283 }
284 else {
285 # Want $k
286 ($n, $m) = frac_standard($k, 1);
287 }
288 }
289 return frac_standard($n, $m);
290 }
291
292
293 # Takes a number, returns an anon sub which iterates through a set of
294 # fractional approximations that converges very quickly to the number.
295 sub ret_frac_iter ($)
296 {
297 my $x = shift;
298 my $term_iter = ret_next_term_iter($x);
299 my @ints;
300 return sub {
301 push @ints, $term_iter->();
302 return ints_to_frac(@ints);
303 }
304 }
305
306
307 # Terms of a continued fraction converging on that number.
308 sub ret_next_term_iter ($)
309 {
310 my $x = shift;
311 return sub {
312 (my $n, $x) = best_int($x);
313 if (0 != $x) {
314 $x = 1/$x;
315 }
316 return $n;
317 }
318 }
319
320 ######################################################################
321
322 # Round a number to the nearest integer.
323 sub round ($)
324 {
325 return int($_[0] + 0.5*($_[0] <=> 0));
326 }
327
328
329 # Round a number to a given precision.
330 sub prec ($)
331 {
332 return round ($_[0] / $rounding) * $rounding;
333 }
334
335
336 # Set a variable's value to the first defined value in the given list.
337 # If the variable was not previously defined and no value in the list
338 # is defined, do nothing.
339 sub assign_default (\$@)
340 {
341 my $varptr = shift; # Pointer to variable to define
342 return if defined $$varptr && $$varptr ne "UNSPECIFIED";
343 foreach my $val (@_) {
344 next if !defined $val;
345 $$varptr = $val;
346 return;
347 }
348 }
349
350
351 # This function is taken unchanged from the Parse::CommandLine package
352 # on CPAN. It gets included here to avoid a dependency on a module
353 # that is rarely contained in distributions.
354
355 sub parse_command_line {
356 my $str = shift;
357
358 $str =~ s/\A\s+//ms;
359 $str =~ s/\s+\z//ms;
360
361 my @argv;
362 my $buf;
363 my $escaped;
364 my $double_quoted;
365 my $single_quoted;
366
367 for my $char (split //, $str) {
368 if ($escaped) {
369 $buf .= $char;
370 $escaped = undef;
371 next;
372 }
373
374 if ($char eq '\\') {
375 if ($single_quoted) {
376 $buf .= $char;
377 }
378 else {
379 $escaped = 1;
380 }
381 next;
382 }
383
384 if ($char =~ /\s/) {
385 if ($single_quoted || $double_quoted) {
386 $buf .= $char;
387 }
388 else {
389 push @argv, $buf if defined $buf;
390 undef $buf;
391 }
392 next;
393 }
394
395 if ($char eq '"') {
396 if ($single_quoted) {
397 $buf .= $char;
398 next;
399 }
400 $double_quoted = !$double_quoted;
401 next;
402 }
403
404 if ($char eq "'") {
405 if ($double_quoted) {
406 $buf .= $char;
407 next;
408 }
409 $single_quoted = !$single_quoted;
410 next;
411 }
412
413 $buf .= $char;
414 }
415 push @argv, $buf if defined $buf;
416
417 if ($escaped || $single_quoted || $double_quoted) {
418 die 'invalid command line string';
419 }
420
421 @argv;
422 }
423
424
425 # Print and execute a shell command. An environment variable with the
426 # same name as the command overrides the command name; it can also be
427 # used to insert additional command-line parameters. Return 1 on
428 # success, 0 on failure. Optionally abort if the command fails, based
429 # on the first argument to execute_command.
430 sub execute_command ($@)
431 {
432 my $abort_on_failure = shift;
433 my @command = @_;
434 my $env = $ENV{uc $command[0]};
435 if ($env) {
436 my @argv = parse_command_line ($env);
437 splice @command, 0, 1, @argv;
438 }
439 my $prettyargs = join (" ", map {/[\\ ]/ ? "'$_'" : $_} @command);
440 print "Invoking \"$prettyargs\"...\n";
441 my $result = system @command;
442 die "${progname}: \"$prettyargs\" failed ($!)\n" if $result && $abort_on_failure;
443 return !$result;
444 }
445
446
447 # Prepend a directory to a TeX variable.
448 sub prepend_directory($$$)
449 {
450 my ($dir, $varname, $ftype) = @_;
451 my $old_value = `kpsewhich --show-path=$ftype`;
452 die "${progname}: failed to run kpathsea ($!)" if $?;
453 chomp $old_value;
454 $ENV{$varname} = "$dir:$old_value";
455 }
456
457
458 # Output the font header.
459 sub output_header ()
460 {
461 # Show the initial boilerplate.
462 print OUTFILE <<"ENDHEADER";
463 %!FontType1-1.0: $fontname $fontversion
464 %%CreationDate: $creationdate
465 % Font converted to Type 1 by mf2pt1, written by Scott Pakin.
466 11 dict begin
467 /FontInfo 11 dict dup begin
468 /version ($fontversion) readonly def
469 /Notice ($comment) readonly def
470 /FullName ($fullname) readonly def
471 /FamilyName ($familyname) readonly def
472 /Weight ($weight) readonly def
473 /ItalicAngle $italicangle def
474 /isFixedPitch $fixedpitch def
475 /UnderlinePosition $underlinepos def
476 /UnderlineThickness $underlinethick def
477 end readonly def
478 /FontName /$fontname def
479 ENDHEADER
480
481 # If we're not using an encoding that PostScript knows about, then
482 # create an encoding vector.
483 if ($encoding==\@standardencoding) {
484 print OUTFILE "/Encoding StandardEncoding def\n";
485 }
486 else {
487 print OUTFILE "/Encoding 256 array\n";
488 print OUTFILE "0 1 255 {1 index exch /.notdef put} for\n";
489 foreach my $charnum (0 .. $#{$encoding}) {
490 if ($encoding->[$charnum] && $encoding->[$charnum]!~/^_a\d+$/) {
491 print OUTFILE "dup $charnum /$encoding->[$charnum] put\n";
492 }
493 }
494 print OUTFILE "readonly def\n";
495 }
496
497 # Show the final boilerplate.
498 print OUTFILE "/UniqueID $uniqueID def\n" if defined $uniqueID;
499 print OUTFILE <<"ENDHEADER";
500 /PaintType 0 def
501 /FontType 1 def
502 /FontMatrix [0.001 0 0 0.001 0 0] readonly def
503 /FontBBox{@fontbbox}readonly def
504 currentdict end
505 currentfile eexec
506 dup /Private 5 dict dup begin
507 /RD{string currentfile exch readstring pop}executeonly def
508 /ND{noaccess def}executeonly def
509 /NP{noaccess put}executeonly def
510 ENDHEADER
511 }
512
513
514 # Use MetaPost to generate one PostScript file per character. We
515 # calculate the font bounding box from these characters and store them
516 # in @fontbbox. If the input parameter is 1, set other font
517 # parameters, too.
518 sub get_bboxes ($)
519 {
520 execute_command 1, ("mpost", "-mem=mf2pt1", "-progname=mpost",
521 "\\mode:=localfont; mag:=$mag; bpppix $bpppix; nonstopmode; input $mffile");
522 opendir (CURDIR, ".") || die "${progname}: $! ($filedir)\n";
523 @charfiles = sort
524 { ($a=~ /\.(\d+)$/)[0] <=> ($b=~ /\.(\d+)$/)[0] }
525 grep /^$filebase.*\.\d+$/, readdir(CURDIR);
526 close CURDIR;
527 @fontbbox = (1000000, 1000000, -1000000, -1000000);
528 foreach my $psfile (@charfiles) {
529 # Read the character number from the output file's extension.
530 $psfile =~ /\.(\d+)$/;
531 my $charnum = $1;
532
533 # Process in turn each line of the current PostScript file.
534 my $havebbox = 0;
535 open (PSFILE, "<$psfile") || die "${progname}: $! ($psfile)\n";
536 while (<PSFILE>) {
537 my @tokens = split " ";
538 if ($tokens[0] eq "%%BoundingBox:") {
539 # Store the MetaPost-produced bounding box, just in case
540 # the given font doesn't use beginchar.
541 @tokens = ("%", "MF2PT1:", "glyph_dimensions", @tokens[1..4]);
542 $havebbox--;
543 }
544 next if $#tokens<1 || $tokens[1] ne "MF2PT1:";
545
546 # Process a "special" inserted into the generated PostScript.
547 MF2PT1_CMD:
548 {
549 # glyph_dimensions llx lly urx ury -- specified glyph dimensions
550 $tokens[2] eq "glyph_dimensions" && do {
551 my @bbox = @tokens[3..6];
552 $fontbbox[0]=$bbox[0] if $bbox[0]<$fontbbox[0];
553 $fontbbox[1]=$bbox[1] if $bbox[1]<$fontbbox[1];
554 $fontbbox[2]=$bbox[2] if $bbox[2]>$fontbbox[2];
555 $fontbbox[3]=$bbox[3] if $bbox[3]>$fontbbox[3];
556 $charbbox[$charnum] = \@bbox;
557 $havebbox++;
558 last MF2PT1_CMD;
559 };
560
561 # If all we want is the bounding box, exit the loop now.
562 last MF2PT1_CMD if !$_[0];
563
564 # glyph_name name -- glyph name
565 $tokens[2] eq "glyph_name" && do {
566 $glyphname[$charnum] = $tokens[3];
567 last MF2PT1_CMD;
568 };
569
570 # charwd wd -- character width as in TFM
571 $tokens[2] eq "charwd" && do {
572 $charwd[$charnum] = $tokens[3];
573 last MF2PT1_CMD;
574 };
575
576 # font_identifier name -- full font name
577 $tokens[2] eq "font_identifier" && do {
578 $fullname = $tokens[3];
579 last MF2PT1_CMD;
580 };
581
582 # font_size number -- font design size (pt, not bp)
583 $tokens[2] eq "font_size" && $tokens[3] && do {
584 $designsize = $tokens[3] * 72 / 72.27;
585 last MF2PT1_CMD;
586 };
587
588 # font_slant number -- italic amount
589 $tokens[2] eq "font_slant" && do {
590 $italicangle = 0 + rad2deg (atan(-$tokens[3]));
591 last MF2PT1_CMD;
592 };
593
594 # font_coding_scheme string -- font encoding
595 $tokens[2] eq "font_coding_scheme" && do {
596 $encoding = $tokens[3];
597 last MF2PT1_CMD;
598 };
599
600 # font_version string -- font version number (xxx.yyy)
601 $tokens[2] eq "font_version" && do {
602 $fontversion = $tokens[3];
603 last MF2PT1_CMD;
604 };
605
606 # font_comment string -- font comment notice
607 $tokens[2] eq "font_comment" && do {
608 $comment = join (" ", @tokens[3..$#tokens]);
609 last MF2PT1_CMD;
610 };
611
612 # font_family string -- font family name
613 $tokens[2] eq "font_family" && do {
614 $familyname = $tokens[3];
615 last MF2PT1_CMD;
616 };
617
618 # font_weight string -- font weight (e.g., "Book" or "Heavy")
619 $tokens[2] eq "font_weight" && do {
620 $weight = $tokens[3];
621 last MF2PT1_CMD;
622 };
623
624 # font_fixed_pitch number -- fixed width font (0=false, 1=true)
625 $tokens[2] eq "font_fixed_pitch" && do {
626 $fixedpitch = $tokens[3];
627 last MF2PT1_CMD;
628 };
629
630 # font_underline_position number -- vertical underline position
631 $tokens[2] eq "font_underline_position" && do {
632 # We store $underlinepos in points and later
633 # scale it by 1000/$designsize.
634 $underlinepos = $tokens[3];
635 last MF2PT1_CMD;
636 };
637
638 # font_underline_thickness number -- thickness of underline
639 $tokens[2] eq "font_underline_thickness" && do {
640 # We store $underlinethick in points and later
641 # scale it by 1000/$designsize.
642 $underlinethick = $tokens[3];
643 last MF2PT1_CMD;
644 };
645
646 # font_name string -- font name
647 $tokens[2] eq "font_name" && do {
648 $fontname = $tokens[3];
649 last MF2PT1_CMD;
650 };
651
652 # font_unique_id number (as string) -- globally unique font ID
653 $tokens[2] eq "font_unique_id" && do {
654 $uniqueID = 0+$tokens[3];
655 last MF2PT1_CMD;
656 };
657 }
658 }
659 close PSFILE;
660 if (!$havebbox) {
661 warn "${progname}: No beginchar in character $charnum; glyph dimensions are probably incorrect\n";
662 }
663 }
664 }
665
666
667 # Convert ordinary, MetaPost-produced PostScript files into Type 1
668 # font programs.
669 sub output_font_programs ()
670 {
671 # Iterate over all the characters. We convert each one, line by
672 # line and token by token.
673 print "Converting PostScript graphics to Type 1 font programs...\n";
674 foreach my $psfile (@charfiles) {
675 # Initialize the font program.
676 $psfile =~ /\.(\d+)$/;
677 my $charnum = $1;
678 my $gname = $glyphname[$charnum] || $encoding->[$charnum];
679 my @fontprog;
680 push @fontprog, ("/$gname {",
681 frac_string (frac_approx ($charbbox[$charnum]->[0]),
682 frac_approx ($charbbox[$charnum]->[2]))
683 . "hsbw");
684 my ($cpx, $cpy) =
685 ($charbbox[$charnum]->[0], 0); # Current point (PostScript)
686
687 # Iterate over every line in the current file.
688 open (PSFILE, "<$psfile") || die "${progname}: $! ($psfile)\n";
689 while (my $oneline=<PSFILE>) {
690 next if $oneline=~/^\%/;
691 next if $oneline=~/set/; # Fortunately, "set" never occurs on "good" lines.
692 my @arglist; # Arguments to current PostScript function
693
694 # Iterate over every token in the current line.
695 TOKENLOOP:
696 foreach my $token (split " ", $oneline) {
697 # Number: Round and push on the argument list.
698 $token =~ /^[-.\d]+$/ && do {
699 push @arglist, prec ($&);
700 next TOKENLOOP;
701 };
702
703 # curveto: Convert to vhcurveto, hvcurveto, or rrcurveto.
704 $token eq "curveto" && do {
705 my ($dx1, $dy1) = ($arglist[0] - $cpx,
706 $arglist[1] - $cpy);
707 my ($dx1n, $dx1d) = frac_approx ($dx1);
708 my ($dy1n, $dy1d) = frac_approx ($dy1);
709 $cpx += $dx1n / $dx1d;
710 $cpy += $dy1n / $dy1d;
711
712 my ($dx2, $dy2) = ($arglist[2] - $cpx,
713 $arglist[3] - $cpy);
714 my ($dx2n, $dx2d) = frac_approx ($dx2);
715 my ($dy2n, $dy2d) = frac_approx ($dy2);
716 $cpx += $dx2n / $dx2d;
717 $cpy += $dy2n / $dy2d;
718
719 my ($dx3, $dy3) = ($arglist[4] - $cpx,
720 $arglist[5] - $cpy);
721 my ($dx3n, $dx3d) = frac_approx ($dx3);
722 my ($dy3n, $dy3d) = frac_approx ($dy3);
723 $cpx += $dx3n / $dx3d;
724 $cpy += $dy3n / $dy3d;
725
726 if (!$dx1n && !$dy3n) {
727 push @fontprog, frac_string ($dy1n, $dy1d,
728 $dx2n, $dx2d,
729 $dy2n, $dy2d,
730 $dx3n, $dx3d)
731 . "vhcurveto";
732 }
733 elsif (!$dy1n && !$dx3n) {
734 push @fontprog, frac_string ($dx1n, $dx1d,
735 $dx2n, $dx2d,
736 $dy2n, $dy2d,
737 $dy3n, $dy3d)
738 . "hvcurveto";
739 }
740 else {
741 push @fontprog, frac_string ($dx1n, $dx1d,
742 $dy1n, $dy1d,
743 $dx2n, $dx2d,
744 $dy2n, $dy2d,
745 $dx3n, $dx3d,
746 $dy3n, $dy3d)
747 . "rrcurveto";
748 }
749 next TOKENLOOP;
750 };
751
752 # lineto: Convert to vlineto, hlineto, or rlineto.
753 $token eq "lineto" && do {
754 my ($dx, $dy) = ($arglist[0] - $cpx,
755 $arglist[1] - $cpy);
756 my ($dxn, $dxd) = frac_approx ($dx);
757 my ($dyn, $dyd) = frac_approx ($dy);
758 $cpx += $dxn / $dxd;
759 $cpy += $dyn / $dyd;
760
761 if (!$dxn) {
762 push @fontprog, frac_string ($dyn, $dyd)
763 . "vlineto" if $dyn;
764 }
765 elsif (!$dyn) {
766 push @fontprog, frac_string ($dxn, $dxd)
767 . "hlineto";
768 }
769 else {
770 push @fontprog, frac_string ($dxn, $dxd, $dyn, $dyd)
771 . "rlineto";
772 }
773 next TOKENLOOP;
774 };
775
776 # moveto: Convert to vmoveto, hmoveto, or rmoveto.
777 $token eq "moveto" && do {
778 my ($dx, $dy) = ($arglist[0] - $cpx,
779 $arglist[1] - $cpy);
780 my ($dxn, $dxd) = frac_approx ($dx);
781 my ($dyn, $dyd) = frac_approx ($dy);
782 $cpx += $dxn / $dxd;
783 $cpy += $dyn / $dyd;
784
785 if (!$dxn) {
786 push @fontprog, frac_string ($dyn, $dyd)
787 . "vmoveto";
788 }
789 elsif (!$dyn) {
790 push @fontprog, frac_string ($dxn, $dxd)
791 . "hmoveto";
792 }
793 else {
794 push @fontprog, frac_string ($dxn, $dxd, $dyn, $dyd)
795 . "rmoveto";
796 }
797 next TOKENLOOP;
798 };
799
800 # closepath: Output as is.
801 $token eq "closepath" && do {
802 push @fontprog, $token;
803 next TOKENLOOP;
804 };
805 }
806 }
807 close PSFILE;
808 push @fontprog, ("endchar",
809 "} ND");
810 print OUTFILE join ("\n\t", @fontprog), "\n";
811 }
812 }
813
814
815 # Output the final set of code for the Type 1 font.
816 sub output_trailer ()
817 {
818 print OUTFILE <<"ENDTRAILER";
819 /.notdef {
820 0 @{[frac_string (frac_approx ($fontbbox[2] - $fontbbox[0]))]} hsbw
821 endchar
822 } ND
823 end
824 end
825 readonly put
826 noaccess put
827 dup/FontName get exch definefont pop
828 mark currentfile closefile
829 cleartomark
830 ENDTRAILER
831 }
832
833 ######################################################################
834
835 # Parse the command line. Asterisks in the following represents
836 # commands also defined by Plain Metafont.
837 my %opthash = ();
838 GetOptions (\%opthash,
839 "fontversion=s", # font_version
840 "comment=s", # font_comment
841 "family=s", # font_family
842 "weight=s", # font_weight
843 "fullname=s", # font_identifier (*)
844 "fixedpitch!", # font_fixed_pitch
845 "italicangle=f", # font_slant (*)
846 "underpos=f", # font_underline_position
847 "underthick=f", # font_underline_thickness
848 "name=s", # font_name
849 "uniqueid=i", # font_unique_id
850 "designsize=f", # font_size (*)
851 "encoding=s", # font_coding_scheme (*)
852 "rounding=f",
853 "bpppix=f",
854 "ffscript=s",
855 "save-temps!",
856 "output-dir=s",
857 "h|help",
858 "V|version") || pod2usage(2);
859 if (defined $opthash{"h"}) {
860 pod2usage(-verbose => 1,
861 -output => \*STDOUT, # Bug workaround for Pod::Usage
862 -exitval => "NOEXIT");
863 print "Please e-mail bug reports to scott+mf\@pakin.org.\n";
864 exit 1;
865 }
866 do {print $versionmsg; exit 1} if defined $opthash{"V"};
867 pod2usage(2) if $#ARGV != 0;
868
869 # Extract the filename from the command line.
870 $mffile = File::Spec->rel2abs($ARGV[0]);
871 my @fileparts = fileparse $mffile, ".mf";
872 $filebase = $fileparts[0];
873 $filedir = $fileparts[1];
874 $filenoext = File::Spec->catfile ($filedir, $filebase);
875 $pt1file = $filebase . ".pt1";
876 $pfbfile = $filebase . ".pfb";
877
878 # If --output-dir was specified, switch to that directory, but point
879 # Metapost to the current directory.
880 my $outdir = $opthash{"output-dir"};
881 if ($outdir) {
882 my $here = getcwd();
883 prepend_directory $here, "MPINPUTS", "mp";
884 prepend_directory $here, "MFINPUTS", "mf";
885 chdir $outdir or die "${progname}: failed to switch to $outdir ($!)\n";
886 }
887
888 # Make our first pass through the input, to set values for various options.
889 assign_default $bpppix, $opthash{bpppix}, 0.02;
890 $mag = 100; # Get a more precise bounding box.
891 get_bboxes(1); # This might set $designsize.
892
893 # Sanity-check the specified precision.
894 assign_default $rounding, $opthash{rounding}, 1;
895 if ($rounding<=0.0 || $rounding>1.0) {
896 die sprintf "%s: Invalid rounding amount \"%g\"; value must be a positive number no greater than 1.0\n", $progname, $rounding;
897 }
898
899 # Ensure that every user-definable parameter is assigned a value. The only
900 # exception is the unique ID, as Adobe no longer recommends specifying one.
901 assign_default $fontversion, $opthash{fontversion}, "001.000";
902 assign_default $creationdate, scalar localtime;
903 assign_default $comment, $opthash{comment}, "Font converted to Type 1 by mf2pt1, written by Scott Pakin.";
904 assign_default $weight, $opthash{weight}, "Medium";
905 assign_default $fixedpitch, $opthash{fixedpitch}, 0;
906 assign_default $uniqueID, $opthash{uniqueid};
907 assign_default $designsize, $opthash{designsize};
908 die "${progname}: a design size must be specified in $mffile or on the command line\n" if !defined $designsize;
909 die "${progname}: the design size must be a positive number\n" if $designsize<=0.0;
910 assign_default $underlinepos, $opthash{underpos}, -1;
911 $underlinepos = round(1000*$underlinepos/$designsize);
912 assign_default $underlinethick, $opthash{underthick}, 0.5;
913 $underlinethick = round(1000*$underlinethick/$designsize);
914 assign_default $fullname, $opthash{fullname}, $filebase;
915 assign_default $familyname, $opthash{family}, $fullname;
916 assign_default $italicangle, $opthash{italicangle}, 0;
917 assign_default $fontname, $opthash{name}, "$familyname-$weight";
918 $fontname =~ s/\s//g;
919 assign_default $encoding, $opthash{encoding}, "standard";
920 my $encoding_name = $encoding;
921 ENCODING:
922 {
923 if (-e $encoding) {
924 # Filenames take precedence over built-in encodings.
925 my @enc_array;
926 open (ENCFILE, "<$encoding") || die "${progname}: $! ($encoding)\n";
927 while (my $oneline = <ENCFILE>) {
928 $oneline =~ s/\%.*$//;
929 foreach my $word (split " ", $oneline) {
930 push @enc_array, substr($word, 1) if substr($word, 0, 1) eq "/";
931 }
932 }
933 close ENCFILE;
934 $encoding_name = substr (shift @enc_array, 1);
935 $encoding = \@enc_array;
936 last ENCODING;
937 }
938 $encoding=\@standardencoding, last ENCODING if $encoding eq "standard";
939 $encoding=\@isolatin1encoding, last ENCODING if $encoding eq "isolatin1";
940 $encoding=\@ot1encoding, last ENCODING if $encoding eq "ot1";
941 $encoding=\@t1encoding, last ENCODING if $encoding eq "t1";
942 $encoding=\@glyphname, last ENCODING if $encoding eq "asis";
943 warn "${progname}: Unknown encoding \"$encoding\"; using standard Adobe encoding\n";
944 $encoding=\@standardencoding; # Default to standard encoding
945 }
946 assign_default $fixedpitch, $opthash{fixedpitch}, 0;
947 $fixedpitch = $fixedpitch ? "true" : "false";
948 assign_default $ffscript, $opthash{ffscript};
949
950 # Output the final values of all of our parameters.
951 print "\n";
952 print <<"PARAMVALUES";
953 mf2pt1 is using the following font parameters:
954 font_version: $fontversion
955 font_comment: $comment
956 font_family: $familyname
957 font_weight: $weight
958 font_identifier: $fullname
959 font_fixed_pitch: $fixedpitch
960 font_slant: $italicangle
961 font_underline_position: $underlinepos
962 font_underline_thickness: $underlinethick
963 font_name: $fontname
964 font_size: $designsize (bp)
965 font_coding_scheme: $encoding_name
966 PARAMVALUES
967 ;
968 print " font_unique_id: $uniqueID\n" if defined $uniqueID;
969 print "\n";
970
971 # Scale by a factor of 1000/design size.
972 $mag = 1000.0 / $designsize;
973 get_bboxes(0);
974 print "\n";
975
976 # Output the font in disassembled format.
977 open (OUTFILE, ">$pt1file") || die "${progname}: $! ($pt1file)\n";
978 output_header();
979 printf OUTFILE "2 index /CharStrings %d dict dup begin\n",
980 1+scalar(grep {defined($_)} @charbbox);
981 output_font_programs();
982 output_trailer();
983 close OUTFILE;
984 unlink @charfiles unless $opthash{'save-temps'};
985 print "\n";
986
987 # Convert from the disassembled font format to Type 1 binary format.
988 if (!execute_command 0, ("t1asm", $pt1file, $pfbfile)) {
989 die "${progname}: You'll need either to install t1utils and rerun $progname or find another way to convert $pt1file to $pfbfile\n";
990 exit 1;
991 }
992 print "\n";
993 unlink $pt1file unless $opthash{'save-temps'};
994
995 # Use FontForge to autohint the result.
996 my $user_script = 0; # 1=script file was provided by the user; 0=created here
997 if (defined $ffscript) {
998 # The user provided his own script.
999 $user_script = 1;
1000 }
1001 else {
1002 # Create a FontForge script file.
1003 $ffscript = $filebase . ".pe";
1004 open (FFSCRIPT, ">$ffscript") || die "${progname}: $! ($ffscript)\n";
1005 print FFSCRIPT <<'AUTOHINT';
1006 Open($1);
1007 SelectAll();
1008 RemoveOverlap();
1009 Simplify(0, 2);
1010 CorrectDirection();
1011 AddExtrema(1);
1012 Simplify(0, 2);
1013 RoundToInt();
1014 AutoHint();
1015 Generate($1);
1016 Quit(0);
1017 AUTOHINT
1018 ;
1019 close FFSCRIPT;
1020 }
1021 if (!execute_command 0, ("fontforge", "-script", $ffscript, $pfbfile)) {
1022 warn "${progname}: You'll need to install FontForge if you want $pfbfile autohinted (not required, but strongly recommended)\n";
1023 }
1024 unlink $ffscript if !$user_script && !$opthash{'save-temps'};
1025 print "\n";
1026
1027 # Finish up.
1028 print "*** Successfully generated $pfbfile! ***\n";
1029 exit 0;
1030
1031 ######################################################################
1032
1033 __END__
1034
1035 =head1 NAME
1036
1037 mf2pt1 - produce a PostScript Type 1 font program from a Metafont source
1038
1039
1040 =head1 SYNOPSIS
1041
1042 mf2pt1
1043 [B<--help>]
1044 [B<--version>]
1045 [B<--comment>=I<string>]
1046 [B<--designsize>=I<number>]
1047 [B<--encoding>=I<encoding>]
1048 [B<--family>=I<name>]
1049 [B<-->[B<no>]B<fixedpitch>]
1050 [B<--fontversion>=I<MMM.mmm>]
1051 [B<--fullname>=I<name>]
1052 [B<--italicangle>=I<number>]
1053 [B<--name>=I<name>]
1054 [B<--underpos>=I<number>]
1055 [B<--underthick>=I<number>]
1056 [B<--uniqueid>=I<number>]
1057 [B<--weight>=I<weight>]
1058 [B<--rounding>=I<number>]
1059 [B<--bpppix>=I<number>]
1060 [B<--ffscript>=I<file.pe>]
1061 [B<--save-temps>]
1062 [B<--output-dir>=I<directory>]
1063 I<infile>.mf
1064
1065
1066 =head1 WARNING
1067
1068 The B<mf2pt1> Info file is the main source of documentation for
1069 B<mf2pt1>. This man page is merely a brief summary.
1070
1071
1072 =head1 DESCRIPTION
1073
1074 B<mf2pt1> facilitates producing PostScript Type 1 fonts from a
1075 Metafont source file. It is I<not>, as the name may imply, an
1076 automatic converter of arbitrary Metafont fonts to Type 1 format.
1077 B<mf2pt1> imposes a number of restrictions on the Metafont input. If
1078 these restrictions are met, B<mf2pt1> will produce valid Type 1
1079 output. (Actually, it produces "disassembled" Type 1; the B<t1asm>
1080 program from the B<t1utils> suite will convert this to a true Type 1
1081 font.)
1082
1083 =head2 Usage
1084
1085 mf2pt1 myfont.mf
1086
1087 =head1 OPTIONS
1088
1089 Font parameters are best specified within a Metafont program. If
1090 necessary, though, command-line options can override any of these
1091 parameters. The B<mf2pt1> Info page, the primary source of B<mf2pt1>
1092 documentation, describes the following in greater detail.
1093
1094 =over 4
1095
1096 =item B<--help>
1097
1098 Provide help on B<mf2pt1>'s command-line options.
1099
1100 =item B<--version>
1101
1102 Output the B<mf2pt1> version number, copyright, and license.
1103
1104 =item B<--comment>=I<string>
1105
1106 Include a font comment, usually a copyright notice.
1107
1108 =item B<--designsize>=I<number>
1109
1110 Specify the font design size in points.
1111
1112 =item B<--encoding>=I<encoding>
1113
1114 Designate the font encoding, either the name of a---typically
1115 F<.enc>---file which contains a PostScript font-encoding vector or one
1116 of C<standard> (the default), C<ot1>, C<t1>, or C<isolatin1>.
1117
1118 =item B<--family>=I<name>
1119
1120 Specify the font family.
1121
1122 =item B<--fixedpitch>, B<--nofixedpitch>
1123
1124 Assert that the font uses either monospaced (B<--fixedpitch>) or
1125 proportional (B<--nofixedpitch>) character widths.
1126
1127 =item B<--fontversion>=I<MMM.mmm>
1128
1129 Specify the font's major and minor version number.
1130
1131 =item B<--fullname>=I<name>
1132
1133 Designate the full font name (family plus modifiers).
1134
1135 =item B<--italicangle>=I<number>
1136
1137 Designate the italic angle in degrees counterclockwise from vertical.
1138
1139 =item B<--name>=I<name>
1140
1141 Provide the font name.
1142
1143 =item B<--underpos>=I<number>
1144
1145 Specify the vertical position of the underline in thousandths of the
1146 font height.
1147
1148 =item B<--underthick>=I<number>
1149
1150 Specify the thickness of the underline in thousandths of the font
1151 height.
1152
1153 =item B<--uniqueid>=I<number>
1154
1155 Specify a globally unique font identifier.
1156
1157 =item B<--weight>=I<weight>
1158
1159 Provide a description of the font weight (e.g., ``Heavy'').
1160
1161 =item B<--rounding>=I<number>
1162
1163 Specify the fraction of a font unit (0.0 < I<number> <= 1.0) to which
1164 to round coordinate values [default: 1.0].
1165
1166 =item B<--bpppix>=I<number>
1167
1168 Redefine the number of big points per pixel from 0.02 to I<number>.
1169
1170 =item B<--ffscript>=I<file.pe>
1171
1172 Name a script to pass to FontForge.
1173
1174 =item B<--save-temps>
1175
1176 Do not delete intermediate files (can be useful for debugging).
1177
1178 =item B<--output-dir>=I<directory>
1179
1180 Write all intermediate and output files to directory I<directory>
1181 [default: the current directory]. The directory must already exist.
1182
1183 =back
1184
1185
1186 =head1 ENVIRONMENT
1187
1188 Environment variables with the same name as a program that B<mf2pt1>
1189 launches but in uppercase specify an alternative program, possibly
1190 with arguments, to run instead. For example, setting C<MPOST='mpost
1191 -recorder'> causes B<mf2pt1> to include the B<-recorder> option when
1192 running B<mpost>.
1193
1194
1195 =head1 FILES
1196
1197 F<mf2pt1.mem> (which is generated from F<mf2pt1.mp> and F<mfplain.mp>)
1198
1199
1200 =head1 NOTES
1201
1202 As stated in L</"WARNING">, the complete source of documentation for
1203 B<mf2pt1> is the Info page, not this man page.
1204
1205
1206 =head1 SEE ALSO
1207
1208 mf(1), mpost(1), t1asm(1), fontforge(1)
1209
1210
1211 =head1 AUTHOR
1212
1213 Scott Pakin, I<[email protected]>