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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#![deny(dead_code)]
#![deny(unreachable_patterns)]
#![deny(unused_extern_crates)]
#![deny(unused_imports)]
#![deny(unused_qualifications)]
#![deny(clippy::all)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![deny(unused_results)]
#![deny(variant_size_differences)]

//! A set of utilites used across crates.
//! Note that these call some external commands:
//! - `latexmk` (and by extension xelatex)
//! - `pdftocairo` (only if required to convert a pdf image -- will gracefully fallback if not present)
//!
//! The following are not necessary for normal operation,
//! but are useful in development:
//! - `epubcheck`
//! - `pdftotext`
//!
//! If used in combination with `bookbinder`, the following packages are needed for LaTex calls:
//!
//! -`titlesec`
//! -`caption`
//! -`geometry`
//! -`ulem`
//! -`textcase`
//! -`xpatch`
//! -`amsmath`
//! -`amssymb`
//! -`bookmark`
//! -`booktabs`
//! -`etoolbox`
//! -`fancyhdr`
//! -`fancyvrb`
//! -`footnotehyper`
//! -`listings`
//! -`longtable`
//! -`unicode-math`
//! -`upquote`
//! -`xcolor`
//! -`xurl`
//! -`fontspec`
//! -`graphicx`
//! -`microtype`
//! -`hyperref`
//! -`fmtcount`
//! -`appendix`

use std::borrow::Cow;
use std::error::Error;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
mod num_conversions;
use std::io::Write;
mod isbn;
mod mimetypes;
use aho_corasick::AhoCorasick;
pub use isbn::{display_isbn, validate_isbn};
pub use mimetypes::{GuessMimeType, MimeType, MimeTypeHelper};
mod svg;
use lazy_static::lazy_static;
pub use svg::{convert_svg_file_to_png, convert_svg_to_jpg, convert_svg_to_png, simplify_svg};
use temp_file_name::HashToString;
pub mod fonts;

lazy_static! {
    static ref HTML_FINDER: AhoCorasick = AhoCorasick::new(&HTML_TARGET_CHARS);
    static ref LATEX_FINDER: AhoCorasick = AhoCorasick::new(&LATEX_TARGET_CHARS);
}

static HTML_TARGET_CHARS: [&str; 4] = ["<", ">", "&", "'"];

static HTML_REPLACEMENTS: [&str; 4] = ["&lt;", "&gt;", "&amp;", "’"];

/// escape `input` for html output
pub fn escape_to_html<'a, S: Into<Cow<'a, str>>>(input: S) -> Cow<'a, str> {
    let input = input.into();
    let input_bytes = input.as_bytes();
    if HTML_FINDER.is_match(input_bytes) {
        let mut wtr = Vec::with_capacity(input.len());
        HTML_FINDER
            .stream_replace_all(input_bytes, &mut wtr, &HTML_REPLACEMENTS)
            .expect("Aho-Corasick error");
        unsafe { Cow::Owned(String::from_utf8_unchecked(wtr)) }
    } else {
        input
    }
}

static LATEX_TARGET_CHARS: [&str; 16] = [
    "…", "–", "—", "\u{a0}", "&", "%", "$", "#", "_", "{", "}", "[", "]", "~", "^", "\\",
];

static LATEX_REPLACEMENTS: [&str; 16] = [
    "\\ldots{}",
    "--",
    "---",
    "~",
    "\\&",
    r"\%",
    r"\$",
    r"\#",
    r"\_",
    r"\{",
    r"\}",
    r"{[}",
    r"{]}",
    r"\textasciitilde{}",
    r"\textasciicircum{}",
    r"\textbackslash{}",
];

/// escape `input` for latex output
pub fn escape_to_latex<'a, S: Into<Cow<'a, str>>>(input: S) -> Cow<'a, str> {
    let input = input.into();
    let input_bytes = input.as_bytes();
    if LATEX_FINDER.is_match(input_bytes) {
        let mut wtr = Vec::with_capacity(input.len());
        LATEX_FINDER
            .stream_replace_all(input_bytes, &mut wtr, &LATEX_REPLACEMENTS)
            .expect("Aho-Corasick error");
        unsafe { Cow::Owned(String::from_utf8_unchecked(wtr)) }
    } else {
        input
    }
}

/// call lualatex on a particular str and return the pdf
pub fn call_latex(tex: &str) -> Result<Vec<u8>, std::io::Error> {
    _call_latex(tex, false)
}

/// call lualatex on a particular str and return the pdf,
/// displaying lualatex's output as it goes
pub fn call_latex_verbose(tex: &str) -> Result<Vec<u8>, std::io::Error> {
    _call_latex(tex, true)
}

/// call a latex engine on a particular str and return the pdf
fn _call_latex(tex: &str, verbose: bool) -> Result<Vec<u8>, std::io::Error> {
    let filename_base = tex.hash_to_string();
    let mut outdir = std::env::temp_dir();
    outdir = outdir.join("bookbinder");

    let tex_fn = format!("{}.tex", &filename_base);
    let texpath = outdir.join(tex_fn);
    let filename = format!("{}.pdf", &filename_base);
    let outpath = outdir.join(&filename);

    std::fs::write(&texpath, tex)?;

    let odir_arg = format!("-output-directory={}", &outdir.to_string_lossy());

    let mut ltx = if !verbose {
        Command::new("latexmk")
            .args(&[
                &odir_arg,
                "-xelatex",
                "-interaction=batchmode",
                "-halt-on-error",
                texpath.to_string_lossy().as_ref(),
            ])
            .spawn()?
    } else {
        Command::new("latexmk")
            .args(&[&odir_arg, "-xelatex", texpath.to_string_lossy().as_ref()])
            .spawn()?
    };

    let _ = ltx.wait()?;

    if !outpath.exists() {
        let mut log = texpath;
        let _ = log.set_extension("log");
        let log = std::fs::read_to_string(log).unwrap_or_else(|_| {
            "Latex error without log generated; perhaps LaTeX is not installed?".to_string()
        });
        let e = std::io::Error::new(std::io::ErrorKind::Other, log);
        return Err(e);
    }
    let o = std::fs::read(outpath)?;
    Ok(o)
}

/// Call `epubcheck` on a file to check that it is a valid epub
pub fn epubcheck(p: PathBuf) -> Result<(), String> {
    let epubcheck = Command::new("epubcheck")
        .arg(p.to_str().unwrap())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .map_err(|_| "Error launching epubcheck -- is it installed?".to_string())?;

    if epubcheck.status.success() {
        Ok(())
    } else {
        let (stdout, stderr) = unsafe {
            let stdout = String::from_utf8_unchecked(epubcheck.stdout);
            let stderr = String::from_utf8_unchecked(epubcheck.stderr);
            (stdout, stderr)
        };
        let mut msg = String::new();
        msg.push_str(&stdout);
        msg.push_str(&stderr);
        Err(msg)
    }
}

/// Convert an image at path `filepath` to a jpeg;
/// generally common raster formats as well as svg and pdf are supported,
/// but note that eps files are not
pub fn convert_to_jpg<P: AsRef<Path>>(filepath: P) -> Result<Vec<u8>, Box<dyn Error>> {
    let p = filepath.as_ref();
    let ext = p.extension().map(|o| o.to_str()).flatten();

    match ext {
        Some("pdf") => {
            let data = std::fs::read(p)?;
            let svg = convert_pdf_to_svg(&data, None)?;
            let jpg = convert_svg_to_jpg(&svg, None)?;
            Ok(jpg)
        }
        Some("svg") => {
            let svg = std::fs::read_to_string(p)?;
            let jpg = convert_svg_to_jpg(&svg, None)?;
            Ok(jpg)
        }
        _ => {
            let mut output = Vec::new();
            let dynamic_image = image::open(p)?;
            dynamic_image.write_to(&mut output, image::ImageOutputFormat::Jpeg(100))?;
            Ok(output)
        }
    }
}

/// convert a pdf file to an svg; requires that pdftocairo (part of poppler)
/// be installed.
/// Note that we can't link poppler without licensing difficulties, so there are no plans
/// to incorporate this as a dependency.
pub fn convert_pdf_to_svg(pdf: &[u8], dpi: Option<usize>) -> Result<String, Box<dyn Error>> {
    let dpi = dpi.unwrap_or(150).to_string();
    let mut cv = Command::new("pdftocairo")
        .args(&["-svg", "-origpagesizes", "-r", &dpi, "-", "-"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()?;

    let stdin = cv.stdin.as_mut().unwrap();
    stdin.write_all(&pdf)?;
    let o = cv.wait_with_output()?;
    let mut svg = String::from_utf8(o.stdout)?;

    // remove hardcoded widths
    svg = svg.replacen(r#"width="432pt""#, r#"width="100%""#, 1);
    svg = svg.replacen(
        r#"height="648pt""#,
        r#"height="100%" preserveAspectRatio="xMidYMid meet" x="0px" y="0px""#,
        1,
    );

    Ok(svg)
}

/// get the current year as a string
pub fn get_current_year() -> String {
    let now = time::now_utc();
    time::strftime("%Y", &now).unwrap()
}

/// given a number, return the corresponding letter
/// e.g. 0 -> A, 1 -> B, 2 -> C.
/// Returns an error if the number is greater than 25
/// ```
/// # use bookbinder_common::number_to_letter;
/// let number = 1;
/// assert_eq!(number_to_letter(number), Ok('B'));
/// ```
pub const fn number_to_letter(n: u8) -> Result<char, ()> {
    if n > 25 {
        Err(())
    } else {
        let codepoint = 65 + n;
        let letter = codepoint as char;
        Ok(letter)
    }
}

/// given a number, return it in roman format
/// e.g. 1 -> I, 10 -> X, etc
/// ```
/// # use bookbinder_common::number_to_roman;
/// let number = 1;
/// assert_eq!(number_to_roman(number), "I");
/// ```
pub const fn number_to_roman(n: u8) -> &'static str {
    num_conversions::number_to_roman(n)
}

/// given a number, return its equivalent in words
/// ```
/// # use bookbinder_common::number_to_words;
/// let number = 1;
/// assert_eq!(number_to_words(number), "ONE");
/// ```
pub const fn number_to_words(n: u8) -> &'static str {
    num_conversions::number_to_words(n)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_numbers_to_letter() {
        assert_eq!(number_to_letter(0), Ok('A'));
        assert_eq!(number_to_letter(25), Ok('Z'));
        assert_eq!(number_to_letter(27), Err(()));
    }

    #[test]
    fn test_get_current_year() {
        assert_eq!(get_current_year(), "2020".to_string());
    }

    #[test]
    fn test_hash_to_string() {
        let s = "Hello world".hash_to_string();
        assert_eq!(s, "2216321107127430384");
    }

    #[test]
    fn test_latex_escapes() {
        let escapes = [
            ("&", "\\&"),
            ("%", "\\%"),
            ("$", "\\$"),
            ("#", "\\#"),
            ("_", "\\_"),
            ("{Hello}", "\\{Hello\\}"),
            ("[Hello]", "{[}Hello{]}"),
            ("~", "\\textasciitilde{}"),
            ("^", "\\textasciicircum{}"),
            ("\\", "\\textbackslash{}"),
            //("'quoted'", "\\textquotesingle{}quoted\\textquotesingle{}"),
            //("\"doublequoted\"", "\\textquoteddbl{}doublequoted\\textquoteddbl{}"),
            //("`", "\\textasciigrave{}"),
            //("<>", "\\textless{}\\textgreater{}"),
            //("|", "\\textbar{}")
        ];
        for (input, expected) in escapes.iter() {
            let s = input.to_string();
            let out = escape_to_latex(&s);
            assert_eq!(out.to_string(), *expected);
        }
    }

    #[test]
    fn test_numbers_to_word() {
        assert_eq!(number_to_words(0), "ZERO");
        assert_eq!(number_to_words(5), "FIVE");
        assert_eq!(number_to_words(12), "TWELVE");
        assert_eq!(number_to_words(25), "TWENTY-FIVE");
        assert_eq!(number_to_words(125), "ONE HUNDRED AND TWENTY-FIVE");
    }

    #[test]
    fn test_numbers_to_roman() {
        assert_eq!(number_to_roman(0), "");
        assert_eq!(number_to_roman(1), "I");
    }
}