blib/lib/QWizard/Generator.pm untested

filter: Statementstmt 0.0% 0 / 303 Branchbran 0.0% 0 / 120 Conditioncond 0.0% 0 / 40 MC/DCmcdc 0.0% 0 / 25 Subroutinesub 0.0% 0 / 54 Podpod 0.0% 0 / 44 totaltotal 0.0% 0 / 586 CC 61 SCAR 44.2
CC
61
Cov
0%
get_arguments
306.0
do_graph_data
210.0
binize_x_data
72.0
CRAP 83.2
1 package QWizard::Generator;
2  
3 use AutoLoader;
4 use POSIX qw(isprint);
5 use strict;
6 our $VERSION = '3.15';
7 use QWizard::Storage::Memory;
8 require Exporter;
9 use File::Temp qw(tempfile);
10 use IO::File;
11  
12 @QWizard::Generator::ISA = qw(Exporter);
13 @QWizard::Generator::EXPORT = qw(qwdebug qwpref);
14  
15 our $AUTOLOAD;
16  
17 # just a base class.
18 #
19 # functions to implement:
20 # radio
21  
22 # default do-nothing subroutines. These are optional in sub-generators.
23 sub do_question_end {}
24 sub start_questions {}
25 sub end_questions {}
26 sub do_pass {};
27  
28 sub new {
29 die "should not be called directly\n";
30 }
31  
32 sub init_default_storage {
33 my $self = shift;
34 $self->{'datastore'} = new QWizard::Storage::Memory();
35 $self->{'prefstore'} = new QWizard::Storage::Memory();
36 $self->{'tmpdir'} = "/tmp" if (!$self->{'tmpdir'});
37 }
38  
39 # widgets that have fallbacks to more minimal widgets:
40 sub do_textbox {
41 my $self = shift;
42 $self->do_entry(@_);
43 }
44  
45 sub do_paragraph {
46 my $self = shift;
47 $self->do_label(@_);
48 }
49  
50 our $have_gd_graph = eval { require GD::Graph::lines; };
51 our $have_chart_graph = eval { require Chart::Lines; };
52  
53 our $def_width = 400;
54 our $def_height = 400;
55  
56 #
57 # returns a quantized X dataset from a sorted but non-linear x dataset
58 #
59 # INPUT points:
60 # [[X1, Y1],[X2, Y2]]
61 # OUTPUT quantized WIDTH number of buckets:
62 # [[min(X1), Y1], [min(X1)+(maxx-minx)/WIDTH, YJ]]
63 #
64 sub binize_x_data {
65 my ($self, $multidata, $q, $width) = @_;
66 my ($minx, $maxx);
67  
68 my ($newdata, $x, $xlab);
69  
70 if (!$q->{'multidata'}) {
71 $multidata = [$multidata];
72 }
73  
74 # calculates min and max X values from the datasets
75 foreach my $data (@$multidata) {
76 if (!defined($minx) || $minx > $data->[0][0]) {
77 $minx = $data->[0][0];
78 }
79 if (!defined($maxx) || $maxx < $data->[$#$data][0]) {
80 $maxx = $data->[$#$data][0];
81 }
82 }
83 my $diff = $maxx - $minx;
84 if ($diff == 0) {
85 print STDERR "no data to graph (time diff = 0)!\n";
86 print STDERR "minx: $minx, maxx: $maxx\n";
87 return [[]];
88 }
89 my $addative = 0;
90 foreach my $data (@$multidata) {
91 my $numc = $#{$data->[0]};
92 foreach my $d (@$data) {
93 my $xval = int($width * (($d->[0] - $minx) / $diff));
94 if (!exists($newdata->[0][$xval])) {
95 $newdata->[0][$xval] = $d->[0];
96 }
97 for ($x = 1; $x <= $numc; $x++) {
98 $newdata->[$x + $addative][$xval] = $d->[$x];
99 }
100 }
101 if (!$addative) {
102 # first row contained the indexes
103 $addative = -1;
104 }
105 $addative += $numc+1;
106 }
107  
108 for (my $i = 0; $i <= $#$newdata; $i++) {
109 for ($x = 1; $x <= $#{$newdata->[$i]}; $x++) {
110 if (!exists($newdata->[$i][$x])) {
111 $newdata->[$i][$x] = $newdata->[$i][$x-1];
112 }
113 }
114 }
115  
116 return $newdata;
117 }
118  
119 sub do_graph_data {
120 my ($self, $q, $wiz, $p, $data, $gopts) = @_;
121 my ($w, $h) = ($def_width, $def_height);
122 my @gopts = (
123 bgclr => 'white',
124 transparent => 0,
125 brush_size => 3,
126 max_x_ticks => 10,
127 );
128 push @gopts, @$gopts if ($gopts);
129 my %gopts = @gopts;
130 $gopts = \@gopts;
131 $w = $gopts{'-width'} if (exists($gopts{'-width'}));
132 $h = $gopts{'-height'} if (exists($gopts{'-height'}));
133  
134 return if (!$have_chart_graph || !$have_gd_graph);
135  
136 $data = $self->binize_x_data($data, $q, $w) if (!$q->{'already_in_bins'});
137  
138 if ($have_chart_graph && !$q->{'use_gd_graph'}) {
139  
140 my $charttype = "Lines";
141 $charttype = $gopts{'-charttype'} if (exists($gopts{'-charttype'}));
142  
143 # create the graph
144 my $gph = eval("require Chart::$charttype; return Chart::" . $charttype . '->new($w, $h);');
145  
146 # change various plotting conventions from GD::Graph to Chart::Lines
147 my %converts =
148 qw(
149 legend legend_labels
150 x_number_format f_x_tick
151 y_number_format f_y_tick
152 );
153  
154 foreach my $k (keys(%converts)) {
155 if (exists($gopts{$k})) {
156 push @gopts, $converts{$k} => $gopts{$k};
157 }
158 }
159 # XXX: hack to get around a collision
160 push @gopts, 'legend', 'right';
161  
162 # XXX: forced options
163 push @gopts, skip_x_ticks => ($w/6);
164  
165 # set the options to the passed list
166 $gph->set(@$gopts) if (defined($gopts));
167  
168 # plot everything to a file
169 my %hg = %gopts;
170 my ($fh, $fname) = $self->create_temp_fh(".png");
171 $gph->png($fh, $data);
172
173
174 # Ugh... we should be able to return either data or a file
175 # XXX: the sad thing is that later this is probably put into a file
176 $fh = new IO::File;
177 $fh->open("<$fname");
178 my ($fdata, $outdata);
179 while ($fh->read($fdata, 512)) {
180 $outdata .= $fdata;
181 }
182
183 return $outdata;
184 }
185  
186 if ($have_gd_graph) {
187 my $gph = GD::Graph::lines->new($w, $h);
188 $gph->set(@$gopts) if (defined($gopts));
189 my %hg = %gopts;
190 $gph->set_legend(@{$hg{'legend'}}) if (exists($hg{'legend'}));
191  
192 my $plot = $gph->plot($data);
193 if (!$plot) {
194 print STDERR "plot: " . $gph->error . "\n";
195 return;
196 }
197
198 return $plot->png ||
199 print STDERR "do_graph_data error: $gph->error\n";
200 }
201 }
202  
203 # Default storage = variable space
204  
205 sub qwparam {
206 my $self = shift;
207 return $self->{'datastore'}->access(@_);
208 }
209  
210 sub backup_params {
211 my $self = shift;
212 if ($#{$self->{'backupvars'}} > ($self->{'maxbackups'} || 10)) {
213 pop @{$self->{'backupvars'}};
214 }
215 unshift @{$self->{'backupvars'}}, {%{$self->{'datastore'}->get_all}};
216 }
217  
218 sub revert_params {
219 my $self = shift;
220 shift @{$self->{'backupvars'}};
221 if ($#{$self->{'backupvars'}} > -1) {
222 $self->{'datastore'}->set_all(shift @{$self->{'backupvars'}});
223 } else {
224 $self->{'datastore'}->set_all({});
225  
226 }
227 }
228  
229 #
230 # called by QWizard::pass_vars() to determine if we not be passing on
231 # particular variables.
232 #
233 sub skip_storage {
234 my ($self, $skiptok) = @_;
235 if (exists($self->{'delete_tokens'}) &&
236 exists($self->{'delete_tokens'}{$skiptok})) {
237 delete $self->{'delete_tokens'}{$skiptok};
238 return 1;
239 }
240 return 0;
241 }
242  
243 #
244 # potentially called by post_answers primary code to forget about a
245 # particular variable and not pass it on to forward screens.
246 #
247 sub forget_param {
248 my $self = shift;
249 map { $self->{'datastore'}->set($_,'');
250 $self->{'delete_tokens'}{$_} = 1
251 } @_;
252 }
253  
254 sub do_hidden {
255 my ($self, $wiz, $name, $val) = @_;
256 $self->{'datastore'}->set($name, $val);
257 }
258  
259 sub clear_params {
260 my $self = shift;
261 $self->{'datastore'}->reset();
262 @{$self->{'backupvars'}} = ();
263 }
264  
265 sub get_handler {
266 my ($self, $type, $q) = @_;
267 use Data::Dumper;
268 if (exists($self->{'typemap'}{$type})) {
269 return $self->{'typemap'}{$type};
270 }
271 }
272  
273 sub add_handler {
274 my ($self, $type, $fn, $argdef) = @_;
275 $self->{'typemap'}{$type}{'function'} = $fn;
276 $self->{'typemap'}{$type}{'argdef'} = $argdef;
277 }
278  
279 sub get_supported_tags {
280 my ($self) = @_;
281 return keys(%{$self->{'typemap'}});
282 }
283  
284 sub print_handler_tags {
285 my ($self, $tokformat, $nameformat, $endtext) = @_;
286 $tokformat = " %-20s %-10s\n" if (!$tokformat);
287 $nameformat = "%s arguments:\n" if (!$nameformat);
288 foreach my $t (sort keys(%{$self->{'typemap'}})) {
289 printf($nameformat, $t);
290 foreach my $arg (@{$self->{'typemap'}{$t}{'argdef'}}) {
291 next if ($arg->[0] eq 'forced');
292 my @tagargs = @$arg;
293 if ($#tagargs == 0) {
294 push @tagargs, "single";
295 } else {
296 my $swapit = $tagargs[0];
297 $tagargs[0] = $tagargs[1];
298 $tagargs[1] = $swapit;
299 }
300 printf($tokformat, @tagargs);
301 }
302 print $endtext if ($endtext);
303 }
304 }
305  
306 #
307 # argdef format:
308 # [
309 # [ TYPE, NAMEorSPECIAL, DEFAULT],
310 # ...
311 # ]
312 sub get_arguments {
313 my ($self, $wiz, $q, $argdef, $default) = @_;
314 my @args;
315 for (my $i = 0; $i <= $#$argdef; $i++) {
316 if (ref($argdef->[$i]) ne 'ARRAY') {
317 print STDERR "malformed argument definition: $argdef->[$i]\n";
318 push @args, undef;
319 next;
320 }
321 my $def = $argdef->[$i];
322 if ($def->[0] eq 'default') {
323 push @args, $default;
324 } elsif ($def->[0] eq 'forced') {
325 push @args, $def->[1];
326 } elsif ($def->[0] eq 'values,labels') {
327 push @args, $wiz->get_values_and_labels($q, $def->[1])
328 } elsif ($def->[0] eq 'multi') {
329 if (exists($q->{$def->[1]})) {
330 push @args, $wiz->get_values($q->{$def->[1]});
331 } else {
332 push @args, $def->[2];
333 }
334 } elsif ($def->[0] eq 'single') {
335 if (exists($q->{$def->[1]})) {
336 push @args, $wiz->get_value($q->{$def->[1]});
337 } else {
338 push @args, $def->[2];
339 }
340 } elsif ($def->[0] eq 'norecurse') {
341 if (exists($q->{$def->[1]})) {
342 push @args, $wiz->get_value($q->{$def->[1]}, 1);
343 } else {
344 push @args, $def->[2];
345 }
346 } elsif ($def->[0] eq 'norecursemulti') {
347 if (exists($q->{$def->[1]})) {
348 push @args, $wiz->get_values($q->{$def->[1]}, 1);
349 } else {
350 push @args, $def->[2];
351 }
352 } elsif ($def->[0] eq 'labels') {
353 if (exists($q->{$def->[1]})) {
354 push @args, $wiz->get_labels($q);
355 } else {
356 push @args, $def->[2];
357 }
358 } elsif ($def->[0] eq 'noexpand') {
359 if (exists($q->{$def->[1]})) {
360 push @args, $q->{$def->[1]};
361 } else {
362 push @args, $def->[2];
363 }
364 } else {
365 print STDERR "unknown argument type: $def->[0]\n";
366 }
367 }
368 return \@args;
369 }
370  
371 # preferences
372  
373 sub qwpref {
374 my $self = shift;
375 return $self->{'prefstore'}->access(@_);
376 }
377  
378 # file uploads
379  
380 sub qw_upload_fh {
381 my ($self) = shift;
382 my ($it);
383 my $ret;
384 if (ref($self) =~ /QWizard/) {
385 $it = shift;
386 } else {
387 $it = $self;
388 }
389  
390 my $fh = new IO::File();
391 $fh->open("<" . $self->qwparam($it));
392  
393 return $fh;
394 }
395  
396 # this is overriden by the HTML handler to return a pointer to a temp file
397 sub qw_upload_file {
398 my ($self) = shift;
399 my ($it);
400 my $ret;
401 if (ref($self) =~ /QWizard/) {
402 $it = shift;
403 } else {
404 $it = $self;
405 }
406  
407 return $self->qwparam($it);
408 }
409  
410 ######################################################################
411 ## convenience functions
412  
413 sub make_displayable {
414 my ($self, $str);
415 if ($#_ > 0) {
416 ($self, $str) = @_;
417 } else {
418 ($str) = @_;
419 }
420  
421 if (defined($str) && $str ne '' && !isprint($str)) {
422 $str = "0x" . (unpack("H*", $str))[0];
423 }
424 return $str;
425 }
426  
427 ######################################################################
428 ## temporary file handling
429  
430 sub create_temp_fh {
431 my ($self, $sfx) = @_;
432 mkdir($self->{'tmpdir'}) if (! -d $self->{'tmpdir'});
433 my ($fh, $filename) = tempfile("qwHTMLXXXXXX", SUFFIX => $sfx,
434 DIR => $self->{'tmpdir'} || "/tmp/");
435 return ($fh, $filename);
436 }
437  
438  
439 ## temporary file creation if needed by child classes
440 sub create_temp_file {
441 my ($self, $sfx, $data) = @_;
442  
443 my ($fh, $filename) = $self->create_temp_fh($sfx);
444  
445 if (ref($data) eq 'IO::File' || ref($data) eq 'Fh') {
446 while (<$data>) {
447 print $fh $_;
448 }
449 } else {
450 print $fh $data;
451 }
452 $fh->close();
453  
454 return $filename;
455 }
456  
457 ######################################################################
458 # image path handling
459 #
460  
461 sub find_image_path {
462 my ($self, $file) = @_;
463  
464 # return it if it's already a fullyqualified path
465 # XXX: win32 issues
466 return if (!defined($file));
467 return $file if ($file eq '' || $file =~ /^\//);
468  
469 # get a path list
470 my $paths = $self->{'imgpaths'};
471 $paths = [$paths] if (ref($paths) ne 'ARRAY');
472  
473 # search the paths till we get a hit.
474 foreach my $path (@$paths) {
475 if (-f "$path/$file") {
476 return "$path/$file";
477 }
478 }
479  
480 return;
481 }
482  
483 ######################################################################
484 # accelerator base functions
485 #
486  
487 # removes at least the first _ from the label
488 sub remove_accelerator {
489 my $text = shift;
490 $text =~ s/_//;
491 return $text;
492 }
493  
494 # erases memory of auto_accelerators already used
495 sub initialize_auto_accelerator {
496 my $self = shift;
497  
498 $self->{'auto_accelerators'} =
499 # reserved set
500 {
501 N => 1, # Next
502 B => 1, # Back
503 R => 1, # Refresh
504 };
505 }
506  
507 # Adds in an accelerator to a app if it doesn't exist
508 sub add_accelerator {
509 my ($self, $text) = @_;
510 return $text if ($self->{'no_auto_accelerators'});
511 return $text if ($text =~ s/^!//); # reserve ! as a don't-accelerate this
512 my $accelmap = $self->{'auto_accelerators'};
513 return $text if ($text =~ /(_)/ && exists($accelmap->{$1}));
514 my @lets = split(//,$text);
515 for (my $i = 0; $i <= $#lets; $i++) {
516 if ($lets[$i] =~ /[a-zA-Z]/ && !exists($accelmap->{lc($lets[$i])})) {
517 $accelmap->{lc($lets[$i])} = 1;
518 $lets[$i] = '_' . $lets[$i];
519 return join("",@lets);
520 }
521 }
522 return $text;
523 }
524  
525  
526  
527  
528  
529 ## dummy functions for overriding if needed by child classes
530  
531 # called once in the very beginning
532 sub start_primaries {}
533 # called once at the very end
534 sub end_primaries {}
535 # called once before first primary
536 sub do_top_bar {}
537 # called once before first primary
538 sub do_left_side {}
539 # called once after last primary
540 sub do_right_side {}
541 # called once per primary per screen:
542 sub start_main_section {}
543 # called once per primary per screen:
544 sub end_main_section {}
545 # called once before first primary on screen:
546 sub start_center_section {}
547 # called once after last primary on screen:
548 sub end_center_section {}
549 # called once after qwizard is completely finished; should remove windows, etc.
550 sub finished {}
551 # called to display a progress window
552 sub set_progress {}
553  
554  
555 ## All other missing functions are errors
556  
557 sub AUTOLOAD {
558 my $sub = $AUTOLOAD;
559 my $mod = $AUTOLOAD;
560 $mod =~ s/::[^:]*$//;
561 $sub =~ s/.*:://;
562  
563 die "FATAL PROBLEM: Your widget generator \"$mod\" doesn't support the \"$sub\" function";
564 }
565  
566 1;
567 __END__