summaryrefslogtreecommitdiff
path: root/src/layout/mod.rs
blob: e5fdc42d714ecf843eb3819482940fea071edd47 (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
//! The layouting engine.

use std::borrow::Cow;
use std::mem;

use toddle::query::{SharedFontLoader, FontClass};
use toddle::Error as FontError;

use crate::doc::LayoutAction;
use crate::size::{Size, Size2D, SizeBox};
use crate::syntax::{SyntaxTree, Node, FuncCall};
use crate::style::TextStyle;

use self::flex::{FlexLayout, FlexContext};
use self::boxed::{BoxLayout, BoxContext, BoxLayouter};
use self::text::TextContext;

pub mod text;
pub mod boxed;
pub mod flex;


/// A collection of layouted content.
#[derive(Debug, Clone)]
pub enum Layout {
    /// A box layout.
    Boxed(BoxLayout),
    /// A flexible layout.
    Flex(FlexLayout),
}

/// Layout a syntax tree in a given context.
pub fn layout(tree: &SyntaxTree, ctx: LayoutContext) -> LayoutResult<BoxLayout> {
    Layouter::new(tree, ctx).layout()
}

/// The context for layouting.
#[derive(Copy, Clone)]
pub struct LayoutContext<'a, 'p> {
    /// Loads fonts matching queries.
    pub loader: &'a SharedFontLoader<'p>,
    /// Base style to set text with.
    pub style: &'a TextStyle,
    /// The space to layout in.
    pub space: LayoutSpace,
}

/// Spacial constraints for layouting.
#[derive(Debug, Copy, Clone)]
pub struct LayoutSpace {
    /// The maximum size of the box to layout in.
    pub dimensions: Size2D,
    /// Padding that should be respected on each side.
    pub padding: SizeBox,
    /// The alignment to use for the content.
    pub alignment: Alignment,
    /// Whether to shrink the dimensions to fit the content or the keep the
    /// original ones.
    pub shrink_to_fit: bool,
}

/// Where to align content.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Alignment {
    Left,
    Right,
}

impl LayoutSpace {
    /// The actually usable area.
    pub fn usable(&self) -> Size2D {
        Size2D {
            x: self.dimensions.x - self.padding.left - self.padding.right,
            y: self.dimensions.y - self.padding.top - self.padding.bottom,
        }
    }
}

/// Transforms a syntax tree into a box layout.
struct Layouter<'a, 'p> {
    tree: &'a SyntaxTree,
    box_layouter: BoxLayouter,
    flex_layout: FlexLayout,
    loader: &'a SharedFontLoader<'p>,
    style: Cow<'a, TextStyle>,
}

impl<'a, 'p> Layouter<'a, 'p> {
    /// Create a new layouter.
    fn new(tree: &'a SyntaxTree, ctx: LayoutContext<'a, 'p>) -> Layouter<'a, 'p> {
        Layouter {
            tree,
            box_layouter: BoxLayouter::new(BoxContext { space: ctx.space }),
            flex_layout: FlexLayout::new(),
            loader: ctx.loader,
            style: Cow::Borrowed(ctx.style)
        }
    }

    /// Layout the tree into a box.
    fn layout(mut self) -> LayoutResult<BoxLayout> {
        // Walk all nodes and layout them.
        for node in &self.tree.nodes {
            match node {
                // Layout a single piece of text.
                Node::Text(text) => self.layout_text(text, false)?,

                // Add a space.
                Node::Space => {
                    if !self.flex_layout.is_empty() {
                        self.layout_text(" ", true)?;
                    }
                },

                // Finish the current flex layout and add it to the box layouter.
                Node::Newline => {
                    // Finish the current paragraph into a box and add it.
                    self.layout_flex()?;

                    // Add some paragraph spacing.
                    let size = Size::pt(self.style.font_size)
                        * (self.style.line_spacing * self.style.paragraph_spacing - 1.0);
                    self.box_layouter.add_space(size)?;
                },

                // Toggle the text styles.
                Node::ToggleItalics => self.style.to_mut().toggle_class(FontClass::Italic),
                Node::ToggleBold => self.style.to_mut().toggle_class(FontClass::Bold),
                Node::ToggleMonospace => self.style.to_mut().toggle_class(FontClass::Monospace),

                // Execute a function.
                Node::Func(func) => self.layout_func(func)?,
            }
        }

        // If there are remainings, add them to the layout.
        if !self.flex_layout.is_empty() {
            self.layout_flex()?;
        }

        Ok(self.box_layouter.finish())
    }

    /// Layout a piece of text into a box.
    fn layout_text(&mut self, text: &str, glue: bool) -> LayoutResult<()> {
        let boxed = self::text::layout(text, TextContext {
            loader: &self.loader,
            style: &self.style,
        })?;

        if glue {
            self.flex_layout.add_glue(boxed);
        } else {
            self.flex_layout.add_box(boxed);
        }

        Ok(())
    }

    /// Finish the current flex run and return the resulting box.
    fn layout_flex(&mut self) -> LayoutResult<()> {
        let mut layout = FlexLayout::new();
        mem::swap(&mut layout, &mut self.flex_layout);

        let boxed = layout.finish(FlexContext {
            space: LayoutSpace {
                dimensions: self.box_layouter.remaining(),
                padding: SizeBox::zero(),
                alignment: self.box_layouter.ctx.space.alignment,
                shrink_to_fit: true,
            },
            flex_spacing: (self.style.line_spacing - 1.0) * Size::pt(self.style.font_size),
        })?;

        self.box_layouter.add_box(boxed)
    }

    /// Layout a function.
    fn layout_func(&mut self, func: &FuncCall) -> LayoutResult<()> {
        let layout = func.body.layout(LayoutContext {
            loader: &self.loader,
            style: &self.style,
            space: LayoutSpace {
                dimensions: self.box_layouter.remaining(),
                padding: SizeBox::zero(),
                alignment: self.box_layouter.ctx.space.alignment,
                shrink_to_fit: true,
            },
        })?;

        // Add the potential layout.
        if let Some(layout) = layout {
            match layout {
                Layout::Boxed(boxed) => {
                    // Finish the previous flex run before adding the box.
                    self.layout_flex()?;
                    self.box_layouter.add_box(boxed)?;
                },
                Layout::Flex(flex) => self.flex_layout.add_flexible(flex),
            }
        }

        Ok(())
    }
}

/// Manipulates and optimizes a list of actions.
#[derive(Debug, Clone)]
pub struct ActionList {
    pub origin: Size2D,
    actions: Vec<LayoutAction>,
    active_font: (usize, f32),
}

impl ActionList {
    /// Create a new action list.
    pub fn new() -> ActionList {
        ActionList {
            actions: vec![],
            origin: Size2D::zero(),
            active_font: (std::usize::MAX, 0.0),
        }
    }

    /// Add an action to the list if it is not useless
    /// (like changing to a font that is already active).
    pub fn add(&mut self, action: LayoutAction) {
        use LayoutAction::*;
        match action {
            MoveAbsolute(pos) => self.actions.push(MoveAbsolute(self.origin + pos)),
            SetFont(index, size) => if (index, size) != self.active_font {
                self.active_font = (index, size);
                self.actions.push(action);
            },
            _ => self.actions.push(action),
        }
    }

    /// Add a series of actions.
    pub fn extend<I>(&mut self, actions: I) where I: IntoIterator<Item=LayoutAction> {
        for action in actions.into_iter() {
            self.add(action);
        }
    }

    /// Add all actions from a box layout at a position. A move to the position
    /// is generated and all moves inside the box layout are translated as necessary.
    pub fn add_box_absolute(&mut self, position: Size2D, layout: BoxLayout) {
        self.actions.push(LayoutAction::MoveAbsolute(position));
        self.origin = position;
        self.extend(layout.actions);
    }

    /// Whether there are any actions in this list.
    pub fn is_empty(&self) -> bool {
        self.actions.is_empty()
    }

    /// Return the list of actions as a vector.
    pub fn into_vec(self) -> Vec<LayoutAction> {
        self.actions
    }
}

/// The error type for layouting.
pub enum LayoutError {
    /// There is not enough space to add an item.
    NotEnoughSpace,
    /// There was no suitable font for the given character.
    NoSuitableFont(char),
    /// An error occured while gathering font data.
    Font(FontError),
}

/// The result type for layouting.
pub type LayoutResult<T> = Result<T, LayoutError>;

error_type! {
    err: LayoutError,
    show: f => match err {
        LayoutError::NotEnoughSpace => write!(f, "not enough space"),
        LayoutError::NoSuitableFont(c) => write!(f, "no suitable font for '{}'", c),
        LayoutError::Font(err) => write!(f, "font error: {}", err),
    },
    source: match err {
        LayoutError::Font(err) => Some(err),
        _ => None,
    },
    from: (std::io::Error, LayoutError::Font(FontError::Io(err))),
    from: (FontError, LayoutError::Font(err)),
}