2 # graphviz plugin for ikiwiki: render graphviz source as an image.
4 package IkiWiki::Plugin::graphviz;
12 hook(type => "getsetup", id => "graphviz", call => \&getsetup);
13 hook(type => "preprocess", id => "graph", call => \&graph);
25 my %graphviz_programs = (
26 "dot" => 1, "neato" => 1, "fdp" => 1, "twopi" => 1, "circo" => 1
29 sub render_graph (\%) {
30 my %params = %{(shift)};
32 my $src = "$params{type} g {\n";
33 $src .= "charset=\"utf-8\";\n";
34 $src .= "ratio=compress;\nsize=\"".($params{width}+0).", ".($params{height}+0)."\";\n"
35 if defined $params{width} and defined $params{height};
39 # Use the sha1 of the graphviz code as part of its filename.
40 eval q{use Digest::SHA1};
42 my $dest=$params{page}."/graph-".
43 IkiWiki::possibly_foolish_untaint(Digest::SHA1::sha1_hex($src)).
45 will_render($params{page}, $dest);
47 if (! -e "$config{destdir}/$dest") {
50 $SIG{PIPE}=sub { $sigpipe=1 };
51 $pid=open2(*IN, *OUT, "$params{prog} -Tpng");
53 # open2 doesn't respect "use open ':utf8'"
54 binmode (OUT, ':utf8');
68 error gettext("failed to run graphviz") if $sigpipe;
70 if (! $params{preview}) {
71 writefile($dest, $config{destdir}, $png, 1);
74 # can't write the file, so embed it in a data uri
75 eval q{use MIME::Base64};
77 return "<img src=\"data:image/png;base64,".
78 encode_base64($png)."\" />";
82 return "<img src=\"".urlto($dest, $params{destpage})."\" />\n";
87 $params{src} = "" unless defined $params{src};
88 $params{type} = "digraph" unless defined $params{type};
89 $params{prog} = "dot" unless defined $params{prog};
90 error gettext("prog not a valid graphviz program") unless $graphviz_programs{$params{prog}};
92 return render_graph(%params);