home *** CD-ROM | disk | FTP | other *** search
/ CD Actual Thematic 7: Programming / CDAT7.iso / Share / Editores / Perl5 / perl / lib / site / Font / AFM.pm
Encoding:
Perl POD Document  |  1997-08-10  |  10.0 KB  |  381 lines

  1. # This -*- perl -*-  module is a simple parser for Adobe Font Metrics files.
  2. # $Id: AFM.pm,v 1.11 1996/06/13 08:15:11 aas Exp $
  3.  
  4. package Font::AFM;
  5.  
  6. =head1 NAME
  7.  
  8. Font::AFM - Interface to Adobe Font Metrics files
  9.  
  10. =head1 SYNOPSIS
  11.  
  12.  use Font::AFM;
  13.  $h = new Font::AFM "Helvetica";
  14.  $copyright = $h->Notice;
  15.  $w = $h->Wx->{"aring"};
  16.  $w = $h->stringwidth("Gisle", 10);
  17.  $h->dump;  # for debugging
  18.  
  19. =head1 DESCRIPTION
  20.  
  21. This module implements the Font::AFM class. Objects of this class are
  22. initialised from an AFM-file and allows you to obtain information
  23. about the font and the metrics of the various glyphs in the font.
  24.  
  25. All measurements in AFM files are given in terms of units equal to
  26. 1/1000 of the scale factor of the font being used. To compute actual
  27. sizes in a document, these amounts should be multiplied by (scale
  28. factor of font)/1000.
  29.  
  30. The following methods are available:
  31.  
  32. =over 3
  33.  
  34. =item new($fontname)
  35.  
  36. Object constructor. Takes the name of the font as argument. It will
  37. croak if the font can not be found.
  38.  
  39. =item latin1_wx_table()
  40.  
  41. Returns a 256 element array, where each element contains the width
  42. of the corresponding character in the iso-8859-1 character set.
  43.  
  44. =item stringwidth($string, [$fontsize])
  45.  
  46. Returns the width of the string passed as argument. The string is
  47. assumed to be encoded in the iso-8859-1 character set.  A second
  48. argument can be used to scale the width according to the font size.
  49.  
  50. =item FontName
  51.  
  52. The name of the font as presented to the PostScript language
  53. C<findfont> operator, for instance "Times-Roman".
  54.  
  55. =item FullName
  56.  
  57. Unique, human-readable name for an individual font, for instance
  58. "Times Roman".
  59.  
  60. =item FamilyName
  61.  
  62. Human-readable name for a group of fonts that are stylistic variants
  63. of a single design. All fonts that are member of such a group should
  64. have exactly the same C<FamilyName>. Example of a family name is
  65. "Times".
  66.  
  67. =item Weight
  68.  
  69. Human-readable name for the weight, or "boldness", attribute of a font.
  70. Exampes are C<Roman>, C<Bold>, C<Light>.
  71.  
  72. =item ItalicAngle
  73.  
  74. Angle in degrees counterclockwise from the vertical of the dominant
  75. vertical strokes of the font.
  76.  
  77. =item IsFixedPitch
  78.  
  79. If the value is C<true>, it indicated that the font is a fixed-pitch
  80. (monospaced) font.
  81.  
  82. =item FontBBox
  83.  
  84. A string of four numbers giving the lower-left x, lower-left y,
  85. upper-right x, and upper-right y of the font bounding box. The font
  86. bounding box is the smallest rectangle enclosing the shape that would
  87. result if all the characters of the font were placed with their
  88. origins coincident, and then painted.
  89.  
  90. =item UnderlinePosition
  91.  
  92. Recommended distance from the baseline for positioning underline
  93. stokes. This number is the y coordinate of the center of the stroke.
  94.  
  95. =item UnderlineThickness
  96.  
  97. Recommended stroke width for underlining.
  98.  
  99. =item Version
  100.  
  101. Version number of the font.
  102.  
  103. =item Notice
  104.  
  105. Trademark or copyright notice, if applicable.
  106.  
  107. =item Comment
  108.  
  109. Comments found in the AFM file.
  110.  
  111. =item EncodingScheme
  112.  
  113. The name of the standard encoding scheme for the font. Most Adobe
  114. fonts use the C<AdobeStandardEncoding>. Special fonts might state
  115. C<FontSpecific>.
  116.  
  117. =item CapHeight
  118.  
  119. Usually the y-value of the top of the capital H.
  120.  
  121. =item XHeight
  122.  
  123. Typically the y-value of the top of the lowercase x.
  124.  
  125. =item Ascender
  126.  
  127. Typically the y-value of the top of the lowercase d.
  128.  
  129. =item Descender
  130.  
  131. Typically the y-value of the bottom of the lowercase p.
  132.  
  133. =item Wx
  134.  
  135. Returns a hash table that maps from glyph names to the width of that glyph.
  136.  
  137. =item BBox
  138.  
  139. Returns a hash table that maps from glyph names to bounding box information.
  140. The bounding box consist of 4 numbers: llx, lly, urx, ury.
  141.  
  142. =item dump
  143.  
  144. Dumps the content of the Font::AFM object to STDOUT.  Might sometimes
  145. be useful for debugging.
  146.  
  147. =back
  148.  
  149.  
  150. The AFM specification can be found at:
  151.  
  152.    ftp://ftp.adobe.com/pub/adobe/DeveloperSupport/TechNotes/PSfiles/5004.AFM_Spec.ps
  153.  
  154.  
  155. =head1 ENVIRONMENT
  156.  
  157. =over 10
  158.  
  159. =item METRICS
  160.  
  161. Contains the path to seach for AFM-files.  Format is as for the PATH
  162. environment variable. The default path built into this library is:
  163.  
  164.  /usr/lib/afm:/usr/local/lib/afm:/usr/openwin/lib/fonts/afm/:.
  165.  
  166. =back
  167.  
  168.  
  169. =head1 BUGS
  170.  
  171. Kerning data and composite character data is not yet parsed.
  172. Ligature data is not parsed.
  173.  
  174.  
  175. =head1 COPYRIGHT
  176.  
  177. Copyright 1995 Gisle Aas. All rights reserved.
  178.  
  179. This program is free software; you can redistribute it and/or modify
  180. it under the same terms as Perl itself.
  181.  
  182. =cut
  183.  
  184. #-------perl resumes here--------------------------------------------
  185.  
  186. use Carp;
  187.  
  188. $VERSION = sprintf("%d.%02d", q$Revision: 1.11 $ =~ /(\d+)\.(\d+)/);
  189. sub ModuleVersion { $VERSION; }
  190.  
  191.  
  192. # The metrics_path is used to locate metrics files
  193. #
  194. $metrics_path = $ENV{METRICS} ||
  195.     "/usr/lib/afm:/usr/local/lib/afm:/usr/openwin/lib/fonts/afm/:.";
  196. @metrics_path = split(/:/, $metrics_path);
  197. foreach (@metrics_path) { s,/$,, }    # reove trailing slashes
  198.  
  199. @ISOLatin1Encoding = qw(
  200.  .notdef .notdef .notdef .notdef .notdef .notdef .notdef .notdef
  201.  .notdef .notdef .notdef .notdef .notdef .notdef .notdef .notdef
  202.  .notdef .notdef .notdef .notdef .notdef .notdef .notdef .notdef
  203.  .notdef .notdef .notdef .notdef .notdef .notdef .notdef .notdef space
  204.  exclam quotedbl numbersign dollar percent ampersand quoteright
  205.  parenleft parenright asterisk plus comma minus period slash zero one
  206.  two three four five six seven eight nine colon semicolon less equal
  207.  greater question at A B C D E F G H I J K L M N O P Q R S
  208.  T U V W X Y Z bracketleft backslash bracketright asciicircum
  209.  underscore quoteleft a b c d e f g h i j k l m n o p q r s
  210.  t u v w x y z braceleft bar braceright asciitilde .notdef .notdef
  211.  .notdef .notdef .notdef .notdef .notdef .notdef .notdef .notdef
  212.  .notdef .notdef .notdef .notdef .notdef .notdef .notdef dotlessi grave
  213.  acute circumflex tilde macron breve dotaccent dieresis .notdef ring
  214.  cedilla .notdef hungarumlaut ogonek caron space exclamdown cent
  215.  sterling currency yen brokenbar section dieresis copyright ordfeminine
  216.  guillemotleft logicalnot hyphen registered macron degree plusminus
  217.  twosuperior threesuperior acute mu paragraph periodcentered cedilla
  218.  onesuperior ordmasculine guillemotright onequarter onehalf threequarters
  219.  questiondown Agrave Aacute Acircumflex Atilde Adieresis Aring AE
  220.  Ccedilla Egrave Eacute Ecircumflex Edieresis Igrave Iacute Icircumflex
  221.  Idieresis Eth Ntilde Ograve Oacute Ocircumflex Otilde Odieresis
  222.  multiply Oslash Ugrave Uacute Ucircumflex Udieresis Yacute Thorn
  223.  germandbls agrave aacute acircumflex atilde adieresis aring ae
  224.  ccedilla egrave eacute ecircumflex edieresis igrave iacute icircumflex
  225.  idieresis eth ntilde ograve oacute ocircumflex otilde odieresis divide
  226.  oslash ugrave uacute ucircumflex udieresis yacute thorn ydieresis
  227. );
  228.  
  229.  
  230. # Creates a new Font::AFM object.  Pass it the name of the font as parameter.
  231. # Synopisis:
  232. #
  233. #    $h = new Font::AFM "Helvetica";
  234. #
  235.  
  236. sub new
  237. {
  238.    my($class, $fontname) = @_;
  239.    $fontname =~ s/.amf$//;
  240.    my $file = "$fontname.afm";
  241.    unless ($file =~ m,^/,) {
  242.        # not absolute, search the metrics path for the file
  243.        foreach (@metrics_path) {
  244.        if (-f "$_/$file") {
  245.            $file = "$_/$file";
  246.            last;
  247.        }
  248.        }
  249.    }
  250.    open(AFM, $file) or croak "Can't find the AFM file for $fontname";
  251.    my $this = bless { }, $class;
  252.    local($/, $_) = ("\n", undef);  # ensure correct $INPUT_RECORD_SEPARATOR
  253.    while (<AFM>) {
  254.        next if /^StartKernData/ .. /^EndKernData/;  # kern data not parsed yet
  255.        next if /^StartComposites/ .. /^EndComposites/; # same for composites
  256.        if (/^StartCharMetrics/ .. /^EndCharMetrics/) {
  257.        # only lines that start with "C" or "CH" are parsed
  258.        next unless /^CH?\s/;
  259.        my($name) = /\bN\s+(\w+)\s*;/;
  260.        my($wx)   = /\bWX\s+(\d+)\s*;/;
  261.        my($bbox)    = /\bB\s+([^;]+)\s*;/;
  262.        # Should also parse lingature data (format: L successor lignature)
  263.        $this->{'wx'}{$name} = $wx;
  264.        $this->{'bbox'}{$name} = $bbox;
  265.        next;
  266.        }
  267.        last if /^EndFontMetrics/;
  268.        if (/(^\w+)\s+(.*)/) {
  269.        my($key,$val) = ($1, $2);
  270.        $key = lc $key;
  271.        if (defined $this->{$key}) {
  272.            $this->{$key} = [ $this->{$key} ] unless ref $this->{$key};
  273.            push(@{$this->{$key}}, $val);
  274.        } else {
  275.            $this->{$key} = $val;
  276.        }
  277.        } else {
  278.        print STDERR "Can't parse: $_";
  279.        }
  280.    }
  281.    close(AFM);
  282.    $this->{wx}->{'.notdef'} = 0;
  283.    $this->{bbox}{'.notdef'} = "0 0 0 0";
  284.    $this;
  285. }
  286.  
  287. # Returns an 256 element array that maps from characters to width
  288. sub latin1_wx_table
  289. {
  290.     my($this) = @_;
  291.     unless ($this->{'_wx_table'}) {
  292.     $this->{'_wx_table'} =
  293.         [ map {$this->{wx}->{$ISOLatin1Encoding[$_]}} 0..255 ];
  294.     }
  295.     @{ $this->{'_wx_table'} };
  296. }
  297.  
  298. sub stringwidth
  299. {
  300.     my($this, $string, $pointsize) = @_;
  301.     return 0.0 unless defined $string;
  302.     return 0.0 unless length $string;
  303.  
  304.     my @wx = $this->latin1_wx_table;
  305.     my $width = 0.0;
  306.     while ($string =~ /./g) {
  307.     $width += $wx[ord $&];
  308.     }
  309.     if ($pointsize) {
  310.     $width *= $pointsize / 1000;
  311.     }
  312.     $width;
  313. }
  314.  
  315. sub FontName;
  316. sub FullName;
  317. sub FamilyName;
  318. sub Weight;
  319. sub ItalicAngle;
  320. sub IsFixedPitch;
  321. sub FontBBox;
  322. sub UnderlinePosition;
  323. sub UnderlineThickness;
  324. sub Version;
  325. sub Notice;
  326. sub Comment;
  327. sub EncodingScheme;
  328. sub CapHeight;
  329. sub XHeight;
  330. sub Ascender;
  331. sub Descender;
  332. sub Wx;
  333. sub BBox;
  334.  
  335. # We implement all the access functions within this simple autoload
  336. # function.
  337.  
  338. sub AUTOLOAD
  339. {
  340.     #print "AUTOLOAD: $AUTOLOAD\n";
  341.     if ($AUTOLOAD =~ /::DESTROY$/) {
  342.     eval "sub $AUTOLOAD {}";
  343.     goto &$AUTOLOAD;
  344.     } else {
  345.     my $name = $AUTOLOAD;
  346.     $name =~ s/^.*:://;
  347.     croak "Attribute $name not defined for AFM object"
  348.         unless defined $_[0]->{lc $name};
  349.     return $_[0]->{lc $name};
  350.     }
  351. }
  352.  
  353.  
  354. # Dumping might be usefull for debugging
  355.  
  356. sub dump
  357. {
  358.     my($this) = @_;
  359.     my($key, $val);
  360.     foreach $key (sort keys %$this) {
  361.     if (ref $this->{$key}) {
  362.         if (ref $this->{$key} eq "ARRAY") {
  363.         print "$key = [\n\t", join("\n\t", @{$this->{$key}}), "\n]\n";
  364.         } elsif (ref $this->{$key} eq "HASH") {
  365.         print "$key = {\n";
  366.         my $key2;
  367.         foreach $key2 (sort keys %{$this->{$key}}) {
  368.             print "\t$key2 => $this->{$key}{$key2},\n";
  369.         }
  370.         print "}\n";
  371.         } else {
  372.         print "$key = $this->{$key}\n";
  373.         }
  374.     } else {
  375.         print "$key = $this->{$key}\n";
  376.     }
  377.     }
  378. }
  379.  
  380. 1;
  381.