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
|
//! The core layouting engine.
use std::io::{self, Write};
use smallvec::SmallVec;
use toddle::query::{FontClass, SharedFontLoader};
use toddle::Error as FontError;
use crate::func::Command;
use crate::size::{Size, Size2D, SizeBox};
use crate::style::{PageStyle, TextStyle};
use crate::syntax::{FuncCall, Node, SyntaxTree};
mod actions;
mod tree;
mod flex;
mod stack;
mod text;
/// Different kinds of layouters (fully re-exported).
pub mod layouters {
pub use super::tree::layout_tree;
pub use super::flex::{FlexLayouter, FlexContext};
pub use super::stack::{StackLayouter, StackContext};
pub use super::text::{layout_text, TextContext};
}
pub use actions::{LayoutAction, LayoutActionList};
pub use layouters::*;
/// A sequence of layouting actions inside a box.
#[derive(Debug, Clone)]
pub struct Layout {
/// The size of the box.
pub dimensions: Size2D,
/// The actions composing this layout.
pub actions: Vec<LayoutAction>,
/// Whether to debug-render this box.
pub debug_render: bool,
}
impl Layout {
/// Serialize this layout into an output buffer.
pub fn serialize<W: Write>(&self, f: &mut W) -> io::Result<()> {
writeln!(
f,
"{:.4} {:.4}",
self.dimensions.x.to_pt(),
self.dimensions.y.to_pt()
)?;
writeln!(f, "{}", self.actions.len())?;
for action in &self.actions {
action.serialize(f)?;
writeln!(f)?;
}
Ok(())
}
}
/// A collection of layouts.
#[derive(Debug, Clone)]
pub struct MultiLayout {
pub layouts: Vec<Layout>,
}
impl MultiLayout {
/// Create an empty multi-layout.
pub fn new() -> MultiLayout {
MultiLayout { layouts: vec![] }
}
/// Extract the single sublayout. This panics if the layout does not have
/// exactly one child.
pub fn into_single(mut self) -> Layout {
if self.layouts.len() != 1 {
panic!("into_single: contains not exactly one layout");
}
self.layouts.pop().unwrap()
}
/// Add a sublayout.
pub fn add(&mut self, layout: Layout) {
self.layouts.push(layout);
}
/// The count of sublayouts.
pub fn count(&self) -> usize {
self.layouts.len()
}
/// Whether this layout contains any sublayouts.
pub fn is_empty(&self) -> bool {
self.layouts.is_empty()
}
}
impl MultiLayout {
/// Serialize this collection of layouts into an output buffer.
pub fn serialize<W: Write>(&self, f: &mut W) -> io::Result<()> {
writeln!(f, "{}", self.count())?;
for layout in self {
layout.serialize(f)?;
}
Ok(())
}
}
impl IntoIterator for MultiLayout {
type Item = Layout;
type IntoIter = std::vec::IntoIter<Layout>;
fn into_iter(self) -> Self::IntoIter {
self.layouts.into_iter()
}
}
impl<'a> IntoIterator for &'a MultiLayout {
type Item = &'a Layout;
type IntoIter = std::slice::Iter<'a, Layout>;
fn into_iter(self) -> Self::IntoIter {
self.layouts.iter()
}
}
/// The general context for layouting.
#[derive(Debug, Clone)]
pub struct LayoutContext<'a, 'p> {
/// The font loader to retrieve fonts from when typesetting text
/// using [`layout_text`].
pub loader: &'a SharedFontLoader<'p>,
/// Whether this layouting process handles the top-level pages.
pub top_level: bool,
/// The style to set text with. This includes sizes and font classes
/// which determine which font from the loaders selection is used.
pub text_style: &'a TextStyle,
/// The current size and margins of the top-level pages.
pub page_style: PageStyle,
/// The spaces to layout in.
pub spaces: LayoutSpaces,
/// The axes to flow on.
pub axes: LayoutAxes,
/// Whether layouts should expand to the full dimensions of the space
/// they lie on or whether should tightly fit the content.
pub expand: bool,
}
/// A possibly stack-allocated vector of layout spaces.
pub type LayoutSpaces = SmallVec<[LayoutSpace; 2]>;
/// Spacial layouting constraints.
#[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,
}
impl LayoutSpace {
/// The actually usable area (dimensions minus padding).
pub fn usable(&self) -> Size2D {
self.dimensions.unpadded(self.padding)
}
/// The offset from the origin to the start of content, that is,
/// `(padding.left, padding.top)`.
pub fn start(&self) -> Size2D {
Size2D::new(self.padding.left, self.padding.right)
}
/// A layout space without padding and dimensions reduced by the padding.
pub fn usable_space(&self) -> LayoutSpace {
LayoutSpace {
dimensions: self.usable(),
padding: SizeBox::zero(),
}
}
}
/// The axes along which the content is laid out.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct LayoutAxes {
pub primary: AlignedAxis,
pub secondary: AlignedAxis,
}
impl LayoutAxes {
/// Returns the generalized version of a `Size2D` dependent on
/// the layouting axes, that is:
/// - The x coordinate describes the primary axis instead of the horizontal one.
/// - The y coordinate describes the secondary axis instead of the vertical one.
pub fn generalize(&self, size: Size2D) -> Size2D {
if self.primary.axis.is_horizontal() {
size
} else {
Size2D { x: size.y, y: size.x }
}
}
/// Returns the specialized version of this generalized Size2D.
/// (Inverse to `generalized`).
pub fn specialize(&self, size: Size2D) -> Size2D {
// In fact, generalized is its own inverse. For reasons of clarity
// at the call site, we still have this second function.
self.generalize(size)
}
/// The position of the anchor specified by the two aligned axes
/// in the given generalized space.
pub fn anchor(&self, space: Size2D) -> Size2D {
Size2D::new(self.primary.anchor(space.x), self.secondary.anchor(space.y))
}
/// This axes with `expand` set to the given value for both axes.
pub fn expanding(&self, expand: bool) -> LayoutAxes {
LayoutAxes {
primary: self.primary.expanding(expand),
secondary: self.secondary.expanding(expand),
}
}
}
/// An axis with an alignment.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct AlignedAxis {
pub axis: Axis,
pub alignment: Alignment,
pub expand: bool,
}
impl AlignedAxis {
/// Creates an aligned axis from its three components.
pub fn new(axis: Axis, alignment: Alignment, expand: bool) -> AlignedAxis {
AlignedAxis { axis, alignment, expand }
}
/// The position of the anchor specified by this axis on the given line.
pub fn anchor(&self, line: Size) -> Size {
use Alignment::*;
match (self.axis.is_positive(), self.alignment) {
(true, Origin) | (false, End) => Size::zero(),
(_, Center) => line / 2,
(true, End) | (false, Origin) => line,
}
}
/// This axis with `expand` set to the given value.
pub fn expanding(&self, expand: bool) -> AlignedAxis {
AlignedAxis { expand, ..*self }
}
/// Whether this axis needs expansion.
pub fn needs_expansion(&self) -> bool {
self.expand || self.alignment != Alignment::Origin
}
}
/// Where to put content.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Axis {
LeftToRight,
RightToLeft,
TopToBottom,
BottomToTop,
}
impl Axis {
/// Whether this is a horizontal axis.
pub fn is_horizontal(&self) -> bool {
match self {
Axis::LeftToRight | Axis::RightToLeft => true,
Axis::TopToBottom | Axis::BottomToTop => false,
}
}
/// Whether this axis points into the positive coordinate direction.
pub fn is_positive(&self) -> bool {
match self {
Axis::LeftToRight | Axis::TopToBottom => true,
Axis::RightToLeft | Axis::BottomToTop => false,
}
}
/// The direction factor for this axis.
///
/// - 1 if the axis is positive.
/// - -1 if the axis is negative.
pub fn factor(&self) -> i32 {
if self.is_positive() { 1 } else { -1 }
}
}
/// Where to align content.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Alignment {
Origin,
Center,
End,
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum SpaceKind {
/// Soft spaces are eaten up by hard spaces before or after them.
Soft,
/// Independent do not eat up soft spaces and are not eaten up by hard spaces.
Independent,
/// Hard spaces eat up soft spaces before or after them.
Hard,
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum SpaceState {
Soft(Size),
Forbidden,
Allowed,
}
impl SpaceState {
fn soft_or_zero(&self) -> Size {
if let SpaceState::Soft(space) = self { *space } else { Size::zero() }
}
}
/// The error type for layouting.
pub struct LayoutError(String);
/// The result type for layouting.
pub type LayoutResult<T> = Result<T, LayoutError>;
impl LayoutError {
/// Create a new layout error with a message.
pub fn new<S: Into<String>>(message: S) -> LayoutError {
LayoutError(message.into())
}
}
error_type! {
err: LayoutError,
show: f => f.write_str(&err.0),
from: (std::io::Error, LayoutError::new(err.to_string())),
from: (FontError, LayoutError::new(err.to_string())),
}
|