pytools_rs/
show_graphviz.rs

1// Copyright (c) 2022 Kaushik Kulkarni
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21use std::io::Write;
22use std::process::Command;
23use tempfile::NamedTempFile;
24
25/// Valid visualzation modes for [`show_dot`].
26#[derive(Clone)]
27pub enum DotOutputT {
28    /// Open as a new tab in the system's default browser. Recommended for
29    /// graphs with large number of nodes.
30    Browser,
31    /// Save the graph as a SVG file on the filesystem.
32    SVG(String),
33    /// Open an Xwindow displaying the graph. Recommended for graphs with small
34    /// number of nodes.
35    XWindow,
36}
37
38pub trait ConvertibleToDotOutputT {
39    fn to_dot_output_t(self) -> DotOutputT;
40}
41
42impl ConvertibleToDotOutputT for DotOutputT {
43    fn to_dot_output_t(self) -> DotOutputT {
44        self
45    }
46}
47
48impl ConvertibleToDotOutputT for &str {
49    fn to_dot_output_t(self) -> DotOutputT {
50        match self {
51            "xwindow" => DotOutputT::XWindow,
52            "browser" => DotOutputT::Browser,
53            x if x.ends_with(".svg") => DotOutputT::SVG(x[..x.len() - 4].to_string()),
54            _ => panic!("Can be one of xwindow or browser"),
55        }
56    }
57}
58
59/// Visualize a graph written according to the [graphviz](https://www.graphviz.org/)
60/// specification.
61///
62/// # Arguments
63///
64/// * `dot_code` - the [DOT](https://graphviz.org/doc/info/lang.html) code.
65/// * `output_to` - how to visualize the graph. See [`DotOutputT`].
66pub fn show_dot<T1: ToString, T2: ConvertibleToDotOutputT>(dot_code: T1, output_to: T2) {
67    let mut fp = NamedTempFile::new().unwrap();
68    writeln!(fp, "{}", dot_code.to_string()).unwrap();
69    let (_file, fpath) = fp.keep().unwrap();
70
71    match output_to.to_dot_output_t() {
72        DotOutputT::XWindow => {
73            let output = Command::new("dot").arg("-Tx11")
74                                            .arg(fpath.to_str().unwrap())
75                                            .output()
76                                            .expect("could not run 'dot'");
77            if !output.status.success() {
78                panic!("dot exited with error: {}",
79                       String::from_utf8_lossy(&output.stderr));
80            }
81        }
82        DotOutputT::SVG(fname) => {
83            let output = Command::new("dot").arg("-Tsvg")
84                                            .arg(fpath.to_str().unwrap())
85                                            .arg("-o")
86                                            .arg(fname.as_str())
87                                            .output()
88                                            .expect("could not run 'dot'");
89            if !output.status.success() {
90                panic!("dot exited with error: {}",
91                       String::from_utf8_lossy(&output.stderr));
92            }
93        }
94        DotOutputT::Browser => unimplemented!("Browser output not yet supported"),
95    }
96}