2 # graphviz plugin for ikiwiki: render graphviz source as an image.
4 package IkiWiki::Plugin::graphviz;
12 hook(type => "preprocess", id => "graph", 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 (IN, ':utf8');
45 binmode (OUT, ':utf8');
59 return "[[graph ".gettext("failed to run graphviz")."]]" if ($sigpipe);
61 if (! $params{preview}) {
62 writefile($dest, $config{destdir}, $png, 1);
65 # can't write the file, so embed it in a data uri
66 eval q{use MIME::Base64};
68 return "<img src=\"data:image/png;base64,".
69 encode_base64($png)."\" />";
73 return "<img src=\"".urlto($dest, $params{page})."\" />\n";
78 $params{src} = "" unless defined $params{src};
79 $params{type} = "digraph" unless defined $params{type};
80 $params{prog} = "dot" unless defined $params{prog};
81 return "[[graph ".gettext("prog not a valid graphviz program")."]]" unless $graphviz_programs{$params{prog}};
83 return render_graph(%params);