File: Graph.pm

package info (click to toggle)
libsvg-tt-graph-perl 0.14-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 412 kB
  • ctags: 186
  • sloc: perl: 5,564; makefile: 2
file content (508 lines) | stat: -rwxr-xr-x 11,322 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
package SVG::TT::Graph;

use strict;
use Carp;

use vars qw($VERSION $AUTOLOAD);
use Template;
use POSIX;

$VERSION = '0.14';

=head1 NAME

SVG::TT::Graph - Base object for generating SVG Graphs

=head1 SYNOPSIS

  package SVG::TT::Graph::GRAPH_TYPE
  use SVG::TT::Graph;
  use base qw(SVG::TT::Graph);

  sub _set_defaults {
    my $self = shift;

    my %default = (
        'keys'  => 'value',
    );
    while( my ($key,$value) = each %default ) {
      $self->{config}->{$key} = $value;
    }
  }

  sub get_template {
    my $self = shift;
    # read in template
    my $template = 'set the template';
    return $template;
  }
  
  # optional - called when object is created
  sub _init {
    my $self = shift;
  # any testing you want to do.
  
  }
  
  1;
  
  In your script...
  
  use SVG::TT::Graph::GRAPH_TYPE;
  
  my $width = '500',
  my $heigh = '300',
  my @fields = qw(field_1 field_2 field_3);
  
  my $graph = SVG::TT::Graph::GRAPH_TYPE->new({
    # Required for some graph types
    'fields'           => \@fields,
    # .. other config options
    'height' => '500',
  });
  
  my @data = qw(23 56 32);
  $graph->add_data({
    'data' => \@data,
    'title' => 'Sales 2002',
  });
  
  # find a config options value
  my $config_value = $graph->config_option();
  # set a config option value
  $graph->config_option($config_value);
  
  # All graphs support SVGZ (compressed SVG) if 
  # Compress::Zlib is available.
  # either 'compress' => 1 config option, or
  $graph->compress(1);

  # All graph SVGs can be tidied if XML::Tidy
  # Compress::Zlib is installed.
  # either 'tidy' => 1 config option, or
  $graph->tidy(1);

  print "Content-type: image/svg+xml\n\n";
  print $graph->burn();

=head1 DESCRIPTION

This package should be used as a base for creating SVG graphs. If XML::Tidy is
installed, the SVG files generated are tidied.

See SVG::TT::Graph::Line for an example.

=cut

sub new {
  my ($proto,$conf) = @_;
  my $class = ref($proto) || $proto;
  my $self = {};

  bless($self, $class);

  if($self->can('_set_defaults')) {
    # Populate with local defaults
    $self->_set_defaults();
  } else {
    croak "$class should have a _set_defaults method";
  }

  # overwrite defaults with user options
  while( my ($key,$value) = each %{$conf} ) {
    $self->{config}->{$key} = $value;
  }

  # Allow the inheriting modules to do checks
  if($self->can('_init')) {
    $self->_init();
  }

  return $self;
}

=head1 METHODS

=head2 add_data()

  my @data_sales_02 = qw(12 45 21);

  $graph->add_data({
    'data' => \@data_sales_02,
    'title' => 'Sales 2002',
  });

This method allows you do add data to the graph object.
It can be called several times to add more data sets in.

=cut
  
sub add_data {
  my ($self, $conf) = @_;
  # create an array
  unless(defined $self->{'data'}) {
    my @data;
    $self->{'data'} = \@data;
  }
  
  croak 'no fields array ref' 
  unless defined $self->{'config'}->{'fields'} 
    && ref($self->{'config'}->{'fields'}) eq 'ARRAY';

  if(defined $conf->{'data'} && ref($conf->{'data'}) eq 'ARRAY') {
    my %new_data;
    @new_data{ map { s/&/&/; $_ } @{$self->{'config'}->{'fields'}}} = @{$conf->{'data'}};
    my %store = (
      'data' => \%new_data,
    );
    $store{'title'} = $conf->{'title'} if defined $conf->{'title'};
    push (@{$self->{'data'}},\%store);
    return 1;
  }
  return undef;
}

=head2 clear_data()

  my $graph->clear_data();

This method removes all data from the object so that you can
reuse it to create a new graph but with the same config options.

=cut

sub clear_data {
  my $self = shift;
  my @data;
  $self->{'data'} = \@data;
}

=head2 burn()

  print $graph->burn();

This method processes the template with the data and
config which has been set and returns the resulting SVG.

This method will croak unless at least one data set has
been added to the graph object.

=cut

sub burn {
  my $self = shift;
  
  # Check we have at least one data value
  croak "No data available" 
    unless scalar(@{$self->{'data'}}) > 0;
        
  # perform any calculations prior to burn
  $self->calculations() if $self->can('calculations');
  croak ref($self) . ' must have a get_template method.' 
    unless $self->can('get_template');
  my $template = $self->get_template();
  my %vals = (
    'data'             => $self->{'data'},     # the data
    'config'           => $self->{'config'},   # the configuration
    'calc'             => $self->{'calc'},     # the calculated values
    'sin'              => \&_sin_it,
    'cos'              => \&_cos_it,
    'predefined_color' => \&_predefined_color,
    'random_color'     => \&_random_color,
  );
  
  # euu - hack!! - maybe should just be a method 
  $self->{sin} = \&_sin_it;
  $self->{cos} = \&_cos_it;

  # set up TT object
  my %config = (
    POST_CHOMP   => 1,
    INCLUDE_PATH => '/',
    #DEBUG       => 'undef', # TT warnings on, useful for debugging, finding undef values
  );
  my $tt = Template->new( \%config );
  my $file;
  my $template_response = $tt->process( \$template, \%vals, \$file );
  if($tt->error()) {
    croak "Template error: " . $tt->error . "\n" if $tt->error;
  }

  # tidy SVG if required
  if ($self->tidy()) {
    if (eval "require XML::Tidy") {
      # remove the doctype tag temporarily because it seems to cause trouble
      $file =~ s/(<!doctype svg .+?>)//si;
      my $doctype = $1;
      # tidy
      my $tidy_obj = XML::Tidy->new( 'xml' => $file );
      $tidy_obj->tidy();
      $file = $tidy_obj->toString();
      # re-add the doctype
      if (defined $doctype) {
        $file =~ s/(<\?xml.+?\?>)/$1\n$doctype/si;
      }
      # even more tidy
      $file = $self->_tidy_more($file);
    } else {
      croak "Error tidying the SVG file: XML::Tidy does not seem to be installed properly";
    }
  }

  # compress SVG if required
  if ($self->compress()) {
    if (eval "require Compress::Zlib") {
      $file = Compress::Zlib::memGzip($file); 
    } else {
      croak "Error compressing the SVG file: Compress::Zlib does not seem to be installed properly";
    }
  }
    
  return $file;
}



sub _sin_it {
  return sin(shift);
}


sub _cos_it {
  return cos(shift);
}


=head2 compress()

  $graph->compress(1);

If Compress::Zlib is installed, the content of the SVG file can be compressed.
This get/set method controls whether or not to compress. The default is 1 if
Compress::Zlib is available, 0 otherwise.

=cut

sub compress {
  my ($self, $val) = @_;
  # set the default compress value
  if (not defined $self->{config}->{compress}) {
    if ( eval "require Compress::Zlib" ) {
      $self->{config}->{compress} = 1;
    } else {
      $self->{config}->{compress} = 0;
    }
  }
  # set the user-defined compress value
  if (defined $val) {
    $self->{config}->{compress} = $val;
  }
  # get the compress value
  return $self->{config}->{compress};
}


=head2 tidy()

  $graph->tidy(1);

If XML::Tidy is installed, the content of the SVG file can be formatted in a
prettier way. This get/set method controls whether or not to tidy. The default
is 1 if XML::Tidy is available, 0 otherwise.

=cut

sub tidy {
  my ($self, $val) = @_;
  # set the default tidy value
  if (not defined $self->{config}->{tidy}) {
    if ( eval "require XML::Tidy" ) {
      $self->{config}->{tidy} = 1;
    } else {
      $self->{config}->{tidy} = 0;
    }
  }
  # set the user-defined tidy value
  if (defined $val) {
    $self->{config}->{tidy} = $val;
  }
  # get the tidy value
  return $self->{config}->{tidy};
}


sub _tidy_more {
  # Remove extra spaces in the SVG <path> tag
  my ($self, $svg_string) = @_;
  while ($svg_string =~ s/(<path .*? )\s+(.*?"\s*?\/>)/$1$2/mgi) {};
  return $svg_string;
}


sub _random_color {
  # Generate the rgb code for a randomly selected color
  my $rgb = 'rgb('.int(rand(256)).','.int(rand(256)).','.int(rand(256)).')';
  return $rgb;
}


sub _predefined_color {
  # Get the hexadecimal code for one of 12 predefined colors
  my ($num) = shift;
  my @colors = ("#ff0000", "#0000ff", "#00ff00", "#ffcc00", "#00ccff",
    "#ff00ff", "#00ffff", "#ffff00", "#cc6666", "#663399", "#339900", "#9966FF");
  my $hex;
  if ($num-1 < scalar @colors) {
    $hex = $colors[$num-1];
  }
  return $hex;
}

# Calculate a scaling range and divisions to be aesthetically pleasing
# Parameters:
#   value range
# Returns
#   (revised range, division size, division precision)
sub _range_calc () {
  my ($self, $range) = @_;

  my ($max,$division);
  my $count = 0;
  my $value = $range;
  
  if ($value == 0) {
    # Can't do much really
    $division = 0.2;
    $max = 1;
    return ($max,$division,1);
  }
  
  if ($value < 1) {
    while ($value < 1) {
      $value *= 10;
      $count++;
    }
    $division = 1;
    while ($count--) {
      $division /= 10;
    }
    $max = ceil($range / $division) * $division;
  }
  else {
    while ($value > 10) {
      $value /= 10;
      $count++;
    }
    $division = 1;
    while ($count--) {
      $division *= 10;
    }
    $max = ceil($range / $division) * $division;
  }
  
  if (int($max / $division) <= 2) {
    $division /= 5;
    $max = ceil($range / $division) * $division;
  }
  elsif (int($max / $division) <= 5) {
    $division /= 2;
    $max = ceil($range / $division) * $division;
  }
  
  if ($division >= 1) {
    $count = 0;  
  }
  else {
    $count = length($division) - 2;
  }

  return ($max,$division,$count);
}


# Returns true if config value exists, is defined and not ''
sub _is_valid_config() { 
  my ($self,$name) = @_;
  return ((exists $self->{config}->{$name}) && (defined $self->{config}->{$name}) && ($self->{config}->{$name} ne ''));
}


=head2 config methods

  my $value = $graph->method();
  $graph->method($value);

This object provides autoload methods for all config
options defined in the _set_default method within the
inheriting object.

See the SVG::TT::Graph::GRAPH_TYPE documentation for a list.

=cut

## AUTOLOAD FOR CONFIG editing

sub AUTOLOAD {
  my $name = $AUTOLOAD;
  $name =~ s/.*://;

  croak "No object supplied" unless $_[0];
  if(defined $_[0]->{'config'}->{$name}) {
    if(defined $_[1]) {
      # set the value
      $_[0]->{'config'}->{$name} = $_[1];
    }
    return $_[0]->{'config'}->{$name} if defined $_[0]->{'config'}->{$name};
    return undef;
  } else {
    croak "Method: $name can not be used with " . ref($_[0]);
  }
}


# As we have AUTOLOAD we need this
sub DESTROY {
}


1;
__END__

=head1 EXAMPLES

For examples look at the project home page http://leo.cuckoo.org/projects/SVG-TT-Graph/

=head1 EXPORT

None by default.

=head1 ACKNOWLEDGEMENTS

Thanks to Foxtons for letting us put this on CPAN.
Todd Caine for heads up on reparsing the template (but not using atm)
David Meibusch for TimeSeries and a load of other ideas
Thanks for all the patches supplied by Andrew Ruthven and others

=head1 AUTHOR

Leo Lapworth (LLAP@cuckoo.org) and Stephen Morgan (TT and SVG)

=head1 SEE ALSO

L<SVG::TT::Graph::Line>,
L<SVG::TT::Graph::Bar>,
L<SVG::TT::Graph::BarHorizontal>,
L<SVG::TT::Graph::BarLine>,
L<SVG::TT::Graph::Pie>,
L<SVG::TT::Graph::TimeSeries>,
L<Compress::Zlib>,
L<XML::Tidy>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2003, Leo Lapworth 

This module is free software; you can redistribute it or 
modify it under the same terms as Perl itself. 

=cut