Cairo/Font.pm untested

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