| 1 | # Graph an object structure using GraphViz. | ||
| 2 | use Class::Prototyped; | ||
| 3 | use GraphViz; | ||
| 4 | use IO::File; | ||
| 5 | |||
| 6 | package Class::Prototyped::Mirror; | ||
| 7 | $Class::Prototyped::Mirror::VERSION = '1.16'; | ||
| 8 | |||
| 9 | my %graphOpts = ( | ||
| 10 | R => 1, # H or V orientation | ||
| 11 | i => 'png', # output format | ||
| 12 | u => 0, # output image map? | ||
| 13 | s => 1, # what kind of image map? | ||
| 14 | ); | ||
| 15 | |||
| 16 | sub graphOptions { | ||
| 17 | shift if ref( $_[0] ); | ||
| 18 | %graphOpts = ( %graphOpts, @_ ); | ||
| 19 | } | ||
| 20 | |||
| 21 | # look familiar? | ||
| 22 | sub visitAllParents { | ||
| 23 | my $mirror = shift; | ||
| 24 | my $sub = shift; | ||
| 25 | my $userData = shift; | ||
| 26 | my $stack = shift || []; | ||
| 27 | my $seen = shift || {}; | ||
| 28 | |||
| 29 | push ( @$stack, $mirror ); | ||
| 30 | $sub->( $parentMirror, $userData, $stack ); | ||
| 31 | foreach my $parent ( $mirror->parents ) { | ||
| 32 | next unless UNIVERSAL::can( $parent, 'reflect' ); | ||
| 33 | my $parentMirror = $parent->reflect; | ||
| 34 | $parentMirror->visitAllParents( $sub, $userData, $stack, $seen ); | ||
| 35 | } | ||
| 36 | pop (@$stack); | ||
| 37 | } | ||
| 38 | |||
| 39 | sub _graphOneObject { | ||
| 40 | my $mirror = shift; | ||
| 41 | my $data = shift; | ||
| 42 | my $g = $data->[0]; | ||
| 43 | my $slotName = $data->[1]; | ||
| 44 | my $stack = shift; | ||
| 45 | |||
| 46 | my $name = $stack->[-1]->getSlot($slotName); | ||
| 47 | $g->add_node($name); | ||
| 48 | |||
| 49 | my $fromName; | ||
| 50 | |||
| 51 | if ( @$stack >= 2 ) { | ||
| 52 | $fromName = $stack->[-2]->getSlot($slotName); | ||
| 53 | $g->add_edge( $fromName, $name ); | ||
| 54 | } | ||
| 55 | } | ||
| 56 | |||
| 57 | sub graph { | ||
| 58 | shift if UNIVERSAL::isa( $_[0], 'Class::Prototyped::Mirror' ); | ||
| 59 | my $slotName = shift; | ||
| 60 | |||
| 61 | my $outfile = 'graph.png'; | ||
| 62 | my $g = GraphViz->new( rankdir => $graphOpts{R} || 0 ); | ||
| 63 | |||
| 64 | foreach my $obj (@_) { | ||
| 65 | my $mirror = $obj->reflect; | ||
| 66 | $mirror->visitAllParents( \&_graphOneObject, [ $g, $slotName ] ); | ||
| 67 | } | ||
| 68 | |||
| 69 | my $output = IO::File->new( $outfile, 'w' ) | ||
| 70 | or die "can't open $outfile: $!\n"; | ||
| 71 | $output->print( eval "\$g->as_$graphOpts{i}()" ); | ||
| 72 | $output->close(); | ||
| 73 | |||
| 74 | if ( $graphOpts{u} ) { | ||
| 75 | STDOUT->print( exists( $graphOpts{s} ) ? $g->as_imap : $g->as_ismap() ); | ||
| 76 | } | ||
| 77 | } | ||
| 78 | |||
| 79 | 1; |