- my $sub = sub {
- my $cont = shift;
- my $children = $cont->children;
- return if @$children < 2;
- $cont->set_children( $ordersub->( $children ) );
- };
- $self->iterate_down( undef, $sub );
- undef $sub;
-}
-
-# non-recursive version of recurse_down to avoid stack depth warnings
-sub recurse_down {
- my ($self, $callback) = @_;
- my %seen;
- my @q = ($self);
- while (my $cont = shift @q) {
- $seen{$cont}++;
- $callback->($cont);
-
- if (my $next = $cont->{next}) {
- if ($seen{$next}) {
- $cont->{next} = undef;
- } else {
- push @q, $next;
- }
- }
- if (my $child = $cont->{child}) {
- if ($seen{$child}) {
- $cont->{child} = undef;
- } else {
- push @q, $child;
- }
- }
- }
-}
-
-sub iterate_down {
- my $self = shift;
- my ($before, $after) = @_;
-
- my %seen;
- my $walk = $self;
- my $depth = 0;
- my @visited;
- while ($walk) {
- push @visited, [ $walk, $depth ];
- $before->($walk, $depth) if $before;
-
- # spot/break loops
- $seen{$walk}++;
-
- my $child = $walk->{child};
- if ($child && $seen{$child}) {
- $walk->{child} = $child = undef;
- }
-
- my $next = $walk->{next};
- if ($next && $seen{$next}) {
- $walk->{next} = $next = undef;
- }
-
- # go down, or across
- if ($child) {
- $next = $child;
- ++$depth;
- }
-
- # no next? look up
- if (!$next) {
- my $up = $walk;
- while ($up && !$next) {
- $up = $up->{parent};
- --$depth;
- $next = $up->{next} if $up;
- }
- }
- $walk = $next;
+ $c = [ grep { !$seen{$_}++ && visible($_, $srch) } values %$c ];
+ $c = $ordersub->($c) if scalar @$c > 1;
+ $cur->{children} = $c; # ...becomes an arrayref
+ push @q, @$c;