2 # graphviz plugin for ikiwiki: render graphviz source as an image.
4 package IkiWiki::Plugin::graphviz;
12 hook(type => "preprocess", id => "graphviz", call => \&graph);
15 my %graphviz_programs = (
16 "dot" => 1, "neato" => 1, "fdp" => 1, "twopi" => 1, "circo" => 1
19 sub render_graph (\%) { #{{{
20 my %params = %{(shift)};
22 my $src = "$params{type} g {\n";
23 $src .= "charset=\"utf-8\";\n";
24 $src .= "ratio=compress;\nsize=\"".($params{width}+0).", ".($params{height}+0)."\";\n"
25 if defined $params{width} and defined $params{height};
29 # Use the sha1 of the graphviz code as part of its filename.
30 eval q{use Digest::SHA1};
32 my $dest=$params{page}."/graph-".
33 IkiWiki::possibly_foolish_untaint(Digest::SHA1::sha1_hex($src)).
35 will_render($params{page}, $dest);
37 if (! -e "$config{destdir}/$dest") {
40 $SIG{PIPE}=sub { $sigpipe=1 };
41 $pid=open2(*IN, *OUT, "$params{prog} -Tpng");
43 # open2 doesn't respect "use open ':utf8'"
44 binmode (OUT, ':utf8');
58 error gettext("failed to run graphviz") if $sigpipe;
60 if (! $params{preview}) {
61 writefile($dest, $config{destdir}, $png, 1);
64 # can't write the file, so embed it in a data uri
65 eval q{use MIME::Base64};
67 return "<img src=\"data:image/png;base64,".
68 encode_base64($png)."\" />";
72 if ($params{preview}) {
73 return "<img src=\"".urlto($dest, "")."\" />\n";
76 return "<img src=\"".urlto($dest, $params{destpage})."\" />\n";
82 $params{src} = "" unless defined $params{src};
83 $params{type} = "digraph" unless defined $params{type};
84 $params{prog} = "dot" unless defined $params{prog};
85 error gettext("prog not a valid graphviz program") unless $graphviz_programs{$params{prog}};
87 return render_graph(%params);