summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/graphviz.pm
blob: fe3559857a211807a133d9b95be05dafac5254b7 (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 2.00;
  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 (OUT, ':utf8');
  37. print OUT $src;
  38. close OUT;
  39. my $png;
  40. {
  41. local $/ = undef;
  42. $png = <IN>;
  43. }
  44. close IN;
  45. waitpid $pid, 0;
  46. $SIG{PIPE}="DEFAULT";
  47. return "[[graph ".gettext("failed to run graphviz")."]]" if ($sigpipe);
  48. if (! $params{preview}) {
  49. writefile($dest, $config{destdir}, $png, 1);
  50. }
  51. else {
  52. # can't write the file, so embed it in a data uri
  53. eval q{use MIME::Base64};
  54. error($@) if $@;
  55. return "<img src=\"data:image/png;base64,".
  56. encode_base64($png)."\" />";
  57. }
  58. }
  59. if ($params{preview}) {
  60. return "<img src=\"".urlto($dest, "")."\" />\n";
  61. }
  62. else {
  63. return "<img src=\"".urlto($dest, $params{destpage})."\" />\n";
  64. }
  65. } #}}}
  66. sub graph (@) { #{{{
  67. my %params=@_;
  68. $params{src} = "" unless defined $params{src};
  69. $params{type} = "digraph" unless defined $params{type};
  70. $params{prog} = "dot" unless defined $params{prog};
  71. return "[[graph ".gettext("prog not a valid graphviz program")."]]" unless $graphviz_programs{$params{prog}};
  72. return render_graph(%params);
  73. } # }}}
  74. 1