summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/linkmap.pm
blob: 68eb6c8c66367c3d1c3760973a693f92623a7a19 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki::Plugin::linkmap;
  3. use warnings;
  4. use strict;
  5. use IkiWiki 3.00;
  6. use IPC::Open2;
  7. sub import {
  8. hook(type => "getsetup", id => "linkmap", call => \&getsetup);
  9. hook(type => "preprocess", id => "linkmap", call => \&preprocess);
  10. }
  11. sub getsetup () {
  12. return
  13. plugin => {
  14. safe => 1,
  15. rebuild => undef,
  16. },
  17. }
  18. my $mapnum=0;
  19. sub preprocess (@) {
  20. my %params=@_;
  21. $params{pages}="*" unless defined $params{pages};
  22. $mapnum++;
  23. my $connected=IkiWiki::yesno($params{connected});
  24. # Get all the items to map.
  25. my %mapitems = map { $_ => urlto($_, $params{destpage}) }
  26. pagespec_match_list($params{page}, $params{pages},
  27. # update when a page is added or removed, or its
  28. # links change
  29. deptype => deptype("presence", "links"));
  30. my $dest=$params{page}."/linkmap.png";
  31. # Use ikiwiki's function to create the file, this makes sure needed
  32. # subdirs are there and does some sanity checking.
  33. will_render($params{page}, $dest);
  34. writefile($dest, $config{destdir}, "");
  35. # Run dot to create the graphic and get the map data.
  36. my $pid;
  37. my $sigpipe=0;
  38. $SIG{PIPE}=sub { $sigpipe=1 };
  39. $pid=open2(*IN, *OUT, "dot -Tpng -o '$config{destdir}/$dest' -Tcmapx");
  40. # open2 doesn't respect "use open ':utf8'"
  41. binmode (IN, ':utf8');
  42. binmode (OUT, ':utf8');
  43. print OUT "digraph linkmap$mapnum {\n";
  44. print OUT "concentrate=true;\n";
  45. print OUT "charset=\"utf-8\";\n";
  46. print OUT "ratio=compress;\nsize=\"".($params{width}+0).", ".($params{height}+0)."\";\n"
  47. if defined $params{width} and defined $params{height};
  48. my %shown;
  49. my $show=sub {
  50. my $item=shift;
  51. if (! $shown{$item}) {
  52. print OUT "\"$item\" [shape=box,href=\"$mapitems{$item}\"];\n";
  53. $shown{$item}=1;
  54. }
  55. };
  56. foreach my $item (keys %mapitems) {
  57. $show->($item) unless $connected;
  58. foreach my $link (map { bestlink($item, $_) } @{$links{$item}}) {
  59. next unless length $link and $mapitems{$link};
  60. foreach my $endpoint ($item, $link) {
  61. $show->($endpoint);
  62. }
  63. print OUT "\"$item\" -> \"$link\";\n";
  64. }
  65. }
  66. print OUT "}\n";
  67. close OUT || error gettext("failed to run dot");
  68. local $/=undef;
  69. my $ret="<img src=\"".urlto($dest, $params{destpage}).
  70. "\" alt=\"".gettext("linkmap").
  71. "\" usemap=\"#linkmap$mapnum\" />\n".
  72. <IN>;
  73. close IN || error gettext("failed to run dot");
  74. waitpid $pid, 0;
  75. if ($?) {
  76. error gettext("failed to run dot");
  77. }
  78. $SIG{PIPE}="DEFAULT";
  79. error gettext("failed to run dot") if $sigpipe;
  80. return $ret;
  81. }
  82. 1