Graph.pm

filter: Statementstmt 66.6% 4 / 6 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 75.0% 6 / 8 CC 1 SCAR 1.4
CC
1
Cov
67%
BEGIN
1.3
BEGIN
1.0
CRAP 1.1
« Graph/linespoints.pm ↑ Summary Graph/axestype.pm »
1 #==========================================================================
2 # Copyright (c) 1995-2000 Martien Verbruggen
3 #--------------------------------------------------------------------------
4 #
5 # Name:
6 # GD::Graph.pm
7 #
8 # Description:
9 # Module to create graphs from a data set drawing on a GD::Image
10 # object
11 #
12 # Package of a number of graph types:
13 # GD::Graph::bars
14 # GD::Graph::hbars
15 # GD::Graph::lines
16 # GD::Graph::points
17 # GD::Graph::linespoints
18 # GD::Graph::area
19 # GD::Graph::pie
20 # GD::Graph::mixed
21 #
22 # $Id: Graph.pm,v 1.58 2007/06/05 04:28:31 ben Exp $
23 #
24 #==========================================================================
25  
26 #
27 # GD::Graph
28 #
29 # Parent class containing data all graphs have in common.
30 #
31  
32 package GD::Graph;
33  
34 ($GD::Graph::prog_version) = '$Revision: 1.58 $' =~ /\s([\d.]+)/;
35 $GD::Graph::VERSION = '1.44_01';
36  
37 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 3 ▶use GD;
Subroutine BEGIN: called CC=1 SCAR=2.6
39 use GD::Text::Align;
40 use GD::Graph::Data;
41 use GD::Graph::Error;
42 use Carp;
43  
44 @GD::Graph::ISA = qw(GD::Graph::Error);
45  
46 # Some tools and utils
47 use GD::Graph::colour qw(:colours);
48  
49 my %GDsize = (
50 'x' => 400,
51 'y' => 300
52 );
53  
54 my %Defaults = (
55  
56 # Set the top, bottom, left and right margin for the chart. These
57 # margins will be left empty.
58 t_margin => 0,
59 b_margin => 0,
60 l_margin => 0,
61 r_margin => 0,
62  
63 # Set the factor with which to resize the logo in the chart (need to
64 # automatically compute something nice for this, really), set the
65 # default logo file name, and set the logo position (UR, BR, UL, BL)
66 logo => undef,
67 logo_resize => 1.0,
68 logo_position => 'LR',
69  
70 # Do we want a transparent background?
71 transparent => 1,
72  
73 # Do we want interlacing?
74 interlaced => 1,
75  
76 # Set the background colour, the default foreground colour (used
77 # for axes etc), the textcolour, the colour for labels, the colour
78 # for numbers on the axes, the colour for accents (extra lines, tick
79 # marks, etc..)
80 bgclr => 'white', # background colour
81 fgclr => 'dblue', # Axes and grid
82 boxclr => undef, # Fill colour for box axes, default: not used
83 accentclr => 'gray', # bar, area and pie outlines.
84  
85 labelclr => 'dblue', # labels on axes
86 axislabelclr => 'dblue', # values on axes
87 legendclr => 'dblue', # Text for the legend
88 textclr => 'dblue', # All text, apart from the following 2
89  
90 valuesclr => 'dblue', # values printed above the points
91
92 # data set colours
93 dclrs => [qw(lred lgreen lblue lyellow lpurple cyan lorange)],
94  
95 # number of pixels to use as text spacing
96 text_space => 4,
97  
98 # These have undefined values, but are here so that the set method
99 # knows about them:
100 title => undef,
101 );
102  
103 sub _has_default {
104 my $self = shift;
105 my $attr = shift || return;
106 exists $Defaults{$attr}
107 }
108  
109 #
110 # PUBLIC methods, documented in pod.
111 #
112 sub new # ( width, height, truecolor ) optional;
113 {
114 my $type = shift;
115 my $self = {};
116 bless $self, $type;
117  
118 if (@_)
119 {
120 # If there are any parameters, they should be the size
121 return GD::Graph->_set_error(
122 "Usage: GD::Graph::<type>::new(width, height, truecolor)") unless @_ >= 2;
123  
124 $self->{width} = shift;
125 $self->{height} = shift;
126 $self->{truecolor} = shift;
127 $self->{truecolor} = 0 unless defined($self->{truecolor});
128 }
129 else
130 {
131 # There were obviously no parameters, so use defaults
132 $self->{width} = $GDsize{'x'};
133 $self->{height} = $GDsize{'y'};
134 }
135  
136 # Initialise all relevant parameters to defaults
137 # These are defined in the subclasses. See there.
138 $self->initialise() or return;
139  
140 return $self;
141 }
142  
143 sub get
144 {
145 my $self = shift;
146 my @wanted = map $self->{$_}, @_;
147 wantarray ? @wanted : $wanted[0];
148 }
149  
150 sub set
151 {
152 my $self = shift;
153 my %args = @_;
154 my $w = 0;
155  
156 foreach (keys %args)
157 {
158 # Enforce read-only attributes.
159 /^width$/ || /^height$/ and do
160 {
161 $self->_set_warning("Read-only attribute '$_' not set");
162 $w++;
163 next;
164 };
165  
166 $self->{$_} = $args{$_}, next if $self->_has_default($_);
167  
168 $w++;
169 $self->_set_warning("No attribute '$_'");
170 }
171  
172 return $w ? undef : "No problems";
173 }
174  
175 # Generic routine to instantiate GD::Text::Align objects for text
176 # attributes
177 sub _set_font
178 {
179 my $self = shift;
180 my $name = shift;
181  
182 if (! exists $self->{$name})
183 {
184 $self->{$name} = GD::Text::Align->new($self->{graph},
185 valign => 'top',
186 halign => 'center',
187 ) or return $self->_set_error("Couldn't set font");
188 }
189  
190 $self->{$name}->set_font(@_);
191 }
192  
193 sub set_title_font # (fontname, size)
194 {
195 my $self = shift;
196 $self->_set_font('gdta_title', @_);
197 }
198  
199 sub set_text_clr # (colour name)
200 {
201 my $self = shift;
202 my $clr = shift;
203  
204 $self->set(
205 textclr => $clr,
206 labelclr => $clr,
207 axislabelclr => $clr,
208 valuesclr => $clr,
209 );
210 }
211  
212 sub plot
213 {
214 # ABSTRACT
215 my $self = shift;
216 $self->die_abstract("sub plot missing,");
217 }
218  
219 # Set defaults that apply to all graph/chart types.
220 # This is called by the default initialise methods
221 # from the objects further down the tree.
222  
223 sub initialise
224 {
225 my $self = shift;
226  
227 foreach (keys %Defaults)
228 {
229 $self->set($_ => $Defaults{$_});
230 }
231  
232 $self->open_graph() or return;
233 $self->set_title_font(GD::Font->Large) or return;
234 }
235  
236  
237 # Check the integrity of the submitted data
238 #
239 # Checks are done to assure that every input array
240 # has the same number of data points, it sets the variables
241 # that store the number of sets and the number of points
242 # per set, and kills the process if there are no datapoints
243 # in the sets, or if there are no data sets.
244  
245 sub check_data # \@data
246 {
247 my $self = shift;
248 my $data = shift;
249  
250 $self->{_data} = GD::Graph::Data->new($data)
251 or return $self->_set_error(GD::Graph::Data->error);
252
253 $self->{_data}->make_strict;
254  
255 $self->{_data}->num_sets > 0 && $self->{_data}->num_points > 0
256 or return $self->_set_error('No data sets or points');
257
258 if ($self->{show_values})
259 {
260 # If this isn't a GD::Graph::Data compatible structure, then
261 # we'll just use the data structure.
262 #
263 # XXX We should probably check a few more things here, e.g.
264 # similarity between _data and show_values.
265 #
266 my $ref = ref($self->{show_values});
267 if (! $ref || ($ref ne 'GD::Graph::Data' && $ref ne 'ARRAY'))
268 {
269 $self->{show_values} = $self->{_data}
270 }
271 elsif ($ref eq 'ARRAY')
272 {
273 $self->{show_values} =
274 GD::Graph::Data->new($self->{show_values})
275 or return $self->_set_error(GD::Graph::Data->error);
276 }
277 }
278  
279 return $self;
280 }
281  
282 # Open the graph output canvas by creating a new GD object.
283  
284 sub open_graph
285 {
286 my $self = shift;
287 return $self->{graph} if exists $self->{graph};
288 if (2.0 <= $GD::VERSION){
289 if ($self->{truecolor}){
290 $self->{graph} = GD::Image->newTrueColor($self->{width}, $self->{height});
291 } else {
292 $self->{graph} = GD::Image->newPalette($self->{width}, $self->{height});
293 }
294 } else {
295 $self->{graph} = GD::Image->new($self->{width}, $self->{height});
296 }
297 }
298  
299 # Initialise the graph output canvas, setting colours (and getting back
300 # index numbers for them) setting the graph to transparent, and
301 # interlaced, putting a logo (if defined) on there.
302  
303 sub init_graph
304 {
305 my $self = shift;
306  
307 $self->{bgci} = $self->set_clr(_rgb($self->{bgclr}));
308 if ($self->{truecolor}){
309 #fake up the background, since it doesn't work with the first allocated color,
310 #like in palette based images
311 $self->{graph}->filledRectangle(0,0,$self->{width},$self->{height},$self->{bgci});
312 }
313 $self->{fgci} = $self->set_clr(_rgb($self->{fgclr}));
314 $self->{tci} = $self->set_clr(_rgb($self->{textclr}));
315 $self->{lci} = $self->set_clr(_rgb($self->{labelclr}));
316 $self->{alci} = $self->set_clr(_rgb($self->{axislabelclr}));
317 $self->{acci} = $self->set_clr(_rgb($self->{accentclr}));
318 $self->{valuesci} = $self->set_clr(_rgb($self->{valuesclr}));
319 $self->{legendci} = $self->set_clr(_rgb($self->{legendclr}));
320 $self->{boxci} = $self->set_clr(_rgb($self->{boxclr}))
321 if $self->{boxclr};
322  
323 $self->{graph}->transparent($self->{bgci}) if $self->{transparent};
324 $self->{graph}->interlaced( $self->{interlaced} || undef ); # required by GD.pm
325  
326 # XXX yuck. This doesn't belong here.. or does it?
327 $self->put_logo();
328  
329 return $self;
330 }
331  
332 sub _read_logo_file
333 {
334 my $self = shift;
335 my $glogo;
336 local (*LOGO);
337 my $logo_path = $self->{logo};
338 open(LOGO, $logo_path)
339 or do { carp "Unable to open logo file '$logo_path': $!";return};
340 binmode(LOGO);
341 # if the file has an extension, use that importer
342 my $gdimport;
343 my @tried;
344 # possibly forward-compatible: just try whatever file extension
345 if ( $logo_path =~ /\.(\w+)$/i) {
346 my $fmt = lc $1;
347 $fmt = "jpeg" if 'jpg' eq $fmt;
348 push @tried, uc $fmt;
349 if ($gdimport = GD::Image->can("newFrom\u$fmt")) {
350 if ('xpm' ne $fmt) { $glogo = GD::Image->$gdimport(\*LOGO) }
351 else { $glogo = GD::Image->$gdimport($logo_path) } # quirky special case
352 }
353 }
354 # if that didn't work, try using magic numbers
355 if (!$glogo) {
356 my $logodata;
357 read LOGO,$logodata, -s LOGO;
358 my %magic = (
359 pack("H8",'ffd8ffe0') => "jpeg",
360 'GIF8' => "gif",
361 '.PNG' => "png",
362 '/* X'=> "xpm", # technically '/* XPM */', but I'm hashing, here
363 );
364 if (my $match = $magic{ substr $logodata, 0, 4 }) {
365 push @tried, $match;
366 my $matchmethod = "newFrom\u$match";
367 if ($gdimport = GD::Image->can($matchmethod . "Data")) {
368 $glogo = GD::Image->$gdimport($logodata);
369 } elsif ($gdimport = GD::Image->can($matchmethod)) {
370 if ('xpm' eq $match) {
371 $glogo = GD::Image->$gdimport($logo_path);
372 } else {
373 seek LOGO,0,0;
374 $glogo = GD::Image->$gdimport(\*LOGO);
375 }
376 }
377 # should this actually be "if (!$glogo), rather than an else?
378 } else { # Hail Mary, full of Grace! Blessed art thou among women...
379 push @tried, 'libgd best-guess';
380 $glogo = GD::Image->new($logodata);
381 }
382 }
383 close LOGO or croak "Unable to close logo file '$logo_path': $!";
384 # XXX change to use warnings::enabled when we break 5.005 compatibility
385 carp "Problems reading $logo_path (tried: @tried)" unless $glogo;
386 return $glogo;
387 }
388  
389 # read in the logo, and paste it on the graph canvas
390  
391 sub put_logo
392 {
393 my $self = shift;
394 return unless defined $self->{logo};
395  
396 my $glogo = $self->_read_logo_file() or return;
397  
398 my ($x, $y);
399 my $r = $self->{logo_resize};
400  
401 my $r_margin = (defined $self->{r_margin_abs}) ?
402 $self->{r_margin_abs} : $self->{r_margin};
403 my $b_margin = (defined $self->{b_margin_abs}) ?
404 $self->{b_margin_abs} : $self->{b_margin};
405  
406 my ($w, $h) = $glogo->getBounds;
407 LOGO: for ($self->{logo_position}) {
408 /UL/i and do {
409 $x = $self->{l_margin};
410 $y = $self->{t_margin};
411 last LOGO;
412 };
413 /UR/i and do {
414 $x = $self->{width} - $r_margin - $w * $r;
415 $y = $self->{t_margin};
416 last LOGO;
417 };
418 /LL/i and do {
419 $x = $self->{l_margin};
420 $y = $self->{height} - $b_margin - $h * $r;
421 last LOGO;
422 };
423 # default "LR"
424 $x = $self->{width} - $r_margin - $r * $w;
425 $y = $self->{height} - $b_margin - $r * $h;
426 last LOGO;
427 }
428 $self->{graph}->copyResized($glogo,
429 $x, $y, 0, 0, $r * $w, $r * $h, $w, $h);
430 }
431  
432 # Set a colour to work with on the canvas, by rgb value.
433 # Return the colour index in the palette
434  
435 sub set_clr # GD::Image, r, g, b
436 {
437 my $self = shift;
438 return unless @_ > 1;
439 my $gd = $self->gd;
440  
441 if (3 < @_ ) {
442 if ( $gd->can('colorResolveAlpha') ) {
443 return $gd->colorResolveAlpha(@_);
444 } else {
445 pop @_; # discard alpha information
446 }
447 }
448 # All of this could potentially be done by using colorResolve
449 # The problem is that colorResolve doesn't return an error
450 # condition (-1) if it can't allocate a color. Instead it always
451 # returns 0.
452  
453 # Check if this colour already exists on the canvas
454 my $i = $gd->colorExact(@_);
455 # if not, allocate a new one, and return its index
456 $i = $gd->colorAllocate(@_) if $i < 0;
457 # if this fails, we should use colorClosest.
458 $i = $gd->colorClosest(@_) if $i < 0;
459  
460 return $i;
461 }
462  
463 # Set a temporary colour that can be used with fillToBorder
464 sub _set_tmp_clr
465 {
466 my $self = shift;
467 # XXX Error checks!
468 $self->{graph}->colorAllocate(0,0,0);
469 }
470  
471 # Remove the temporary colour
472 sub _rm_tmp_clr
473 {
474 my $self = shift;
475 return unless @_;
476 # XXX Error checks?
477 $self->{graph}->colorDeallocate(shift);
478 }
479  
480 # Set a colour, disregarding wether or not it already exists. This may
481 # be necessary where one wants the same colour to have a different
482 # index, as in pie slices of the same color as the edge.
483 # Note that this could be cleaned up after needed, but we won't do that.
484  
485 sub set_clr_uniq # GD::Image, r, g, b
486 {
487 my $self = shift;
488 return unless @_ > 1;
489 my $gd = $self->gd;
490 if (3 < @_ ) {
491 if ( $gd->can('colorResolveAlpha') ) {
492 return $gd->colorResolveAlpha(@_);
493 } else {
494 pop @_; # discard alpha information
495 }
496 }
497 $gd->colorAllocate(@_);
498 }
499  
500 # Return an array of rgb values for a colour number
501  
502 sub pick_data_clr # number
503 {
504 my $self = shift;
505 _rgb($self->{dclrs}[$_[0] % @{$self->{dclrs}} - 1]);
506 }
507  
508 # contrib "Bremford, Mike" <mike.bremford@gs.com>
509 sub pick_border_clr # number
510 {
511 my $self = shift;
512  
513 ref $self->{borderclrs} ?
514 _rgb($self->{borderclrs}[$_[0] % @{$self->{borderclrs}} - 1]) :
515 _rgb($self->{accentclr});
516 }
517  
518 sub gd
519 {
520 my $self = shift;
521 return $self->{graph};
522 }
523  
524 sub export_format
525 {
526 my $proto = shift;
527 my @f = grep { GD::Image->can($_) &&
528 do {
529 my $g = GD::Image->new(5,5);
530 $g->colorAllocate(0,0,0);
531 $g->$_()
532 };
533 } qw(gif png jpeg xbm xpm gd gd2);
534 wantarray ? @f : $f[0];
535 }
536  
537 # The following method is undocumented, and will not be supported as
538 # part of the interface. There isn't really much reason to do so.
539 sub import_format
540 {
541 my $proto = shift;
542 # xpm now included despite bugginess--should document the problem, though
543 my @f = grep { GD::Image->can("newFrom\u$_") }
544 qw(gif png jpeg xbm xpm gd gd2);
545 wantarray ? @f : $f[0];
546 }
547  
548 sub can_do_ttf
549 {
550 my $proto = shift;
551 return GD::Text->can_do_ttf;
552 }
553  
554 # DEBUGGING
555 # data_dump obsolete now, use Data::Dumper
556  
557 sub die_abstract
558 {
559 my $self = shift;
560 my $msg = shift;
561 # ABSTRACT
562 confess
563 "Subclass (" .
564 ref($self) .
565 ") not implemented correctly: " .
566 (defined($msg) ? $msg : "unknown error");
567 }
568  
569 "Just another true value";
570  
571 __END__
« Graph/linespoints.pm ↑ Summary Graph/axestype.pm »