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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
//! LaTeX-rendering
//!
//! A thin wrapper around external tools like `latexmk`. See `TexRender` for details.
//!
//! Also supports generation of LaTeX documents, see the `tpl` module.

pub mod tex_escape;
pub mod tpl;

use std::{
    ffi::{OsStr, OsString},
    fs, io, path, process,
};
use thiserror::Error;

/// LaTeX-rendering command.
///
/// Creating a new rendering command usually starts by supplying a LaTeX-document, either via
/// `from_bytes` or `from_file`. Other options can be set through the various builder methods.
///
/// Once satisfied, the `render` method will perform the call to the external TeX-engine and return
/// a rendered PDF as raw bytes.
///
/// # TEXINPUTS
///
/// The search path for classes, includes or other files used in TeX can be extended using the
/// `TEXINPUTS` environment variable; `TexRender` sets this variable when rendering. See
/// `add_texinput` for details.
///
/// # Assets
///
/// Instead of adding a folder to `TEXINPUTS`, any sort of external file can be added as an asset.
/// Assets are stored in a temporary folder that lives as long as the `TexRender` instance, the
/// folder will automatically be added to `TEXINPUTS` when rendering. See the `add_asset_*`
/// functions for details.
#[derive(Debug)]
pub struct TexRender {
    /// Content to render.
    source: Vec<u8>,
    /// A number of folders to add to `TEXINPUTS`.
    texinputs: Vec<path::PathBuf>,
    /// Path to latexmk.
    latex_mk_path: path::PathBuf,
    /// Whether or not to use XeLaTeX.
    use_xelatex: bool,
    /// Whether or not to allow shell escaping.
    allow_shell_escape: bool,
    /// Temporary directory holding assets to be included.
    assets_dir: Option<tempdir::TempDir>,
}

/// Error occuring during rendering.
#[derive(Debug, Error)]
pub enum RenderingError {
    /// Temporary directry could not be created.
    #[error("could not create temporary directory: {0}")]
    TempdirCreation(io::Error),
    /// Writing the input file failed.
    #[error("could not write input file: {0}")]
    WriteInputFile(io::Error),
    /// Reading the resulting output file failed.
    #[error("could not read output file: {0}")]
    ReadOutputFile(io::Error),
    /// Could not run LaTeX rendering command.
    #[error("could not run latexmk: {0}")]
    RunError(io::Error),
    /// latexmk failed.
    #[error("LaTeX failure: {stdout:?} {stderr:?}")]
    LatexError {
        /// Process exit code.
        status: Option<i32>,
        /// Content of stdout.
        stdout: Vec<u8>,
        /// Content of stderr.
        stderr: Vec<u8>,
    },
}

impl TexRender {
    /// Create a new tex render configuration using raw input bytes as the source file.
    pub fn from_bytes(source: Vec<u8>) -> TexRender {
        TexRender {
            source,
            texinputs: Vec::new(),
            latex_mk_path: "latexmk".into(),
            use_xelatex: true,
            allow_shell_escape: false,
            assets_dir: None,
        }
    }

    /// Create a new tex render configuration from an input latex file.
    pub fn from_file<P: AsRef<path::Path>>(source: P) -> io::Result<TexRender> {
        Ok(Self::from_bytes(fs::read(source)?))
    }

    /// Adds an asset to the texrender.
    pub fn add_asset_from_bytes<S: AsRef<OsStr>>(
        &mut self,
        filename: S,
        bytes: &[u8],
    ) -> io::Result<()> {
        // Initialize assets dir, if not present.
        let assets_path = match self.assets_dir {
            Some(ref assets_dir) => assets_dir.path(),
            None => {
                let assets_dir = tempdir::TempDir::new("texrender-assets")?;
                self.texinputs.push(assets_dir.path().to_owned());
                self.assets_dir = Some(assets_dir);
                &self.texinputs[self.texinputs.len() - 1]
            }
        };

        let output_fn = assets_path.join(filename.as_ref());
        fs::create_dir_all(output_fn.parent().expect("filename has no parent?"))?;

        fs::write(output_fn, bytes)
    }

    /// Adds an assets to the texrender from a file.
    ///
    /// # Panics
    ///
    /// Panics if the passed-in path has no proper filename.
    pub fn add_asset_from_file<P: AsRef<path::Path>>(&mut self, path: P) -> io::Result<()> {
        let source = path.as_ref();
        let filename = source.file_name().expect("file has no filename");

        let buf = fs::read(source)?;
        self.add_asset_from_bytes(filename, &buf)
    }

    /// Adds a path to list of texinputs.
    pub fn add_texinput<P: Into<path::PathBuf>>(&mut self, input_path: P) -> &mut Self {
        self.texinputs.push(input_path.into());
        self
    }

    /// Sets the path of `latexmk`.
    ///
    /// If not set, will look for `latexmk` on the current `PATH`.
    pub fn latex_mk_path<P: Into<path::PathBuf>>(&mut self, latex_mk_path: P) -> &mut Self {
        self.latex_mk_path = latex_mk_path.into();
        self
    }

    /// Renders the given source as PDF.
    pub fn render(&self) -> Result<Vec<u8>, RenderingError> {
        let tmp = tempdir::TempDir::new("texrender").map_err(RenderingError::TempdirCreation)?;
        let input_file = tmp.path().join("input.tex");
        let output_file = tmp.path().join("input.pdf");

        let mut texinputs = OsString::new();
        for input in &self.texinputs {
            texinputs.push(":");
            texinputs.push(input.as_os_str());
        }

        fs::write(&input_file, &self.source).map_err(RenderingError::WriteInputFile)?;

        let mut cmd = process::Command::new(&self.latex_mk_path);
        cmd.args(&[
            "-interaction=nonstopmode",
            "-halt-on-error",
            "-file-line-error",
            "-pdf",
        ]);

        if self.use_xelatex {
            cmd.arg("-xelatex");
        }

        if !self.allow_shell_escape {
            cmd.arg("-no-shell-escape");
        }

        cmd.arg(&input_file);

        cmd.env("TEXINPUTS", texinputs);
        cmd.current_dir(tmp.path());

        let output = cmd.output().map_err(RenderingError::RunError)?;

        if !output.status.success() {
            // latexmk failed,
            return Err(RenderingError::LatexError {
                status: output.status.code(),
                stdout: output.stdout,
                stderr: output.stderr,
            });
        }

        fs::read(output_file).map_err(RenderingError::ReadOutputFile)
    }
}

#[cfg(test)]
mod tests {
    use super::{RenderingError, TexRender};

    #[test]
    fn render_example_tex() {
        let doc = r"
        \documentclass{article}
        \begin{document}
        hello, world.
        \end{document}
        ";

        let tex = TexRender::from_bytes(doc.into());
        let _pdf = tex.render().unwrap();
    }

    #[test]
    fn broken_tex_gives_correct_error() {
        let doc = r"
        \documentSOBROKENclass{article}
        ";

        let tex = TexRender::from_bytes(doc.into());

        match tex.render() {
            Err(RenderingError::LatexError { .. }) => (),
            other => panic!("expected latex error, got {:?}", other),
        }
    }
}