Pod/Tree.pm untested

filter: Statementstmt 0.0% 0 / 417 Branchbran 0.0% 0 / 114 Conditioncond 0.0% 0 / 77 MC/DCmcdc 0.0% 0 / 46 Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 705 CC 58 SCAR 37.0
CC
58
Cov
0%
Fill
90.0
Populate
72.0
_FillDone
72.0
CRAP 40.5
1 # -*- perl -*-
2  
3 #
4 # Author: Slaven Rezic
5 #
6 # Copyright (C) 2001,2004,2007,2008,2012,2015 Slaven Rezic. All rights reserved.
7 # This package is free software; you can redistribute it and/or
8 # modify it under the same terms as Perl itself.
9 #
10 # Mail: slaven@rezic.de
11 # WWW: http://www.rezic.de/eserte/
12 #
13  
14 package Tk::Pod::Tree;
15  
16 =head1 NAME
17  
18 Tk::Pod::Tree - list Pod file hierarchy
19  
20  
21 =head1 SYNOPSIS
22  
23 use Tk::Pod::Tree;
24  
25 $parent->PodTree;
26  
27 =head1 WIDGET-SPECIFIC OPTIONS
28  
29 =over 4
30  
31 =item Name: B<-showcommand>
32  
33 Specifies a callback for selecting a Pod module (Button-1 binding).
34  
35 =item Name: B<-showcommand2>
36  
37 Specifies a callback for selecting a Pod module in a different window
38 (Button-2 binding).
39  
40 =item Name: B<-usecache>
41  
42 True, if a cache of Pod modules should be created and used. The
43 default is true.
44  
45 =back
46  
47 =head1 DESCRIPTION
48  
49 The B<Tk::Pod::Tree> widget shows all available Perl Pod documentation
50 in a tree.
51  
52 =cut
53  
54 use strict;
55 use vars qw($VERSION @ISA @POD %EXTRAPODDIR $ExtraFindPods);
56 $VERSION = '5.11';
57  
58 use base 'Tk::Tree';
59  
60 use File::Spec;
61  
62 use Tk::Pod::FindPods;
63 use Tk::ItemStyle;
64 use Tk qw(Ev);
65  
66 Construct Tk::Widget 'PodTree';
67  
68 my $search_history;
69  
70 use constant SEP => "/";
71  
72 BEGIN { @POD = @INC }
73  
74 BEGIN { # Make a DEBUG constant very first thing...
75 if(defined &DEBUG) {
76 } elsif(($ENV{'TKPODDEBUG'} || '') =~ m/^(\d+)/) { # untaint
77 my $debug = $1;
78 *DEBUG = sub () { $debug };
79 } else {
80 *DEBUG = sub () {0};
81 }
82 }
83  
84 ######################################################################
85 use Class::Struct;
86 struct '_PodEntry' => [
87 'uri' => "\$",
88 'type' => "\$",
89 'name' => "\$",
90 ];
91 sub _PodEntry::create {
92 my $e = shift->new;
93 $e->uri(shift);
94 $e;
95 }
96 sub _PodEntry::file {
97 my $uri = shift->uri;
98 local $^W = 0;
99 ($uri =~ /^file:(.*)/)[0];
100 }
101 ######################################################################
102  
103 sub Dir {
104 my $class = shift;
105 unshift @POD, @_;
106 $EXTRAPODDIR{$_} = 1 for (@_);
107 }
108  
109 sub ClassInit {
110 my ($class,$mw) = @_;
111 $class->SUPER::ClassInit($mw);
112 $mw->bind($class, '<3>', ['PostPopupMenu', Ev('X'), Ev('Y')] )
113 if $Tk::VERSION > 800.014;
114  
115 my $set_anchor_and_sel = sub {
116 my($w, $ent) = @_;
117 $w->anchorSet($ent);
118 $w->selectionClear;
119 $w->selectionSet($ent);
120 };
121  
122 # Force callbacks to be treated as methods. This is done by putting
123 # the $widget reference at the beginning of the Tk::Callback array
124 my $inherited_cb = sub {
125 my($w, $cb) = @_;
126 if (UNIVERSAL::isa($cb, "Tk::Callback")) {
127 my $new_cb = bless [$w, @$cb], 'Tk::Callback';
128 $new_cb->Call;
129 } else {
130 # XXX OK?
131 $cb->($w);
132 }
133 };
134  
135 # Add functionality to some callbacks:
136 my $orig_home = $mw->bind($class, "<Home>");
137 $mw->bind($class, "<Home>" => sub {
138 my $w = shift;
139 $inherited_cb->($w, $orig_home);
140 $set_anchor_and_sel->($w, ($w->infoChildren)[0]);
141 });
142 my $orig_end = $mw->bind($class, "<End>");
143 $mw->bind($class, "<End>" => sub {
144 my $w = shift;
145 $inherited_cb->($w, $orig_end);
146 # get last opened entry
147 my $last = ($w->infoChildren)[-1];
148 while ($w->getmode($last) eq "close" && $w->infoChildren($last)) {
149 $last = ($w->infoChildren($last))[-1];
150 }
151 $set_anchor_and_sel->($w, $last);
152 });
153 my $orig_prior = $mw->bind($class, "<Prior>");
154 $mw->bind($class, "<Prior>" => sub {
155 my $w = shift;
156 $inherited_cb->($w, $orig_prior);
157 my $ent = $w->nearest(10); # XXX why 10?
158 return if !defined $ent;
159 $set_anchor_and_sel->($w, $ent);
160 });
161 my $orig_next = $mw->bind($class, "<Next>");
162 $mw->bind($class, "<Next>" => sub {
163 my $w = shift;
164 $inherited_cb->($w, $orig_next);
165 my $ent = $w->nearest($w->height - 10); # XXX why 10?
166 return if !defined $ent;
167 $set_anchor_and_sel->($w, $ent);
168 });
169 }
170  
171 sub Populate {
172 my($w,$args) = @_;
173  
174 $args->{-separator} = SEP;
175  
176 my $show_command = sub {
177 my($w, $cmd, $ent) = @_;
178  
179 my $data = $w->info('data', $ent);
180 if ($data) {
181 $w->Callback($cmd, $w, $data);
182 }
183 };
184  
185 my $show_command_mouse = sub {
186 my $w = shift;
187 my $cmd = shift || '-showcommand';
188  
189 my $Ev = $w->XEvent;
190 my $ent = $w->GetNearest($Ev->y, 1);
191 return unless (defined $ent and length $ent);
192  
193 my @info = $w->info('item',$Ev->x, $Ev->y);
194 if (defined $info[1] && $info[1] eq 'indicator') {
195 $w->Callback(-indicatorcmd => $ent, '<Arm>');
196 return;
197 }
198  
199 $show_command->($w, $cmd, $ent);
200 };
201  
202 my $show_command_key = sub {
203 my $w = shift;
204 my $cmd = shift || '-showcommand';
205  
206 my($ent) = $w->selectionGet;
207 return unless (defined $ent and length $ent);
208  
209 if ($w->info('children', $ent)) {
210 $w->open($ent);
211 }
212  
213 $show_command->($w, $cmd, $ent);
214 };
215  
216 $w->bind("<1>" => sub { $show_command_mouse->(shift) });
217 foreach (qw/space Return/) {
218 $w->bind("<$_>" => sub { $show_command_key->(shift) });
219 }
220  
221 foreach (qw/2 Shift-1/) {
222 $w->bind("<$_>" => sub { $show_command_mouse->(shift, '-showcommand2') });
223 }
224  
225 $w->SUPER::Populate($args);
226  
227 $w->{Style} = {};
228 $w->{Style}{'core'} = $w->ItemStyle('imagetext',
229 -foreground => '#006000',
230 -selectforeground => '#006000',
231 );
232 $w->{Style}{'site'} = $w->ItemStyle('imagetext',
233 -foreground => '#702000',
234 -selectforeground => '#702000',
235 );
236 $w->{Style}{'vendor'} = $w->ItemStyle('imagetext',
237 -foreground => '#856b48',
238 -selectforeground => '#856b48',
239 );
240 $w->{Style}{'cpan'} = $w->ItemStyle('imagetext',
241 -foreground => '#000080',
242 -selectforeground => '#000080',
243 );
244 $w->{Style}{'folder'} = $w->ItemStyle('imagetext',
245 -foreground => '#606060',
246 -selectforeground => '#606060',
247 );
248 $w->{Style}{'script'} = $w->{Style}{'site'};
249 $w->{Style}{'local dirs'} = $w->{Style}{'site'};
250  
251 my $m = $w->Menu(-tearoff => $Tk::platform ne 'MSWin32');
252 eval { $w->menu($m) }; warn $@ if $@;
253 $m->command(-label => 'Reload', -command => sub {
254 $w->toplevel->Busy(-recurse => 1);
255 eval {
256 $w->Fill(-nocache => 1);
257 };
258 my $err = $@;
259 $w->toplevel->Unbusy(-recurse => 1);
260 die $err if $err;
261 });
262 $m->command(-label => 'Search...', -command => [$w, 'search_dialog']);
263  
264 $w->Component('Label' => 'UpdateLabel',
265 -text => "Updating..."
266 );
267  
268 $w->ConfigSpecs(
269 -showcommand => ['CALLBACK', undef, undef, undef],
270 -showcommand2 => ['CALLBACK', undef, undef, undef],
271 -usecache => ['PASSIVE', undef, undef, 1],
272 );
273 }
274  
275 =head1 WIDGET METHODS
276  
277 =over 4
278  
279 =item I<$tree>-E<gt>B<Fill>(?I<-nocache =E<gt> 1>?, ?I<-forked =E<gt> 0|1>?, ?I<-fillcb =E<gt> ...>?)
280  
281 Find Pod modules and fill the tree widget. If I<-nocache> is
282 specified, then no cache will be used for loading.
283  
284 A cache of Pod modules is written unless the B<-usecache>
285 configuration option of the widget is set to false.
286  
287 If C<-forked> is specified, then searching for Pods is done in the
288 background, if possible. Note that the default is currently
289 unspecified.
290  
291 A callback may be specified with the C<-fillcb> option and will be
292 called after the tree is filled.
293  
294 =cut
295  
296 sub Fill {
297 my $w = shift;
298 my(%args) = @_;
299  
300 if ($w->{FillPid}) {
301 warn "Forked filling currently running.\n";
302 return;
303 }
304  
305 $w->delete("all");
306 delete $w->{Pods};
307 $w->{Filled} = 0;
308  
309 my $forked = delete $args{-forked};
310 if (!defined $forked) {
311 $forked = 1; # by default we try -forked
312 }
313 if ($forked) {
314 if (!eval { require Storable; 1 }) {
315 warn "Cannot fork, Storable is missing.\n";
316 $forked = 0;
317 } elsif ($^O eq 'MSWin32' || $^O eq 'cygwin') {
318 warn "Cannot fork on Windows systems.\n";
319 $forked = 0;
320 }
321 }
322  
323 if ($forked) {
324 require POSIX;
325 my($rdr,$wtr);
326 pipe($rdr,$wtr);
327 $w->{FillPid} = fork;
328 if (!defined $w->{FillPid}) {
329 warn "Cannot fork: $!";
330 # fall back to non-forked operation
331 } elsif (!$w->{FillPid}) {
332 # child
333 close $rdr;
334 my $pods = $w->_FillFind(%args);
335 my $serialized = Storable::freeze($pods);
336 print $wtr $serialized
337 or die "While writing to pipe: $!";
338 close $wtr
339 or die "While closing pipe: $!";
340 POSIX::_exit(0);
341 } else {
342 # parent
343 close $wtr;
344 $w->Subwidget('UpdateLabel')->place('-x' => 5, '-y' => 5);
345 $w->fileevent($rdr, 'readable',
346 sub {
347 local $/;
348 my $serialized = <$rdr>;
349 my $pods = Storable::thaw($serialized);
350 $w->_FillDone($pods, $args{'-fillcb'});
351 $w->fileevent($rdr, 'readable', '');
352 $w->Subwidget('UpdateLabel')->placeForget;
353 waitpid $w->{FillPid}, &POSIX::WNOHANG; # zombie reaping
354 $w->{FillPid} = undef;
355 });
356 return;
357 }
358 }
359  
360 # non-forked
361 my $pods = $w->_FillFind(%args);
362 $w->_FillDone($pods, $args{'-fillcb'});
363 }
364  
365 sub _FillFind {
366 my($w, %args) = @_;
367  
368 my $usecache = ($w->cget('-usecache') && !$args{'-nocache'});
369  
370 my $FindPods = Tk::Pod::FindPods->new;
371 my $pods = $FindPods->pod_find(-categorized => 1,
372 -usecache => $usecache,
373 );
374  
375 if (keys %EXTRAPODDIR) {
376 $ExtraFindPods = Tk::Pod::FindPods->new unless $ExtraFindPods;
377 my $extra_pods = $ExtraFindPods->pod_find
378 (-categorized => 0,
379 -category => "local dirs",
380 -directories => [keys %EXTRAPODDIR],
381 -usecache => 0,
382 );
383 while(my($k,$v) = each %$extra_pods) {
384 $pods->{$k} = $v;
385 }
386 }
387  
388 if ($w->cget('-usecache') && !$FindPods->has_cache) {
389 $FindPods->WriteCache;
390 }
391  
392 $pods;
393 }
394  
395 sub _FillDone {
396 my($w, $pods, $fillcb) = @_;
397  
398 my %category_seen;
399  
400 foreach (['perl', 'Perl language'],
401 ['pragma', 'Pragmata'],
402 ['mod', 'Modules'],
403 ['script', 'Scripts'],
404 keys(%$pods),
405 ) {
406 my($category, $title) = (ref $_ ? @$_ : ($_, $_));
407 next if $category_seen{$category};
408  
409 $w->add($category, -text => $title);
410  
411 my $hash = $pods->{$category};
412 foreach my $pod (sort keys %$hash) {
413 my $treepath = $category . SEP . $pod;
414 (my $title = $pod) =~ s|/|::|g;
415 $w->_add_parents($treepath);
416  
417 my $loc = $category =~ m{^(script|local dirs)$} ? $category : Tk::Pod::FindPods::module_location($hash->{$pod});
418 my $is = $w->{Style}{$loc};
419 my @entry_args = ($treepath,
420 -text => $title,
421 -data => _PodEntry->create($hash->{$pod}),
422 ($is ? (-style => $is) : ()),
423 );
424 if ($w->info('exists', $treepath)) {
425 $w->entryconfigure(@entry_args);
426 } else {
427 $w->add(@entry_args);
428 }
429 }
430  
431 $category_seen{$category}++;
432 }
433  
434 for(my $entry = ($w->info('children'))[0];
435 defined $entry && $entry ne "";
436 $entry = $w->info('next', $entry)) {
437 if ($w->info('children', $entry) ||
438 $w->entrycget($entry, -text) eq 'perlfunc') {
439 $w->folderentry($entry);
440 } else {
441 $w->entryconfigure($entry, -image => $w->Getimage("file"));
442 $w->hide('entry', $entry);
443 }
444 }
445  
446 $w->{Pods} = $pods;
447 $w->{Filled}++;
448  
449 if ($fillcb) {
450 $fillcb->();
451 }
452 }
453  
454 sub folderentry {
455 my($w, $entry) = @_;
456 $w->entryconfigure($entry, -image => $w->Getimage("folder"));
457 $w->setmode($entry, 'open');
458 if ($entry =~ m|/|) { # XXX SEP?
459 $w->hide('entry', $entry);
460 }
461 }
462  
463 sub Filled { shift->{Filled} }
464  
465 sub _add_parents {
466 my($w, $entry) = @_;
467 (my $parent = $entry) =~ s|/[^/]*$||; # XXX SEP?
468 return if $parent eq '';
469 do{warn "XXX Should not happen: $entry eq $parent";return} if $parent eq $entry;
470 return if $w->info('exists', $parent);
471 my @parent = split SEP, $parent;
472 my $title = join "::", @parent[1..$#parent];
473 $w->_add_parents($parent);
474 $w->add($parent, -text => $title,
475 ($w->{Style}{'folder'} ? (-style => $w->{Style}{'folder'}) : ()));
476 }
477  
478 sub _open_parents {
479 my($w, $entry) = @_;
480 (my $parent = $entry) =~ s|/[^/]+$||; # XXX SEP?
481 return if $parent eq '' || $parent eq $entry;
482 $w->_open_parents($parent);
483 $w->open($parent);
484 }
485  
486 =item I<$tree>-E<gt>B<SeePath>($path)
487  
488 Move the anchor/selection and view to the given C<$path> and open
489 subtrees to make the C<$path> visible, if necessary.
490  
491 =cut
492  
493 sub SeePath {
494 my($w,$path) = @_;
495 my $fs_case_tolerant =
496 ($^O eq 'MSWin32' ||
497 $^O eq 'darwin' || # case_tolerant=0 here!
498 (File::Spec->can("case_tolerant") && File::Spec->case_tolerant)
499 );
500 if ($^O eq 'MSWin32') {
501 $path =~ s/\\/\//g;
502 }
503 if ($fs_case_tolerant) {
504 $path = lc $path;
505 }
506 DEBUG and warn "Call SeePath with $path\n";
507 return if !$w->Filled; # not yet filled
508 my $pods = $w->{Pods};
509 return if !$pods;
510  
511 my $see_treepath = sub {
512 my $treepath = shift;
513 $w->open($treepath);
514 $w->_open_parents($treepath);
515 $w->anchorSet($treepath);
516 $w->selectionClear;
517 $w->selectionSet($treepath);
518 $w->see($treepath);
519 };
520  
521 foreach my $category (keys %$pods) {
522 foreach my $pod (keys %{ $pods->{$category} }) {
523 my $podpath = $pods->{$category}->{$pod};
524 $podpath = lc $podpath if $fs_case_tolerant;
525 if ($path eq $podpath) {
526 my $treepath = $category . SEP . $pod;
527 $see_treepath->($treepath);
528 return 1;
529 }
530 }
531 }
532 DEBUG and warn "SeePath: cannot find $path in tree\n";
533 0;
534 }
535  
536 sub GetCurrentPodPath {
537 my $w = shift;
538 my $sel_entry = ($w->selectionGet)[0];
539 if (defined $sel_entry) {
540 my @c = split m{/}, $sel_entry;
541 shift @c;
542 my $pod = join "::", @c;
543 return $pod;
544 }
545 }
546  
547 sub search_dialog {
548 my($w) = @_;
549 my $t = $w->Toplevel(-title => "Search");
550 $t->transient($w);
551 $t->Label(-text => "Search module:")->pack(-side => "left");
552 my $term;
553  
554 my $Entry = 'Entry';
555 eval {
556 require Tk::HistEntry;
557 Tk::HistEntry->VERSION(0.40);
558 $Entry = "HistEntry";
559 };
560  
561 my $e = $t->$Entry(-textvariable => \$term)->pack(-side => "left");
562 if ($e->can('history') && $search_history) {
563 $e->history($search_history);
564 }
565 $e->focus;
566 $e->bind("<Escape>" => sub { $t->destroy });
567  
568 my $do_search = sub {
569 if ($e->can('historyAdd')) {
570 $e->historyAdd($term);
571 $search_history = [ $e->history ];
572 }
573 $w->search($term);
574 };
575  
576 $e->bind("<Return>" => $do_search);
577  
578 {
579 my $f = $t->Frame->pack(-fill => "x");
580 Tk::grid($f->Button(-text => "Search",
581 -command => $do_search,
582 ),
583 $f->Button(-text => "Close",
584 -command => sub { $t->destroy },
585 ),
586 -sticky => "ew");
587 }
588 }
589  
590 sub search {
591 my($w, $rx) = @_;
592 return if $rx eq '';
593 my($entry) = ($w->info('selection'))[0];
594 if (!defined $entry) {
595 $entry = ($w->info('children'))[0];
596 return if (!defined $entry);
597 }
598 my $wrapped = 0;
599 while(1) {
600 $entry = $w->info('next', $entry);
601 if (!defined $entry) {
602 if ($wrapped) {
603 $w->bell;
604 return;
605 }
606 $wrapped++;
607 $entry = ($w->info('children'))[0];
608 }
609 my $text = $w->entrycget($entry, '-text');
610 if ($text =~ /$rx/i) {
611 my $p = $entry;
612 while(1) {
613 $p = $w->info('parent', $p);
614 if (defined $p) {
615 $w->open($p);
616 } else {
617 last;
618 }
619 }
620 $w->selectionClear;
621 $w->selectionSet($entry);
622 $w->anchorSet($entry);
623 $w->see($entry);
624 return;
625 }
626 }
627 }
628  
629 sub IndicatorCmd {
630 my($w, $ent, $event) = @_;
631 my $podentry = $w->entrycget($ent, "-data");
632 my $file = $podentry && $podentry->file;
633 my $type = $podentry && $podentry->type;
634  
635 # Dynamically create children for perlfunc entry
636 if (defined $type && $type =~ /^func_/ && !$w->info('children', $ent)) {
637 require Pod::Functions;
638  
639 my $add_func = sub {
640 my($ent, $func) = @_;
641 my $podentry = _PodEntry->new;
642 $podentry->type("func");
643 $podentry->name($func);
644 (my $safe_name = $func) =~ s{[^a-zA-Z]}{_}g;
645 $ent = $ent . SEP . $safe_name;
646 $w->add($ent, -text => $func, -data => $podentry,
647 -style => $w->{Style}{'core'});
648 };
649  
650 if ($type eq 'func_alphabetically') {
651 my $last_func;
652 my @funcs = map { if (!defined $last_func || $last_func ne $_) {
653 $last_func = $_;
654 ($_);
655 } else {
656 $last_func = $_;
657 ();
658 }
659 }
660 sort
661 map { @{ $Pod::Functions::Kinds{$_} } }
662 keys %Pod::Functions::Kinds;
663 for my $func (@funcs) {
664 $add_func->($ent, $func);
665 }
666 } else { # by category
667 for my $cat (sort keys %Pod::Functions::Kinds) {
668 (my $safe_name = $cat) =~ s{[^a-zA-Z]}{_}g;
669 my $ent = $ent . SEP . $safe_name;
670 $w->add($ent, -text => $cat, -style => $w->{Style}{'folder'});
671 my $funcs = $Pod::Functions::Kinds{$cat};
672 for my $func (@$funcs) {
673 $add_func->($ent, $func);
674 }
675 }
676 }
677 } elsif (defined $file && $file =~ /perlfunc\.pod$/ && !$w->info('children', $ent)) {
678 my($treepath, $podentry);
679  
680 $treepath = $ent . SEP. "func_alphabetically";
681 $podentry = _PodEntry->new;
682 $podentry->type("func_alphabetically");
683 $w->add($treepath, -text => "Alphabetically", -data => $podentry,
684 -style => $w->{Style}{'folder'});
685 $w->folderentry($treepath);
686  
687 $treepath = $ent . SEP. "func_by_category";
688 $podentry = _PodEntry->new;
689 $podentry->type("func_by_category");
690 $w->add($treepath, -text => "By category", -data => $podentry,
691 -style => $w->{Style}{'folder'});
692 $w->folderentry($treepath);
693 }
694 $w->SUPER::IndicatorCmd($ent, $event);
695 }
696  
697 1;
698  
699 __END__