summaryrefslogtreecommitdiff
path: root/src/exec/context.rs
blob: 6ba5b25f5590d9aa55eb0e747b9ef28c4268cba1 (plain) (blame)
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
use std::mem;
use std::rc::Rc;

use fontdock::FontStyle;

use super::{Exec, FontFamily, State};
use crate::diag::{Diag, DiagSet, Pass};
use crate::env::Env;
use crate::eval::TemplateValue;
use crate::geom::{Dir, Gen, Linear, Sides, Size};
use crate::layout::{
    Node, PadNode, PageRun, ParNode, SpacingNode, StackNode, TextNode, Tree,
};
use crate::parse::{is_newline, Scanner};
use crate::syntax::{Span, Spanned};

/// The context for execution.
#[derive(Debug)]
pub struct ExecContext<'a> {
    /// The environment from which resources are gathered.
    pub env: &'a mut Env,
    /// The active execution state.
    pub state: State,
    /// Execution diagnostics.
    pub diags: DiagSet,
    /// The tree of finished page runs.
    tree: Tree,
    /// Metrics of the active page.
    page: Option<PageInfo>,
    /// The content of the active stack. This may be the top-level stack for the
    /// page or a lower one created by [`exec`](Self::exec).
    stack: StackNode,
    /// The content of the active paragraph.
    par: ParNode,
}

impl<'a> ExecContext<'a> {
    /// Create a new execution context with a base state.
    pub fn new(env: &'a mut Env, state: State) -> Self {
        Self {
            env,
            diags: DiagSet::new(),
            tree: Tree { runs: vec![] },
            page: Some(PageInfo::new(&state, true)),
            stack: StackNode::new(&state),
            par: ParNode::new(&state),
            state,
        }
    }

    /// Add a diagnostic.
    pub fn diag(&mut self, diag: Diag) {
        self.diags.insert(diag);
    }

    /// Set the directions.
    ///
    /// Produces an error if the axes aligned.
    pub fn set_dirs(&mut self, new: Gen<Option<Spanned<Dir>>>) {
        let dirs = Gen::new(
            new.main.map(|s| s.v).unwrap_or(self.state.dirs.main),
            new.cross.map(|s| s.v).unwrap_or(self.state.dirs.cross),
        );

        if dirs.main.axis() != dirs.cross.axis() {
            self.state.dirs = dirs;
        } else {
            for dir in new.main.iter().chain(new.cross.iter()) {
                self.diag(error!(dir.span, "aligned axis"));
            }
        }
    }

    /// Set the font to monospace.
    pub fn set_monospace(&mut self) {
        let families = self.state.font.families_mut();
        families.list.insert(0, FontFamily::Monospace);
    }

    /// Push a layout node into the active paragraph.
    ///
    /// Spacing nodes will be handled according to their
    /// [`softness`](SpacingNode::softness).
    pub fn push(&mut self, node: impl Into<Node>) {
        push(&mut self.par.children, node.into());
    }

    /// Push a word space into the active paragraph.
    pub fn push_space(&mut self) {
        let em = self.state.font.font_size();
        self.push(SpacingNode {
            amount: self.state.par.word_spacing.resolve(em),
            softness: 1,
        });
    }

    /// Push text into the active paragraph.
    ///
    /// The text is split into lines at newlines.
    pub fn push_text(&mut self, text: &str) {
        let mut scanner = Scanner::new(text);
        let mut line = String::new();

        while let Some(c) = scanner.eat_merging_crlf() {
            if is_newline(c) {
                self.push(self.make_text_node(mem::take(&mut line)));
                self.push_linebreak();
            } else {
                line.push(c);
            }
        }

        self.push(self.make_text_node(line));
    }

    /// Apply a forced line break.
    pub fn push_linebreak(&mut self) {
        let em = self.state.font.font_size();
        self.push_into_stack(SpacingNode {
            amount: self.state.par.leading.resolve(em),
            softness: 2,
        });
    }

    /// Apply a forced paragraph break.
    pub fn push_parbreak(&mut self) {
        let em = self.state.font.font_size();
        self.push_into_stack(SpacingNode {
            amount: self.state.par.spacing.resolve(em),
            softness: 1,
        });
    }

    /// Push a node directly into the stack above the paragraph. This finishes
    /// the active paragraph and starts a new one.
    pub fn push_into_stack(&mut self, node: impl Into<Node>) {
        self.finish_par();
        push(&mut self.stack.children, node.into());
    }

    /// Execute a template and return the result as a stack node.
    pub fn exec(&mut self, template: &TemplateValue) -> StackNode {
        let page = self.page.take();
        let stack = mem::replace(&mut self.stack, StackNode::new(&self.state));
        let par = mem::replace(&mut self.par, ParNode::new(&self.state));

        template.exec(self);
        let result = self.finish_stack();

        self.page = page;
        self.stack = stack;
        self.par = par;

        result
    }

    /// Construct a text node from the given string based on the active text
    /// state.
    pub fn make_text_node(&self, text: String) -> TextNode {
        let mut variant = self.state.font.variant;

        if self.state.font.strong {
            variant.weight = variant.weight.thicken(300);
        }

        if self.state.font.emph {
            variant.style = match variant.style {
                FontStyle::Normal => FontStyle::Italic,
                FontStyle::Italic => FontStyle::Normal,
                FontStyle::Oblique => FontStyle::Normal,
            }
        }

        TextNode {
            text,
            dir: self.state.dirs.cross,
            aligns: self.state.aligns,
            families: Rc::clone(&self.state.font.families),
            variant,
            font_size: self.state.font.font_size(),
            top_edge: self.state.font.top_edge,
            bottom_edge: self.state.font.bottom_edge,
            color: self.state.font.color,
        }
    }

    /// Finish the active paragraph.
    fn finish_par(&mut self) {
        let mut par = mem::replace(&mut self.par, ParNode::new(&self.state));
        trim(&mut par.children);

        if !par.children.is_empty() {
            self.stack.children.push(par.into());
        }
    }

    /// Finish the active stack.
    fn finish_stack(&mut self) -> StackNode {
        self.finish_par();

        let mut stack = mem::replace(&mut self.stack, StackNode::new(&self.state));
        trim(&mut stack.children);

        stack
    }

    /// Finish the active page.
    pub fn finish_page(&mut self, keep: bool, hard: bool, source: Span) {
        if let Some(info) = &mut self.page {
            let info = mem::replace(info, PageInfo::new(&self.state, hard));
            let stack = self.finish_stack();

            if !stack.children.is_empty() || (keep && info.hard) {
                self.tree.runs.push(PageRun {
                    size: info.size,
                    child: PadNode {
                        padding: info.padding,
                        child: stack.into(),
                    }
                    .into(),
                });
            }
        } else {
            self.diag(error!(source, "cannot modify page from here"));
        }
    }

    /// Finish execution and return the created layout tree.
    pub fn finish(mut self) -> Pass<Tree> {
        assert!(self.page.is_some());
        self.finish_page(true, false, Span::default());
        Pass::new(self.tree, self.diags)
    }
}

/// Push a node into a list, taking care of spacing softness.
fn push(nodes: &mut Vec<Node>, node: Node) {
    if let Node::Spacing(spacing) = node {
        if nodes.is_empty() && spacing.softness > 0 {
            return;
        }

        if let Some(&Node::Spacing(other)) = nodes.last() {
            if spacing.softness > 0 && spacing.softness >= other.softness {
                return;
            }

            if spacing.softness < other.softness {
                nodes.pop();
            }
        }
    }

    nodes.push(node);
}

/// Remove trailing soft spacing from a node list.
fn trim(nodes: &mut Vec<Node>) {
    if let Some(&Node::Spacing(spacing)) = nodes.last() {
        if spacing.softness > 0 {
            nodes.pop();
        }
    }
}

#[derive(Debug)]
struct PageInfo {
    size: Size,
    padding: Sides<Linear>,
    hard: bool,
}

impl PageInfo {
    fn new(state: &State, hard: bool) -> Self {
        Self {
            size: state.page.size,
            padding: state.page.margins(),
            hard,
        }
    }
}

impl StackNode {
    fn new(state: &State) -> Self {
        Self {
            dirs: state.dirs,
            aligns: state.aligns,
            children: vec![],
        }
    }
}

impl ParNode {
    fn new(state: &State) -> Self {
        let em = state.font.font_size();
        Self {
            dirs: state.dirs,
            aligns: state.aligns,
            line_spacing: state.par.leading.resolve(em),
            children: vec![],
        }
    }
}