-
Notifications
You must be signed in to change notification settings - Fork 2
/
Web.pm
2146 lines (1617 loc) · 60.3 KB
/
Web.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#======================================================================
package Pod::POM::Web; # see doc at end of file
#======================================================================
use strict;
use warnings;
use 5.010;
use parent 'Plack::Component'; # web app based on Plack architecture
use Plack::Request; # Plack API for an HTTP request
use Plack::Response; # Plack API for an HTTP response
use Plack::Util; # encode_html()
use Pod::POM 0.25; # parsing Pod
use List::Util qw/min max/; # numeric minimum & maximum
use List::MoreUtils qw/uniq firstval any/; # list utilities
use Module::CoreList; # asking if a module belongs to Perl core
use MIME::Types; # translate file extension into MIME type
use Alien::GvaScript 1.021000; # javascript files
use Config; # to find where are the perl script directories
use Encode qw/encode_utf8 decode_utf8/; # utf8 encoding
use Params::Validate qw/validate_with SCALAR ARRAYREF/; # check validity of parameters
use Path::Tiny qw/path/; # easy access to file contents
use CPAN::Common::Index::Mux::Ordered; # current CPAN version of a module
use Pod::POM::Web::Util qw/slurp_native_or_utf8 parse_version extract_POM_items/;
# other modules that may be required dynamically :
# Getopt::Long, PPI::HTML, ActiveState::Scineplex, Plack::Runner
#----------------------------------------------------------------------
# GLOBAL VARIABLES
#---------------------------------------------------------------------
our $VERSION = '1.27';
# directories for modules -- filter @INC (we don't want '.', nor server_root added by mod_perl)
my $server_root = eval {Apache2::ServerUtil::server_root()} || "";
my @default_module_dirs = grep {!/^\./ && $_ ne $server_root} @INC;
# directories for executable perl scripts
my @default_script_dirs = grep {$_}
@Config{qw/sitescriptexp vendorscriptexp scriptdirexp/};
(my $default_index_dir = __FILE__) =~ s[Web\.pm$][Web/index];
# parameters for instantiating the module. They could also come from cmd-line options
my %params_for_new = (
page_title => {type => SCALAR , default => 'Perl documentation'},
module_dirs => {type => ARRAYREF, default => \@default_module_dirs},
script_dirs => {type => ARRAYREF, default => \@default_script_dirs},
index_dir => {type => SCALAR , default => $default_index_dir},
script_name => {type => SCALAR , optional => 1}, # will be filled at first web request
);
my @params_for_getopt = (
'page_title|title=s',
'module_dirs|mdirs=s@{,}',
'script_dirs|sdirs=s@{,}',
'index_dir|idir=s',
);
# some subdirs never contain Pod documentation
my @ignore_toc_dirs = qw/auto unicore/;
# syntax coloring (optional)
my $coloring_package
= eval {require PPI::HTML} ? "PPI"
: eval {require ActiveState::Scineplex} ? "SCINEPLEX"
: "";
# A sequence of optional filters to apply to the source code before
# running it through Pod::POM. Source code is passed in $_[0] and
# should be modified in place.
my @podfilters = (
# Pod::POM fails to parse correctly when there is an initial blank line
sub { $_[0] =~ s/\A\s*// },
# Pod::POM only understands =encoding utf8, not utf-8
sub { $_[0] =~ s/=encoding utf-8/=encoding utf8/i; },
);
my %special_podfilters = (
perlfunc => # remove args in links to function names
# (for ex. L<C<open>|/open FILEHANDLE,MODE,EXPR> becomes L<C<open>|/open>
sub {$_[0] =~ s[(L<.*?\|/\w+)\s.*?>][$1>]g},
# perlre: the POM parser is not smart enough to parse
# L</C<< (?>pattern) >>>, so we translate them into L<C<< (?E<gt>pattern) >>|/(?E<gt>pattern)>
perlre => sub {$_[0] =~ s[\(\?>][(?E<gt>]g;
$_[0] =~ s[L</C<< (.*?) >>>][L<C<< $1 >>|/$1>]g},
# POSIX: the POM parser is not smart enough to parse
# L<C<function>(3)>, so we translate them into C<L<function(3)>>
POSIX => sub {$_[0] =~ s[L<C<(\w+)>\((\d)\)>][C<L<$1($2)>>]g},
);
#----------------------------------------------------------------------
# CLASS METHODS
#----------------------------------------------------------------------
# functions exported so that they can be called from command-line
sub import {
my $class = shift;
my ($package, $filename) = caller;
no strict 'refs';
# export "server" and "index" -- for "perl -MPod::POM::Web -e ..."
if ($package eq 'main' and $filename eq '-e') {
*{'main::server'} = sub { $class->server };
*{'main::index'} = sub { $class->index(@_) };
}
# export "app" --- for "plackup -MPod::POM::Web -e app"
elsif($package eq 'Plack::Runner') {
*{'Plack::Runner::app'} = sub {$class->app};
}
}
# launch the app via Plack::Runner when called from perl cmd-line
sub server {
my $class = shift;
require Plack::Runner;
my $runner = Plack::Runner->new;
$runner->parse_options(@ARGV);
$runner->run($class->app);
}
# return an app suitable to run under Plack::Runner
sub app {
my $class = shift;
# get options from command-line
require Getopt::Long;
my $parser = Getopt::Long::Parser->new(config => [qw/pass_through/]);
$parser->getoptions(\my %options, @params_for_getopt);
# create a Pod::POM::Web instance and make it into a Plack app
my $obj = $class->new(%options);
return $obj->to_app;
}
# backcompat : a class method to be used as a CGI script or as a modperl handler
sub handler : method {
my ($class, $r) = @_;
if ($r && ref $r =~ /^Apache/) {
require Plack::Handler::Apache2;
Plack::Handler::Apache2->call_app($r, $class->app);
}
else {
require Plack::Handler::CGI;
Plack::Handler::CGI->new->run($class->app);
}
}
# façade to the Indexer class -- for facilitating command-line invocation
sub index {
my ($class, %options) = @_;
my $self = $class->new();
$self->indexer(%options)->start_indexing_session;
}
# constructor
sub new {
my $class = shift;
# validate input parameters
my $self = validate_with(
params => \@_,
spec => \%params_for_new,
allow_extra => 0,
);
# sources for CPAN index. The default requires an internet connexion. If there is a
# local MiniCPAN mirror, it will be detected and used as an alternate source.
my @cpan_indices = (MetaDB => {});
if (my $local_minicpan = eval {require CPAN::Mini;
my %conf = CPAN::Mini->read_config;
$conf{local}}) {
unshift @cpan_indices,
LocalPackage => { source => "$local_minicpan/modules/02packages.details.txt.gz" };
}
$self->{cpan_index} = CPAN::Common::Index::Mux::Ordered->assemble(@cpan_indices);
# create instance
bless $self, $class;
}
#----------------------------------------------------------------------
# INSTANCE METHODS
#----------------------------------------------------------------------
# simple-minded accessors
sub module_dirs {@{shift->{module_dirs}}}
sub script_dirs {@{shift->{script_dirs}}}
# lazy instantiation of the indexer class
sub indexer {
my ($self, %options) = @_;
# NOTE : the indexer cannot be cached, because this would lock the .BDB files, preventing updates
require Pod::POM::Web::Indexer;
my $indexer = Pod::POM::Web::Indexer->new(index_dir => $self->{index_dir},
module_dirs => $self->{module_dirs},
%options);
return $indexer;
}
# main request dispatcher (see L<Plack::Component>)
sub call {
my ($self, $env) = @_;
# plack request object
my $req = Plack::Request->new($env);
# at first request, register the script name
$self->{script_name} = $req->script_name if not exists $self->{script_name};
# dispatching will be based on path_info
my $path_info = $req->path_info;
# security check : no outside directories
$path_info =~ m[(\.\.|//|\\|:)] and die "illegal path: $path_info";
# dispatch
$path_info =~ s[^/][] or return $self->index_frameset($req);
for ($path_info) {
/^$/ and return $self->index_frameset($req);
/^index$/ and return $self->index_frameset($req);
/^toc$/ and return $self->main_toc($req);
/^toc\/(.*)$/ and return $self->toc_for($1); # Ajax calls
/^script\/(.*)$/ and return $self->serve_script($1);
/^search$/ and return $self->dispatch_search($req);
/^source\/(.*)$/ and return $self->serve_source($1, $req);
/^ft_index$/ and return $self->ft_index($req);
# files with extensions (.css, .js, images)
/\.(\w+)$/ and return $self->serve_file($path_info, $1);
# otherwise, it must be a module
return $self->serve_module($path_info);
}
}
#----------------------------------------------------------------------
# main frameset
#----------------------------------------------------------------------
sub index_frameset{
my ($self, $req) = @_;
# initial page to open
my $ini = $req->parameters->{open};
my $ini_content = $ini || "perl";
my $ini_toc = $ini ? "toc?open=$ini" : "toc";
# HTML title
my $title = Plack::Util::encode_html($self->{page_title});
return $self->respond_html(<<__EOHTML__);
<html>
<head><title>$title</title></head>
<frameset cols="25%, 75%">
<frame name="tocFrame" src="$self->{script_name}/$ini_toc">
<frame name="contentFrame" src="$self->{script_name}/$ini_content">
</frameset>
</html>
__EOHTML__
}
#----------------------------------------------------------------------
# serving a single file (source code, raw content or POD documentation)
#----------------------------------------------------------------------
sub serve_source {
my ($self, $path, $req) = @_;
my $params = $req->parameters;
# default (if not printing): line numbers and syntax coloring are on
$params->{lines} = $params->{coloring} = 1 unless $params->{print};
# find the source file(s)
my @files = $path =~ s[^script/][] ? $self->find_script($path)
: $self->find_module($path)
or die "did not find source for '$path'";
# last modification
my $mtime = max map{(stat $_)[9]} @files;
# build formatted source
my $view = $self->mk_view(
line_numbering => $params->{lines},
syntax_coloring => ($params->{coloring} ? $coloring_package : "")
);
my $formatted_sources = "";
foreach my $file (@files) {
my $source = slurp_native_or_utf8($file);
$source =~ s/\r\n/\n/g;
my $formatted_source = $view->view_verbatim($source);
$formatted_sources .= "<p/><h2>$file</h2><p/><pre>$formatted_source</pre>";
}
my $offer_print = $params->{print} ? "" : <<__EOHTML__;
<form method="get" target="_blank">
<input type="submit" name="print" value="Print"> with<br>
<input type="checkbox" name="lines" checked>line numbers<br>
<input type="checkbox" name="coloring" checked>syntax coloring
</form>
__EOHTML__
my $script = $params->{print} ? <<__EOHTML__ : "";
<script>
window.onload = function () {window.print()};
</script>
__EOHTML__
my $doc_link = $params->{print} ? "" : <<__EOHTML__;
<a href="$self->{script_name}/$path" style="float:right">Doc</a>
__EOHTML__
my $css_links = $self->css_links;
(my $module = $path) =~ s[/][::]g;
my $html = <<__EOHTML__;
<html>
<head>
<title>Source of $module</title>
$css_links
<style>
PRE {border: none; background: none}
FORM {float: right; font-size: 70%; border: 1px solid}
</style>
</head>
<body>
$doc_link
<h1>Source of $module</h1>
$offer_print
$formatted_sources
</body>
</html>
__EOHTML__
$self->respond_html($html, $mtime);
}
sub serve_file {
my ($self, $path, $extension) = @_;
my ($fullpath) = $self->find_files(module_dirs => $path)
or return $self->respond(code => 404,
content => "$path: no such file");
my $mime_type = MIME::Types->new->mimeTypeOf($extension);
my $content = path($fullpath)->slurp_raw;
my $mtime = (stat $fullpath)[9];
$self->respond(content => $content,
mtime => $mtime,
mime_type => $mime_type);
}
sub serve_module {
my ($self, $path) = @_;
$path =~ s[::][/]g; # just in case, if called as /perldoc/Foo::Bar
# find file(s) corresponding to $path
my @sources = $self->find_module($path)
or return $self->_no_such_module($path);
my $mtime = max map {(stat $_)[9]} @sources;
# module version
my $version = firstval {$_} map {parse_version($_)} grep {/\.pm$/} @sources;
# latest CPAN version -- needs hack because CPAN::Common::Index reports 'undef' instead of undef
(my $mod_name = $path) =~ s[/][::]g;
my $cpan_package = $self->{cpan_index}->search_packages( { package => $mod_name } );
my $cpan_version = $cpan_package ? $cpan_package->{version} : undef;
undef $cpan_version if $cpan_version && $cpan_version eq 'undef';
# special pre-processing for some specific paths
my @special_podfilters = ($special_podfilters{$path} // ());
# POD content, preferably from the 1st file in list, otherwise from the 2nd
my $pom = $self->extract_POM($sources[0], @special_podfilters);
my @content = $pom->content;
$pom = $self->extract_POM($sources[1], @special_podfilters)
if @sources > 1 and !@content;
# generate HTML through the view class
my $view = $self->mk_view(version => $version,
mtime => $mtime,
path => $path,
mod_name => $mod_name,
cpan_version => $cpan_version,
syntax_coloring => $coloring_package);
my $html = $view->print($pom);
# special handling for perlfunc : ids should be just function names
$html =~ s/li id="(.*?)_.*?"/li id="$1"/g
if $path =~ /\bperlfunc$/;
# special handling for 'perl' : hyperlinks to man pages
if ($path =~ /\bperl$/) {
my $sub = sub {my $txt = shift;
$txt =~ s[(perl\w+)]
[<a href="$self->{script_name}/$1">$1</a>]g;
return $txt};
$html =~ s[(<pre.*?</pre>)][$sub->($1)]egs;
}
return $self->respond_html($html, $mtime);
}
sub serve_script {
my ($self, $path) = @_;
# find file(s) corresponding to $path
my ($fullpath) = $self->find_script($path)
or die "no such script : $path";
# last modification time
my $mtime = (stat $fullpath)[9];
# call view to generate HTML
my $pom = $self->extract_POM($fullpath);
my $view = $self->mk_view(path => "script/$path",
mtime => $mtime,
syntax_coloring => $coloring_package);
my $html = $view->print($pom);
# return HTML
return $self->respond_html($html, $mtime);
}
sub extract_POM {
my ($self, $sourcefile, @more_podfilters) = @_;
my $pod = slurp_native_or_utf8($sourcefile);
$_->($pod) foreach @podfilters, @more_podfilters;
my $parser = Pod::POM->new;
my $pom = $parser->parse_text($pod) or die $parser->error;
return $pom;
}
sub _no_such_module {
my ($self, $module) = @_;
$module =~ s!/!::!g;
$module = Plack::Util::encode_html($module);
my $html = <<__EOHTML__;
<html>
<head>
<title>$module not found</title>
</head>
<body>
<h1>$module not found</h1>
<p>
The module <code>$module</code> could not be found on this server.
It may not be installed locally. Please try
<a href='https://metacpan.org/pod/$module' target='_blank'>$module on Metacpan</a>.
</p>
</body>
</html>
__EOHTML__
$self->respond_html($html);
}
#----------------------------------------------------------------------
# tables of contents
#----------------------------------------------------------------------
sub toc_for { # partial toc (called through Ajax)
my ($self, $prefix) = @_;
# special handling for builtin paths
for ($prefix) {
/^perldocs$/ and return $self->toc_perldocs;
/^pragmas$/ and return $self->toc_pragmas;
/^scripts$/ and return $self->toc_scripts;
}
# otherwise, find and htmlize entries under a given prefix
my $entries = $self->find_entries_for($prefix);
if ($prefix eq 'Pod') {
# in old versions of perl, basic docs are under Pod/perl*.pod. They should not be listed in the toc.
delete $entries->{$_} for grep /^perl/, keys %$entries;
}
return $self->respond_html($self->htmlize_entries($entries));
}
sub toc_perldocs {
my ($self) = @_;
my %perldocs;
# Perl basic docs are found under "pod" or "pods", depending on the installations.
# "perllocal.pod" is in the root dir.
for my $subdir (qw/pod pods/, "") {
my $entries = $self->find_entries_for($subdir);
# just keep the perl* entries, without subdir prefix
foreach my $key (grep /^perl/, keys %$entries) {
$perldocs{$key} = $entries->{$key};
$perldocs{$key}{node} =~ s[^$subdir/][]i;
}
}
return $self->respond_html($self->htmlize_perldocs(\%perldocs));
}
sub toc_pragmas {
my ($self) = @_;
my $entries = $self->find_entries_for(""); # files found at root level
delete $entries->{$_} for @ignore_toc_dirs, qw/pod pods inc/;
delete $entries->{$_} for grep {/^perl/ or !/^[[:lower:]]/} keys %$entries;
return $self->respond_html($self->htmlize_entries($entries));
}
sub toc_scripts {
my ($self) = @_;
my %scripts;
# gather all scripts and group them by initial letter
foreach my $dir ($self->script_dirs) {
opendir my $dh, $dir or next;
NAME:
foreach my $name (readdir $dh) {
for ("$dir/$name") {
-x && !-d && -T or next NAME ; # try to just keep Perl executables
}
$name =~ s/\.(pl|bat)$//i;
my $letter = uc substr $name, 0, 1;
$scripts{$letter}{$name} = {node => "script/$name", pod => 1};
}
}
# htmlize the structure
my $html = "";
foreach my $letter (sort keys %scripts) {
my $content = $self->htmlize_entries($scripts{$letter});
$html .= closed_node(label => $letter,
content => $content);
}
return $self->respond_html($html);
}
sub find_entries_for {
my ($self, $prefix) = @_;
# if $prefix is of shape A*, we want top-level modules starting
# with that letter
my $filter;
if ($prefix =~ /^([A-Z])\*/) {
$filter = qr/^$1/;
$prefix = "";
}
my %entries;
foreach my $root_dir ($self->module_dirs) {
my $dirname = $prefix ? "$root_dir/$prefix" : $root_dir;
opendir my $dh, $dirname or next;
foreach my $name (readdir $dh) {
next if $name =~ /^\./;
next if $filter and $name !~ $filter;
my $is_dir = -d "$dirname/$name";
my $has_pod = $name =~ s/\.(pm|pod)$//;
# skip if this subdir is a member of @INC (not a real module namespace)
next if $is_dir and grep {m[^\Q$dirname/$name\E]} $self->module_dirs;
if ($is_dir || $has_pod) { # found a TOC entry
$entries{$name}{node} = $prefix ? "$prefix/$name" : $name;
$entries{$name}{dir} = 1 if $is_dir;
$entries{$name}{pod} = 1 if $has_pod;
}
}
}
return \%entries;
}
sub htmlize_perldocs {
my ($self, $perldocs) = @_;
my $parser = Pod::POM->new;
# Pod/perl.pom Synopsis contains a classification of perl*.pod documents
my ($perl_path) = $self->find_module("perl")
or die "'perl.pod' does not seem to be installed on this system";
my $perlpom = $self->extract_POM($perl_path);
my $h1 = (firstval {$_->title eq 'GETTING HELP'} $perlpom->head1)
|| (firstval {$_->title eq 'SYNOPSIS'} $perlpom->head1);
my $html = "";
# classified pages mentioned in the synopsis
foreach my $h2 ($h1->head2) {
my $title = $h2->title;
my $content = $h2->verbatim;
# "Internals and C-Language Interface" is too long
$title =~ s/^Internals.*/Internals/;
# gather leaf entries
my @leaves;
while ($content =~ /^\s*(perl\S*)(?:\h+(\w.+))?/gm) {
my ($ref, $descr) = ($1, $2);
my $attrs = qq{id='$ref'};
$attrs .= qq{ title='$descr'} if $descr;
my $entry = delete $perldocs->{$ref} or next;
push @leaves, {label => $ref,
href => $entry->{node},
attrs => $attrs};
}
# sort and transform into HTML
@leaves = map {leaf(%$_)}
sort {$a->{label} cmp $b->{label}} @leaves;
$html .= closed_node(label => $title,
content => join("\n", @leaves));
}
# maybe some remaining pages
if (keys %$perldocs) {
$html .= closed_node(label => 'Unclassified',
content => $self->htmlize_entries($perldocs));
}
return $html;
}
sub htmlize_entries {
my ($self, $entries) = @_;
my $html = "";
my $has_index = $self->indexer->has_index;
foreach my $name (sort {uc($a) cmp uc($b)} keys %$entries) {
my $entry = $entries->{$name};
(my $id = $entry->{node}) =~ s[/][::]g;
my %args = (class => 'TN_leaf',
label => $name,
attrs => qq{id='$id'});
if ($entry->{dir}) {
$args{class} = 'TN_node TN_closed';
$args{attrs} .= qq{ TN:contentURL='toc/$entry->{node}'};
}
if ($entry->{pod}) {
$args{href} = $entry->{node};
$args{module_descr} = $self->indexer->get_module_description($entry->{node})
if $has_index;
}
$html .= generic_node(%args);
}
return $html;
}
sub main_toc {
my ($self, $req) = @_;
# initial page to open
my $ini = $req->parameters->{open};
my $select_ini = $ini ? "selectToc('$ini');" : "";
# perlfunc entries in JSON format for the DHTML autocompleter
my @funcs = map {$_->title} grep {$_->content =~ /\S/} $self->perlfunc_items;
s|[/\s(].*||s foreach @funcs;
my $json_funcs = "[" . join(",", map {qq{"$_"}} uniq @funcs) . "]";
# perlvar entries in JSON format for the DHTML autocompleter
my @vars = map {$_->title} grep {!/->/} map {@$_} $self->perlvar_items;
s|\s*X<.*||s foreach @vars;
s|\\|\\\\|g foreach @vars;
s|"|\\"|g foreach @vars;
my $json_vars = "[" . join(",", map {qq{"$_"}} uniq @vars) . "]";
# initial sections : perldocs, pragmas and scripts
my @perl_sections = map {closed_node(
label => ucfirst($_),
label_class => "TN_label small_title",
attrs => qq{TN:contentURL='toc/$_' id='$_'},
)} qw/perldocs pragmas scripts/;
# following sections : alphabetical list of modules (details will be loaded dynamically)
my $alpha_list = "";
for my $letter ('A' .. 'Z') {
$alpha_list .= closed_node (
label => $letter,
label_class => "TN_label",
attrs => qq{TN:contentURL='toc/$letter*' id='${letter}:'},
);
}
my $modules = generic_node (label => "Modules",
label_class => "TN_label small_title",
content => $alpha_list);
# build the HTML response
my $css_links = $self->css_links;
my $js_scripts = $self->js_scripts;
return $self->respond_html(<<__EOHTML__);
<html>
<head>
<base target="contentFrame">
$css_links
$js_scripts
<script>
var treeNavigator;
var perlfuncs = $json_funcs;
var perlvars = $json_vars;
var completers = {};
function submit_on_event(event) {
\$('search_form').submit();
}
function resize_tree_navigator() {
// compute available height -- comes either from body or documentElement,
// depending on browser and on compatibility mode !!
var doc_el_height = document.documentElement.clientHeight;
var avail_height
= (Prototype.Browser.IE && doc_el_height) ? doc_el_height
: document.body.clientHeight;
var tree_height = avail_height - \$('toc_frame_top').scrollHeight - 5;
if (tree_height > 100)
\$('TN_tree').style.height = tree_height + "px";
}
function open_nodes(first_node, rest) {
var node = \$(first_node);
if (!node || !treeNavigator) return;
// shift to next node in sequence
first_node = rest.shift();
// build a handler for "onAfterLoadContent" (closure on first_node/rest)
var open_or_select_next = function() {
// delete handler that might have been placed by previous call
delete treeNavigator.onAfterLoadContent;
//
if (rest.length > 0) {
open_nodes(first_node, rest)
}
else {
treeNavigator.openEnclosingNodes(\$(first_node));
treeNavigator.select(\$(first_node));
}
};
// if node is closed and currently has no content, we need to register
// a handler, open the node so that it gets its content by Ajax,
// and then execute the handler to open the rest after Ajax returns
if (treeNavigator.isClosed(node)
&& !treeNavigator.content(node)) {
treeNavigator.onAfterLoadContent = open_or_select_next;
treeNavigator.open(node);
}
// otherwise just a direct call
else {
open_or_select_next();
}
}
function selectToc(entry) {
// build array of intermediate nodes (i.e "Foo", "Foo::Bar", etc.)
var parts = entry.split(new RegExp("/|::"));
var accu = '';
var sequence = parts.map(function(e) {
accu = accu ? (accu + "::" + e) : e;
return accu;
});
// choose id of first_node by analysis of entry
var initial = entry.substr(0, 1);
var first_node
// CASE module (starting with uppercase)
= (initial <= 'Z') ? (initial + ":")
// CASE perl* documentation page
: entry.search(/^perl/) > -1 ? "perldocs"
// CASE other lowercase entries
: "pragmas"
;
// open each node in sequence
open_nodes(first_node, sequence);
}
function setup() {
treeNavigator
= new GvaScript.TreeNavigator('TN_tree', {tabIndex:-1});
completers.perlfunc = new GvaScript.AutoCompleter(
perlfuncs,
{minimumChars: 1,
minWidth: 100,
offsetX: -20,
autoSuggestDelay: 400});
completers.perlfunc.onComplete = submit_on_event;
completers.perlvar = new GvaScript.AutoCompleter(
perlvars,
{minimumChars: 1,
minWidth: 100,
offsetX: -20,
autoSuggestDelay: 400});
completers.perlvar.onComplete = submit_on_event;
completers.modlist = new GvaScript.AutoCompleter(
"search?source=modlist&search=",
{minimumChars: 2, minWidth: 100, offsetX: -20, typeAhead: false});
completers.modlist.onComplete = submit_on_event;
resize_tree_navigator();
$select_ini
}
document.observe('dom:loaded', setup);
window.onresize = resize_tree_navigator;
// Note: observe('resize') doesn't work. Why ?
function displayContent(event) {
var label = event.controller.label(event.target);
if (label && label.tagName == "A") {
label.focus();
return Event. stopNone;
}
}
function maybe_complete(input) {
if (input._autocompleter)
input._autocompleter.detach(input);
switch (input.form.source.selectedIndex) {
case 0: completers.perlfunc.autocomplete(input); break;
case 1: completers.perlvar.autocomplete(input); break;
case 3: if (!no_indexer)
completers.modlist.autocomplete(input);
break;
}
}
</script>
<style>
.small_title {color: midnightblue; font-weight: bold; padding: 0 3 0 3}
FORM {margin:0px}
BODY {margin:0px; font-size: 70%; overflow-x: hidden}
DIV {margin:0px; width: 100%}
#TN_tree {overflow-y:scroll; overflow-x: hidden}
</style>
</head>
<body>
<div id='toc_frame_top'>
<div class="small_title"
style="text-align:center;border-bottom: 1px solid">
$self->{page_title}
</div>
<div style="text-align:right">
<a href="$self->{script_name}/Pod/POM/Web/Help" class="small_title">Help</a>
</div>
<form action="search" id="search_form" method="get" accept-charset="UTF-8">
<span class="small_title">Search in</span>
<select name="source">
<option>perlfunc</option>
<option>perlvar</option>
<option>perlfaq</option>
<option>modules</option>
<option>full-text</option>
</select><br>
<span class="small_title"> for </span><input
name="search" size="15"
autocomplete="off"
onfocus="maybe_complete(this)">
</form>
<br>
<div class="small_title"
style="border-bottom: 1px solid">Browse</div>
</div>
<!-- In principle the tree navigator below would best belong in a
different frame, but instead it's in a div because the autocompleter
from the form above sometimes needs to overlap the tree nav. -->
<div id='TN_tree' onPing='displayContent'>
@perl_sections
$modules
</div>
</body>
</html>
__EOHTML__
}
#----------------------------------------------------------------------
# searching
#----------------------------------------------------------------------
sub dispatch_search {
my ($self, $req) = @_;
my $params = $req->parameters;
my $search_string = decode_utf8($params->{search});
for ($params->{source}) {
/^perlfunc$/ and return $self->search_perlfunc($search_string);
/^perlvar$/ and return $self->search_perlvar($search_string);
/^perlfaq$/ and return $self->search_perlfaq($search_string);
/^modules$/ and return $self->serve_module($search_string);
/^full-text$/ and return $self->search_fulltext($search_string, $params);
/^modlist$/ and return $self->modules_matching_prefix($search_string);
# otherwise
die "cannot search in '$_'";
}
}
sub perlfunc_items {
my ($self) = @_;
# gather POM description of all functions in perlfunc -- lazy loading at first call
if (!$self->{perlfunc_items}) {
my ($func_path) = $self->find_module("perlfunc")
or die "'perlfunc.pod' does not seem to be installed on this system";
my $funcpom = $self->extract_POM($func_path, $special_podfilters{perlfunc});
my ($description) = grep {$_->title eq 'DESCRIPTION'} $funcpom->head1;
my ($alphalist)
= grep {$_->title =~ /^Alphabetical Listing/i} $description->head2;
my @items = $alphalist->over->[0]->item;
$self->{perlfunc_items} = \@items;
}
return @{$self->{perlfunc_items}};
}
sub search_perlfunc {
my ($self, $func) = @_;
# find items matching the $func request
my @matching_items = grep {$_->title =~ /^$func\b/} $self->perlfunc_items
or return $self->respond_html("No documentation found for perl "
."function '<tt>$func</tt>'");