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