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