summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/graphviz.pm
blob: 48f520c4f92f9fc7279852d017310d20ed061a25 (plain)
  1. #!/usr/bin/perl
  2. # graphviz plugin for ikiwiki: render graphviz source as an image.
  3. # Josh Triplett
  4. package IkiWiki::Plugin::graphviz;
  5. use warnings;
  6. use strict;
  7. use IkiWiki;
  8. use IPC::Open2;
  9. sub import { #{{{
  10. hook(type => "preprocess", id => "graph", call => \&graph);
  11. } # }}}
  12. my %graphviz_programs = (
  13. "dot" => 1, "neato" => 1, "fdp" => 1, "twopi" => 1, "circo" => 1
  14. );
  15. sub render_graph (\%) { #{{{
  16. my %params = %{(shift)};
  17. my $src = "$params{type} g {\n";
  18. $src .= "charset=\"utf-8\";\n";
  19. $src .= "ratio=compress;\nsize=\"".($params{width}+0).", ".($params{height}+0)."\";\n"
  20. if defined $params{width} and defined $params{height};
  21. $src .= $params{src};
  22. $src .= "}\n";
  23. # Use the sha1 of the graphviz code as part of its filename.
  24. eval q{use Digest::SHA1};
  25. error($@) if $@;
  26. my $dest=$params{page}."/graph-".
  27. IkiWiki::possibly_foolish_untaint(Digest::SHA1::sha1_hex($src)).
  28. ".png";
  29. will_render($params{page}, $dest);
  30. if (! -e "$config{destdir}/$dest") {
  31. my $pid;
  32. my $sigpipe=0;;
  33. $SIG{PIPE}=sub { $sigpipe=1 };
  34. $pid=open2(*IN, *OUT, "$params{prog} -Tpng");
  35. # open2 doesn't respect "use open ':utf8'"
  36. binmode (IN, ':utf8');
  37. binmode (OUT, ':utf8');
  38. print OUT $src;
  39. close OUT;
  40. my $png;
  41. {
  42. local $/ = undef;
  43. $png = <IN>;
  44. }
  45. close IN;
  46. waitpid $pid, 0;
  47. $SIG{PIPE}="DEFAULT";
  48. return "[[graph ".gettext("failed to run graphviz")."]]" if ($sigpipe);
  49. if (! $params{preview}) {
  50. writefile($dest, $config{destdir}, $png, 1);
  51. }
  52. else {
  53. # can't write the file, so embed it in a data uri
  54. eval q{use MIME::Base64};
  55. error($@) if $@;
  56. return "<img src=\"data:image/png;base64,".
  57. encode_base64($png)."\" />";
  58. }
  59. }
  60. return "<img src=\"".urlto($dest, $params{page})."\" />\n";
  61. } #}}}
  62. sub graph (@) { #{{{
  63. my %params=@_;
  64. $params{src} = "" unless defined $params{src};
  65. $params{type} = "digraph" unless defined $params{type};
  66. $params{prog} = "dot" unless defined $params{prog};
  67. return "[[graph ".gettext("prog not a valid graphviz program")."]]" unless $graphviz_programs{$params{prog}};
  68. return render_graph(%params);
  69. } # }}}
  70. 1