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
use std::fs;
use std::collections::HashMap;

use tera::{self, Tera, Context, Value};
use serde_json::Map as JsonMap;

use crate::project::{Project, OutputSpec};
use crate::error::*;
use super::Render;


fn latex_escape(input: &str) -> String {
    let mut res = String::with_capacity(input.len());
    for c in input.chars() {
        match c {
            '&' | '%' | '$' | '#' | '_' | '{' | '}' => {
                res.push('\\');
                res.push(c);
            },
            '[' => res.push_str("{\\lbrack}"),
            ']' => res.push_str("{\\rbrack}"),
            '~' => res.push_str("{\\textasciitilde}"),
            '^' => res.push_str("{\\textasciicircum}"),
            '\\' => res.push_str("{\\textbackslash}"),
            c => res.push(c),
        }
    }

    res
}

fn filter_latex(val: &Value, args: &HashMap<String, Value>) -> tera::Result<Value> {
    match val {
        Value::String(s) => Ok(Value::String(latex_escape(&s))),
        Value::Array(array) => {
            let mut escaped = Vec::with_capacity(array.len());
            for item in array {
                escaped.push(filter_latex(item, args)?);
            }
            Ok(Value::Array(escaped))
        },
        Value::Object(map) => {
            let mut escaped = JsonMap::new();
            for (key, value) in map.iter() {
                let value = filter_latex(value, args) ?;
                dbg!(&value);
                escaped.insert(latex_escape(key), value);
            }
            Ok(Value::Object(escaped))
        },
        other => Ok(other.clone()),
    }
}

fn filter_base64(val: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    match val {
        Value::String(s) => {
            let encoded = base64::encode(s.as_bytes());

            // Insert newlines at column 80:
            let mut cursor = encoded.as_str();
            let mut encoded_newlines = String::with_capacity(81 * encoded.len() / 80);
            while cursor.len() > 80 {
                let (p1, p2) = cursor.split_at(80);
                encoded_newlines.push_str(p1);
                encoded_newlines.push('\n');
                cursor = p2;
            }
            encoded_newlines.push_str(cursor);

            Ok(Value::String(encoded_newlines))
        }
        _ => Err(tera::Error::msg("base64 requires a string input"))
    }
}

pub trait DefaultTemaplate {
    const TPL_NAME: &'static str;
    const TPL_CONTENT: &'static str;
}

struct TeraRender<'a> {
    tera: Tera,
    tpl_name: String,
    project: &'a Project,
    output: &'a OutputSpec,
}

impl<'a> TeraRender<'a> {
    fn new<DT: DefaultTemaplate>(project: &'a Project, output: &'a OutputSpec) -> Result<Self> {
        let mut tera = Tera::default();

        let tpl_name = if let Some(template) = output.template.as_ref() {
            tera.add_template_file(&template, None)
                .context("Tera template error") ?;
    
            template.to_str().unwrap().to_string()
            // NB: ^ unwrap should be ok, UTF-8 validity is checked while parsing project settings TOML
        } else {
            tera.add_raw_template(DT::TPL_NAME, DT::TPL_CONTENT)
                .expect("Internal error: Could not load default Tera template");
            DT::TPL_NAME.to_string()
        };

        Ok(Self {
            tera,
            tpl_name,
            project,
            output,
        })
    }

    fn render(&self) -> Result<&'a OutputSpec> {
        let mut context = Context::new();
        context.insert("book", self.project.metadata());
        context.insert("songs", self.project.songs());
        context.insert("output", &self.output.metadata);
        if let Some(debug) = self.project.parsing_debug() {
            context.insert("debug", debug);
        }

        let html = self.tera.render(&self.tpl_name, &context) ?;

        fs::write(&self.output.file, html.as_bytes())
            .map_err(|err| ErrorWritingFile(self.output.file.to_owned(), err)) ?;

        Ok(self.output)
    }
}

pub struct RHtml;

impl DefaultTemaplate for RHtml {
    const TPL_NAME: &'static str = "template-html.html";
    const TPL_CONTENT: &'static str = include_str!("../../default/template-html.html");
}

impl Render for RHtml {
    fn render<'a>(project: &'a Project, output: &'a OutputSpec) -> Result<&'a OutputSpec> {
        let render = TeraRender::new::<Self>(project, output)?;
        render.render()
    }
}

pub struct RTex;

impl DefaultTemaplate for RTex {
    const TPL_NAME: &'static str = "template-tex.tex";
    const TPL_CONTENT: &'static str = include_str!("../../default/template-tex.tex");
}

impl Render for RTex {
    fn render<'a>(project: &'a Project, output: &'a OutputSpec) -> Result<&'a OutputSpec> {
        let mut render = TeraRender::new::<Self>(project, output)?;

        // Setup Latex escaping
        render.tera.set_escape_fn(latex_escape);
        render.tera.autoescape_on(vec![".tex"]);
        render.tera.register_filter("latex", filter_latex);
        render.tera.register_filter("base64", filter_base64);

        render.render()
    }
}