Cairo/Font.pm

filter: Statementstmt 81.8% 9 / 11 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 86.6% 13 / 15 CC 1 SCAR 0.7
CC
1
Cov
82%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Cairo/Box.pm ↑ Summary Cairo/Layout.pm »
1 package PDF::Cairo::Font;
2  
3 1 ▶use 5.016;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Cairo;
Subroutine BEGIN: called CC=1 SCAR=2.6
7 use Font::FreeType;
8  
9 our $VERSION = "1.03";
10 $VERSION = eval $VERSION;
11  
12 =head1 NAME
13  
14 PDF::Cairo::Font - wrapper that adds some useful methods to Cairo fonts
15  
16 =head1 SYNOPSIS
17  
18 L<Cairo> supports three types of fonts: built-in, L<Font::FreeType>,
19 and L<Pango>, which all have subtly different behaviors. This module
20 hides that complexity while also adding compatibility methods for
21 easily converting scripts from L<PDF::API2::Lite>.
22  
23 =head1 DESCRIPTION
24  
25 =cut
26  
27 our (
28 @ISA,
29 @EXPORT,
30 @EXPORT_OK,
31 %EXPORT_TAGS,
32 @FONT_PATH,
33 %_api2font,
34 );
35 BEGIN {
36 require Exporter;
37 @ISA = qw(Exporter);
38 @EXPORT = qw();
39 @EXPORT_OK = qw();
40 %EXPORT_TAGS = (all => \@EXPORT_OK);
41  
42 # last-ditch mapping of PDF::API2 core fonts to Cairo toy fonts
43 %_api2font = (
44 'courier' => [ "mono", "normal", "normal" ],
45 'courier-bold' => [ "mono", "normal", "bold" ],
46 'courier-boldoblique' => [ "mono", "oblique", "bold" ],
47 'courier-oblique' => [ "mono", "oblique", "normal" ],
48 'helvetica' => [ "sans", "normal", "normal" ],
49 'helvetica-bold' => [ "sans", "normal", "bold" ],
50 'helvetica-boldoblique' => [ "sans", "oblique", "bold" ],
51 'helvetica-oblique' => [ "sans", "oblique", "normal" ],
52 'times-bold' => [ "serif", "normal", "bold" ],
53 'times-bolditalic' => [ "serif", "italic", "bold" ],
54 'times-italic' => [ "serif", "italic", "normal" ],
55 'times-roman' => [ "serif", "normal", "normal" ],
56 'georgia' => [ "serif", "normal", "normal" ],
57 'georgia-bold' => [ "serif", "normal", "bold" ],
58 'georgia-bolditalic' => [ "serif", "italic", "bold" ],
59 'georgia-italic' => [ "serif", "italic", "normal" ],
60 'verdana' => [ "sans", "normal", "normal" ],
61 'verdana-bold' => [ "sans", "normal", "bold" ],
62 'verdana-bolditalic' => [ "sans", "italic", "bold" ],
63 'verdana-italic' => [ "sans", "italic", "normal" ],
64 );
65 no warnings qw(once);
66  
67 # try to use FontConfig's fc-list to locate all the active
68 # font directories on the current system. Note that on a
69 # Mac, this will not find all active fonts; see macos2fc.pl
70 # for a workaround.
71 # If fc-match is in the path, use it and fc-list to get access
72 # to all installed fonts
73 my $fctmp = `fc-match -V 2>&1` || '';
74  
75 if ($fctmp =~ /^fontconfig/) {
76 open(my $In, "-|", "fc-list : file");
77 my %tmp;
78 while (<$In>) {
79 s|/[^/]+$||;
80 $tmp{$_}++;
81 }
82 close($In);
83 @FONT_PATH = sort keys %tmp;
84 }
85 push(@FONT_PATH, ".");
86 }
87  
88 =head2 Methods
89  
90 =over 4
91  
92 =item B<new> $pdf_cairo_ref, $font, [$index|$metrics]
93  
94 The first argument must be a PDF::Cairo object, in order for Cairo to
95 locate the surface/context, and to stash a reference to a
96 Font::FreeType instance.
97  
98 =cut
99  
100 sub new {
101 my $class = shift;
102 my $pcref = shift;
103 my @font = split(/,/,shift);
104 my $self = {};
105 my $type;
106 if (index($font[0], '.') == -1) {
107 @font = find_api2font(@font);
108 }
109 if ($font[0] =~ /\.([ot]t[cf]|pfb|dfont)$/i) {
110 $type = $1;
111 $type =~ tr/A-Z/a-z/;
112 if (index($font[0], "/") == -1) {
113 foreach my $path (@FONT_PATH) {
114 if (-f "$path/$font[0]") {
115 $font[0] = "$path/$font[0]";
116 last;
117 }
118 }
119 }
120 }
121 my $collection_index = 0;
122 my $metrics_file;
123 if (grep($type eq $_, qw(otc ttc dfont)) and defined $font[1]) {
124 $collection_index = $font[1];
125 }elsif ($type eq "pfb") {
126 my @metrics_file;
127 if (defined $font[1]) {
128 $metrics_file[0] = $font[1];
129 }else{
130 $metrics_file[0] = $font[0];
131 $metrics_file[1] = $font[0];
132 $metrics_file[0] =~ s/pfb$/afm/;
133 $metrics_file[1] =~ s/pfb$/AFM/;
134 }
135 if (-f $metrics_file[0]) {
136 $metrics_file = $metrics_file[0];
137 }elsif ($metrics_file[1] and -f $metrics_file[1]) {
138 $metrics_file = $metrics_file[1];
139 }else{
140 foreach my $path (@FONT_PATH) {
141 foreach my $file (@metrics_file) {
142 if (-f "$path/$file") {
143 $metrics_file = "$path/$file";
144 last;
145 }
146 }
147 last if $metrics_file;
148 }
149 }
150 }
151 $self->{type} = "freetype";
152 $pcref->{_freetype} = Font::FreeType->new
153 unless ref $pcref->{_freetype};
154 my $ft_face = $pcref->{_freetype}->face(
155 $font[0],
156 load_flags => FT_LOAD_NO_HINTING,
157 index => $collection_index,
158 );
159 if ($metrics_file) {
160 $ft_face->attach_file($metrics_file);
161 }
162 $ft_face->set_char_size(1, 1, 72, 72);
163 $self->{_source} = {
164 type => $type,
165 file => $font[0],
166 index => $collection_index,
167 metrics_file => $metrics_file,
168 freetype => $pcref->{_freetype},
169 face => $ft_face,
170 };
171 $self->{face} = Cairo::FtFontFace->create($ft_face);
172  
173 # no font file found? put *something* on the page...
174 if (! defined $self->{type}) {
175 $self->{type} = "cairo";
176 $self->{face} = $pcref->{context}->select_font_face("sans");
177 }
178 _create_font_metrics($self);
179 bless($self, $class);
180 }
181  
182 # slow but precise method of determining the actual metrics
183 # of a font, by rendering strings in a recording surface and
184 # using the resulting ink_extents().
185 # TODO:
186 # bbox - loop over the font; don't go nuts if it's CJK
187 # maxwidth - use results from calculating bbox
188 # has_cjk (requires testing for presence of glyphs)
189 # baseline_cjk - try to render \u{66DC} (UTF-8 0xE69B9C)
190 # cjkheight - use the h from calculating baseline_cjk
191 #
192 sub _create_font_metrics {
193 my ($self) = @_;
194 my $metrics = {};
195 my @tmp;
196  
197 if ($self->{type} eq 'freetype') {
198 my $ft_face = $self->{_source}->{face};
199 my $upm = $ft_face->units_per_em;
200 $metrics->{ascender} = $ft_face->ascender / $upm;
201 $metrics->{descender} = $ft_face->descender / $upm;
202 $metrics->{height} = $ft_face->height / $upm;
203 $metrics->{underline_position} = $ft_face->underline_position / $upm;
204 $metrics->{underline_thickness} = $ft_face->underline_thickness / $upm;
205 my $tmp = $ft_face->bounding_box;
206 $metrics->{bbox} = [
207 $tmp->x_min / $upm,
208 $tmp->y_min / $upm,
209 $tmp->x_max / $upm,
210 $tmp->y_max / $upm,
211 ];
212 }elsif ($self->{type} eq 'cairo') {
213 # TODO: scaled_font_extents()
214 }
215  
216 # calculated ascender
217 @tmp = _text_bbox($self, "XETIhktfb");
218 $metrics->{exact_ascender} = - $tmp[1];
219  
220 # calculated xheight
221 @tmp = _text_bbox($self, "x");
222 $metrics->{exact_xheight} = - $tmp[1];
223 # calculated baseline != 0 usually only found in specialty fonts
224 $metrics->{is_unusual} = $tmp[1] + $tmp[3] != 0;
225  
226 # calculated capheight
227 @tmp = _text_bbox($self, "XETI");
228 $metrics->{exact_capheight} = - $tmp[1];
229 $metrics->{is_unusual} = $tmp[1] + $tmp[3] != 0;
230  
231 # calculated descender
232 @tmp = _text_bbox($self, "ygj");
233 $metrics->{exact_descender} = $tmp[1] + $tmp[3];
234  
235 # fall back to my calculated values
236 for my $i (qw(ascender descender capheight xheight)) {
237 $metrics->{$i} = $metrics->{"exact_$i"}
238 unless defined $metrics->{$i};
239 }
240 if (! defined $metrics->{height}) {
241 # wild-assed guess
242 $metrics->{height} = $metrics->{ascender} / 0.8;
243 }
244 # TODO: fake up a bbox
245 # TODO: fake up underline_{position,thickness}
246  
247 $self->{metrics} = $metrics;
248 }
249  
250 # use a recording surface to calculate the exact bounding box
251 # of a string rendered in the current font.
252 # returns ULx, ULy, width, height
253 #
254 sub _text_bbox {
255 my ($self, $text) = @_;
256 # render at this size to get plenty of precision
257 my $size = 1000;
258 my $s = Cairo::RecordingSurface->create("color-alpha", undef);
259 my $c = Cairo::Context->create($s);
260 if ($self->{type} eq 'freetype') {
261 $c->set_font_face($self->{face});
262 }elsif ($self->{type} eq 'cairo') {
263 $c->select_font_face(@{$self->{_source}->{name}});
264 }
265 $c->set_source_rgb(0, 0, 0);
266 $c->move_to(0, 0);
267 $c->set_font_size($size);
268 $c->show_text($text);
269 my @bbox = map($_ / $size, $s->ink_extents());
270 $s->flush;
271 $s->finish;
272 return @bbox;
273 }
274  
275 =item B<ascender> $use_exact
276  
277 Returns the ascender value for the font, assuming size of 1 point.
278 If you supply a non-zero argument, this will be calculated by
279 rendering sample characters in the font and determining exactly
280 how far they extend above the baseline.
281  
282 =cut
283  
284 sub ascender {
285 my $self = shift;
286 my $metrics = $self->{metrics};
287 return $_[0] ? $metrics->{exact_ascender} : $metrics->{ascender};
288 }
289  
290 =item B<bbox>
291  
292 Returns the bounding box of the font (LLx, LLy, URx, URy),
293 assuming size of 1 point.
294  
295 =cut
296  
297 sub bbox {
298 my $self = shift;
299 my $metrics = $self->{metrics};
300 return @{$metrics->{bbox}};
301 }
302  
303 =item B<capheight> $use_exact
304  
305 Returns the capheight value for the font, assuming size of 1 point. If
306 you supply a non-zero argument, this will be calculated by rendering
307 sample upper-case characters in the font and determining exactly how
308 far they extend above the baseline.
309  
310 =cut
311  
312 sub capheight {
313 my $self = shift;
314 my $metrics = $self->{metrics};
315 return $_[0] ? $metrics->{exact_capheight} : $metrics->{capheight};
316 }
317  
318 =item B<descender> $use_exact
319  
320 Returns the descender value for the font, assuming size of 1 point.
321 This is usually negative, reflecting its offset from the baseline.
322 If you supply a non-zero argument, this will be calculated by
323 rendering sample characters in the font and determining exactly
324 how far they extend below the baseline.
325  
326 =cut
327  
328 sub descender {
329 my $self = shift;
330 my $metrics = $self->{metrics};
331 return $_[0] ? $metrics->{exact_descender} : $metrics->{descender};
332 }
333  
334 =item B<xheight> $use_exact
335  
336 Returns the xheight value for the font, assuming size of 1 point.
337 If you supply a non-zero argument, this will be calculated by
338 rendering a lower-case "X" in the font and determining exactly
339 how far it extends above the baseline.
340  
341 =cut
342  
343 sub xheight {
344 my $self = shift;
345 my $metrics = $self->{metrics};
346 return $_[0] ? $metrics->{exact_xheight} : $metrics->{xheight};
347 }
348  
349 =back
350  
351 =head2 PDF::API2 Compatibility
352  
353 =over 4
354  
355 =item B<fontbbox>
356  
357 Alias for bbox().
358  
359 =cut
360  
361 sub fontbbox {
362 return bbox(@_);
363 }
364  
365 =item B<width> $text
366  
367 Calculate width of text in this font at size of 1 point.
368  
369 =cut
370  
371 sub width {
372 return 0 unless defined $_[1];
373 my @bbox = _text_bbox(@_);
374 return $bbox[2];
375 }
376  
377 =back
378  
379 =head2 Utility Functions
380  
381 =over 4
382  
383 =item B<append_font_path> @paths
384  
385 Add @paths to the end of the font search path.
386  
387 =cut
388  
389 sub append_font_path {
390 push(@FONT_PATH, @_);
391 }
392  
393 =item B<get_font_path>
394  
395 Returns an array of directories that will be searched for fonts,
396 and for AFM metrics files if you load a PFB font (case-insensitive).
397  
398 =cut
399  
400 sub get_font_path {
401 return @FONT_PATH;
402 }
403  
404 =item B<set_font_path> @paths
405  
406 Set the font search path to @paths.
407  
408 =cut
409  
410 sub set_font_path {
411 @FONT_PATH = @_;
412 }
413  
414 =item B<find_api2font> $name
415  
416 Uses Fontconfig to locate a decent match for the PDF::API2 builtin
417 (non-embedded) fonts. The 'core' fonts are Times, Courier, Helvetica,
418 Georgia, and Verdana, which Fontconfig is pretty good at finding
419 matches for. The 'cjk' fonts are more problematic, and I recommend
420 downloading the language-specific OTF files of Source Han from these
421 links and loading them by filename instead:
422  
423 https://github.com/adobe-fonts/source-han-sans/tree/release
424 https://github.com/adobe-fonts/source-han-serif/tree/release
425  
426 Otherwise, the following Fontconfig searches will be used, with
427 results that depend on how sane your F<fonts.conf> is:
428  
429 traditional|ming = "serif:lang=zh-tw"
430 simplified|song = "serif:lang=zh-cn"
431 korean|myungjo = "serif:lang=ko"
432 japanese|kozmin = "serif:lang=ja"
433 kozgo = "sans:lang=ja"
434  
435 =cut
436  
437 sub find_api2font {
438 my $fontname = join('-', @_);
439 $fontname =~ tr/,A-Z/-a-z/;
440 my ($family, $weight, $style) = qw(serif normal normal);
441 my $lang = '';
442 $weight = 'bold' if $fontname =~ /bold/;
443 $style = 'italic' if $fontname =~ /oblique|italic/;
444 if ($fontname =~ /^(times|courier|helvetica|georgia|verdana)/) {
445 $family = $1;
446 }elsif ($fontname =~ /^(traditional|ming)/) {
447 $lang = ':lang=zh-cn';
448 }elsif ($fontname =~ /^(simplified|song)/) {
449 $lang = ':lang=zh-tw';
450 }elsif ($fontname =~ /^(japanese|kozmin)/) {
451 $lang = ':lang=ja';
452 }elsif ($fontname =~ /^kozgo/) {
453 $family = 'sans';
454 $lang = ':lang=ja';
455 }
456 my $search = join(':', $family, $weight, $style, $lang);
457 my $match = `fc-match -f '%{file}\t%{index}' $search`;
458 my ($file, $index) = split(/\t/, $match);
459 if (defined $file) {
460 return ($file, $index);
461 }else{
462 # this allows fallthrough to cairo toy API if matching fonts
463 # are not installed on your system
464 return @_;
465 }
466 }
467  
468 =back
469  
470 =head1 AUTHOR
471  
472 J Greely, C<< <jgreely at cpan.org> >>
473  
474 =head1 SEE ALSO
475  
476 L<PDF::API2>, L<PDF::Builder>, L<Cairo>, L<Font::FreeType>, L<Pango>,
477 L<Fontconfig|http://fontconfig.org>
478  
479 =cut
480  
481 1;
« Cairo/Box.pm ↑ Summary Cairo/Layout.pm »