Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

399 lines
11 KiB

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