summaryrefslogtreecommitdiff
path: root/src/graphmarkup.rs
blob: 1e6b7c1ce55ce2a2712803075d9927143dea204d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
use crate::{Result, SubplotError};

// use roadmap;

use std::env;
use std::ffi::OsString;
use std::io::prelude::*;
use std::path::PathBuf;
// use std::path::Path;
use std::process::{Command, Stdio};

/// A code block with markup for a graph.
///
/// The code block will be converted to an SVG image using an external
/// filter such as Graphviz dot or plantuml. SVG is the chosen image
/// format as it's suitable for all kinds of output formats from
/// typesetting.
///
/// This trait defines the interface for different kinds of markup
/// conversions. There's only one function that needs to be defined
/// for the trait.
pub trait GraphMarkup {
    /// Convert the markup into an SVG.
    fn as_svg(&self) -> Result<Vec<u8>>;
}

/// A code block with pikchr markup.
///
/// ~~~~
/// use subplot::{GraphMarkup, PikchrMarkup};
/// let markup = r#"line; box "Hello," "World!"; arrow"#;
/// let svg = PikchrMarkup::new(markup, None).as_svg().unwrap();
/// assert!(svg.len() > 0);
/// ~~~~
pub struct PikchrMarkup {
    markup: String,
    class: Option<String>,
}

impl PikchrMarkup {
    /// Create a new Pikchr Markup holder
    pub fn new(markup: &str, class: Option<&str>) -> PikchrMarkup {
        PikchrMarkup {
            markup: markup.to_owned(),
            class: class.map(str::to_owned),
        }
    }
}

impl GraphMarkup for PikchrMarkup {
    fn as_svg(&self) -> Result<Vec<u8>> {
        let mut flags = pikchr::PikchrFlags::default();
        flags.generate_plain_errors();
        let image = pikchr::Pikchr::render(&self.markup, self.class.as_deref(), flags)
            .map_err(SubplotError::PikchrRenderError)?;
        Ok(image.as_bytes().to_vec())
    }
}

/// A code block with Dot markup.
///
/// ~~~~
/// use subplot::{GraphMarkup, DotMarkup};
/// let markup = r#"digraph "foo" { a -> b }"#;
/// let svg = DotMarkup::new(&markup).as_svg().unwrap();
/// assert!(svg.len() > 0);
/// ~~~~
pub struct DotMarkup {
    markup: String,
}

impl DotMarkup {
    /// Create a new DotMarkup.
    pub fn new(markup: &str) -> DotMarkup {
        DotMarkup {
            markup: markup.to_owned(),
        }
    }
}

impl GraphMarkup for DotMarkup {
    fn as_svg(&self) -> Result<Vec<u8>> {
        let mut child = Command::new("dot")
            .arg("-Tsvg")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;
        if let Some(stdin) = child.stdin.as_mut() {
            stdin.write_all(self.markup.as_bytes())?;
            let output = child.wait_with_output()?;
            if output.status.success() {
                Ok(output.stdout)
            } else {
                Err(SubplotError::child_failed("dot", &output))
            }
        } else {
            Err(SubplotError::ChildNoStdin)
        }
    }
}

/// A code block with PlantUML markup.
///
/// ~~~~
/// use subplot::{GraphMarkup, PlantumlMarkup};
/// let markup = "@startuml\nAlice -> Bob\n@enduml";
/// let svg = PlantumlMarkup::new(&markup).as_svg().unwrap();
/// assert!(svg.len() > 0);
/// ~~~~
pub struct PlantumlMarkup {
    markup: String,
}

impl PlantumlMarkup {
    /// Create a new PlantumlMarkup.
    pub fn new(markup: &str) -> PlantumlMarkup {
        PlantumlMarkup {
            markup: markup.to_owned(),
        }
    }

    // If JAVA_HOME is set, and PATH is set, then:
    // Check if JAVA_HOME/bin is in PATH, if not, prepend it and return a new
    // PATH
    fn build_java_path() -> Option<OsString> {
        let java_home = env::var_os("JAVA_HOME")?;
        let cur_path = env::var_os("PATH")?;
        let cur_path: Vec<_> = env::split_paths(&cur_path).collect();
        let java_home = PathBuf::from(java_home);
        let java_bin = java_home.join("bin");
        if cur_path.iter().any(|v| v.as_os_str() == java_bin) {
            // No need to add JAVA_HOME/bin it's already on-path
            return None;
        }
        env::join_paths(Some(java_bin).iter().chain(cur_path.iter())).ok()
    }
}

impl GraphMarkup for PlantumlMarkup {
    fn as_svg(&self) -> Result<Vec<u8>> {
        let mut cmd = Command::new("java");
        cmd.arg("-Djava.awt.headless=true")
            .arg("-jar")
            .arg("/usr/share/plantuml/plantuml.jar")
            .arg("--")
            .arg("-pipe")
            .arg("-tsvg")
            .arg("-v")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        if let Some(path) = Self::build_java_path() {
            cmd.env("PATH", path);
        }
        let mut child = cmd.spawn()?;
        if let Some(stdin) = child.stdin.as_mut() {
            stdin.write_all(self.markup.as_bytes())?;
            let output = child.wait_with_output()?;
            if output.status.success() {
                Ok(output.stdout)
            } else {
                Err(SubplotError::child_failed("plantuml", &output))
            }
        } else {
            Err(SubplotError::ChildNoStdin)
        }
    }
}