| 1 | package Language::Homespring::Visualise; | ||
| 2 | |||
| 3 | $VERSION = 0.02; | ||
| 4 | |||
| 5 | use warnings; | ||
| 6 | use strict; | ||
| 7 | |||
| 8 | sub new { | ||
| 9 | my $class = shift; | ||
| 10 | my $self = bless {}, $class; | ||
| 11 | |||
| 12 | my $options = shift; | ||
| 13 | $self->{interp} = $options->{interp}; | ||
| 14 | |||
| 15 | return $self; | ||
| 16 | } | ||
| 17 | |||
| 18 | sub do { | ||
| 19 | my ($self) = @_; | ||
| 20 | my @lines; | ||
| 21 | |||
| 22 | # initiate lines | ||
| 23 | my $lines = $self->{interp}->{root_node}->get_depth(); | ||
| 24 | for(my $i=0; $i<$lines; $i++){ | ||
| 25 | $lines[$i] = '-> '; | ||
| 26 | } | ||
| 27 | |||
| 28 | # do stuff | ||
| 29 | my %nodes = ( 0 => $self->{interp}->{root_node} ); | ||
| 30 | |||
| 31 | while (scalar(keys(%nodes))){ | ||
| 32 | |||
| 33 | # get longest name | ||
| 34 | my $longest = 0; | ||
| 35 | for (values %nodes){ | ||
| 36 | my $l = length($_->{node_name_safe}); | ||
| 37 | $longest = $l if ($l > $longest); | ||
| 38 | } | ||
| 39 | |||
| 40 | # add nodes and stems | ||
| 41 | for (my $i=0; $i<$lines; $i++){ | ||
| 42 | my $line = $nodes{$i}->{node_name_safe}; | ||
| 43 | my $extra = $longest+1-(($line)?length($line):0); | ||
| 44 | my $extra_char = ' '; | ||
| 45 | $extra_char = '-' if ($line && scalar(@{$nodes{$i}->{child_nodes}})); | ||
| 46 | $line .= $extra_char x $extra; | ||
| 47 | $lines[$i] .= $line; | ||
| 48 | } | ||
| 49 | |||
| 50 | # calculate news nodes | ||
| 51 | my %new_nodes; | ||
| 52 | |||
| 53 | for (keys(%nodes)){ | ||
| 54 | my $node = $nodes{$_}; | ||
| 55 | my $index = $_; | ||
| 56 | for my $child(@{$node->{child_nodes}}){ | ||
| 57 | #print "INSERTING AT $index -> $child->{node_name_safe} is child of $node->{node_name_safe}\n"; | ||
| 58 | $new_nodes{$index} = $child; | ||
| 59 | $index += $child->get_depth(); | ||
| 60 | } | ||
| 61 | } | ||
| 62 | |||
| 63 | # add junctions | ||
| 64 | my %junctions; | ||
| 65 | for (keys %nodes){ | ||
| 66 | my $index = $_; | ||
| 67 | my $node = $nodes{$_}; | ||
| 68 | my $child_count = scalar(@{$node->{child_nodes}}); | ||
| 69 | if ($child_count){ | ||
| 70 | $junctions{$index} = ($child_count==1)?'--':'+-'; | ||
| 71 | my @nodes = @{$node->{child_nodes}}; | ||
| 72 | pop @nodes; | ||
| 73 | for (@nodes){ | ||
| 74 | for (my $j=0; $j<$_->get_depth()-1; $j++){ | ||
| 75 | $junctions{$index+$j+1} = '| '; | ||
| 76 | } | ||
| 77 | $junctions{$index+$_->get_depth()} = '+-'; | ||
| 78 | $index += $_->get_depth(); | ||
| 79 | } | ||
| 80 | } | ||
| 81 | } | ||
| 82 | for (my $i=0; $i<$lines; $i++){ | ||
| 83 | $lines[$i] .= ($junctions{$i})?$junctions{$i}:' '; | ||
| 84 | } | ||
| 85 | |||
| 86 | # assign for next round | ||
| 87 | %nodes = %new_nodes; | ||
| 88 | } | ||
| 89 | |||
| 90 | # join lines | ||
| 91 | |||
| 92 | return join("\n",@lines)."\n"; | ||
| 93 | } | ||
| 94 | |||
| 95 | __END__ |