summaryrefslogtreecommitdiff
path: root/src/layout
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2020-08-02 22:05:49 +0200
committerLaurenz <laurmaedje@gmail.com>2020-08-02 22:05:49 +0200
commit266d457292e7461d448f9141030028ea68b573d1 (patch)
treeff3ff3cc289d34040db421b6a7faa1f2aa402b05 /src/layout
parentcbbc46215fe0a0ad8a50e991ec442890b8eadc0a (diff)
Refactor model into tree 🛒
Diffstat (limited to 'src/layout')
-rw-r--r--src/layout/elements.rs3
-rw-r--r--src/layout/line.rs16
-rw-r--r--src/layout/mod.rs477
-rw-r--r--src/layout/model.rs313
-rw-r--r--src/layout/primitive.rs350
-rw-r--r--src/layout/stack.rs58
-rw-r--r--src/layout/text.rs8
-rw-r--r--src/layout/tree.rs223
8 files changed, 725 insertions, 723 deletions
diff --git a/src/layout/elements.rs b/src/layout/elements.rs
index e524e1fd..92b53ae8 100644
--- a/src/layout/elements.rs
+++ b/src/layout/elements.rs
@@ -35,8 +35,7 @@ impl Default for LayoutElements {
}
}
-/// A layouting action, which is the basic building block layouts are composed
-/// of.
+/// A layout element, which is the basic building block layouts are composed of.
#[derive(Debug, Clone, PartialEq)]
pub enum LayoutElement {
/// Shaped text.
diff --git a/src/layout/line.rs b/src/layout/line.rs
index 6b2fd3c6..358d2ac9 100644
--- a/src/layout/line.rs
+++ b/src/layout/line.rs
@@ -45,7 +45,7 @@ pub struct LineContext {
#[derive(Debug)]
struct LineRun {
/// The so-far accumulated layouts in the line.
- layouts: Vec<(f64, Layout)>,
+ layouts: Vec<(f64, BoxLayout)>,
/// The width and maximal height of the line.
size: Size,
/// The alignment of all layouts in the line.
@@ -77,7 +77,7 @@ impl LineLayouter {
}
/// Add a layout to the run.
- pub fn add(&mut self, layout: Layout) {
+ pub fn add(&mut self, layout: BoxLayout) {
let axes = self.ctx.axes;
if let Some(align) = self.run.align {
@@ -116,7 +116,7 @@ impl LineLayouter {
self.add_primary_spacing(spacing, SpacingKind::Hard);
}
- let size = layout.dimensions.generalized(axes);
+ let size = layout.size.generalized(axes);
if !self.usable().fits(size) {
if !self.line_is_empty() {
@@ -125,7 +125,7 @@ impl LineLayouter {
// TODO: Issue warning about overflow if there is overflow.
if !self.usable().fits(size) {
- self.stack.skip_to_fitting_space(layout.dimensions);
+ self.stack.skip_to_fitting_space(layout.size);
}
}
@@ -222,7 +222,7 @@ impl LineLayouter {
/// a function how much space it has to layout itself.
pub fn remaining(&self) -> LayoutSpaces {
let mut spaces = self.stack.remaining();
- *spaces[0].dimensions.secondary_mut(self.ctx.axes)
+ *spaces[0].size.secondary_mut(self.ctx.axes)
-= self.run.size.y;
spaces
}
@@ -256,15 +256,15 @@ impl LineLayouter {
true => offset,
false => self.run.size.x
- offset
- - layout.dimensions.primary(self.ctx.axes),
+ - layout.size.primary(self.ctx.axes),
};
let pos = Size::with_x(x);
elements.extend_offset(pos, layout.elements);
}
- self.stack.add(Layout {
- dimensions: self.run.size.specialized(self.ctx.axes),
+ self.stack.add(BoxLayout {
+ size: self.run.size.specialized(self.ctx.axes),
align: self.run.align
.unwrap_or(LayoutAlign::new(Start, Start)),
elements
diff --git a/src/layout/mod.rs b/src/layout/mod.rs
index 41a314f0..143f1984 100644
--- a/src/layout/mod.rs
+++ b/src/layout/mod.rs
@@ -1,57 +1,100 @@
//! Layouting types and engines.
-use std::fmt::{self, Display, Formatter};
+use async_trait::async_trait;
+use crate::Pass;
+use crate::font::SharedFontLoader;
use crate::geom::{Size, Margins};
+use crate::style::{LayoutStyle, TextStyle, PageStyle};
+use crate::syntax::tree::SyntaxTree;
+
use elements::LayoutElements;
+use tree::TreeLayouter;
use prelude::*;
+pub mod elements;
pub mod line;
+pub mod primitive;
pub mod stack;
pub mod text;
-pub mod elements;
-pub_use_mod!(model);
+pub mod tree;
+
+pub use primitive::*;
/// Basic types used across the layouting engine.
pub mod prelude {
- pub use super::{
- layout, LayoutContext, LayoutSpace, Command, Commands,
- LayoutAxes, LayoutAlign, LayoutExpansion,
- };
- pub use super::Dir::{self, *};
- pub use super::GenAxis::{self, *};
- pub use super::SpecAxis::{self, *};
- pub use super::GenAlign::{self, *};
- pub use super::SpecAlign::{self, *};
+ pub use super::layout;
+ pub use super::primitive::*;
+ pub use Dir::*;
+ pub use GenAxis::*;
+ pub use SpecAxis::*;
+ pub use GenAlign::*;
+ pub use SpecAlign::*;
}
/// A collection of layouts.
-pub type MultiLayout = Vec<Layout>;
+pub type MultiLayout = Vec<BoxLayout>;
/// A finished box with content at fixed positions.
#[derive(Debug, Clone, PartialEq)]
-pub struct Layout {
+pub struct BoxLayout {
/// The size of the box.
- pub dimensions: Size,
+ pub size: Size,
/// How to align this layout in a parent container.
pub align: LayoutAlign,
- /// The actions composing this layout.
+ /// The elements composing this layout.
pub elements: LayoutElements,
}
-/// A vector of layout spaces, that is stack allocated as long as it only
-/// contains at most 2 spaces.
+/// Layouting of elements.
+#[async_trait(?Send)]
+pub trait Layout {
+ /// Layout self into a sequence of layouting commands.
+ async fn layout<'a>(&'a self, _: LayoutContext<'_>) -> Pass<Commands<'a>>;
+}
+
+/// Layout a syntax tree into a list of boxes.
+pub async fn layout(tree: &SyntaxTree, ctx: LayoutContext<'_>) -> Pass<MultiLayout> {
+ let mut layouter = TreeLayouter::new(ctx);
+ layouter.layout_tree(tree).await;
+ layouter.finish()
+}
+
+/// The context for layouting.
+#[derive(Debug, Clone)]
+pub struct LayoutContext<'a> {
+ /// The font loader to retrieve fonts from when typesetting text
+ /// using [`layout_text`].
+ pub loader: &'a SharedFontLoader,
+ /// The style for pages and text.
+ pub style: &'a LayoutStyle,
+ /// The base unpadded size of this container (for relative sizing).
+ pub base: Size,
+ /// The spaces to layout in.
+ pub spaces: LayoutSpaces,
+ /// Whether to have repeated spaces or to use only the first and only once.
+ pub repeat: bool,
+ /// The initial axes along which content is laid out.
+ pub axes: LayoutAxes,
+ /// The alignment of the finished layout.
+ pub align: LayoutAlign,
+ /// Whether the layout that is to be created will be nested in a parent
+ /// container.
+ pub nested: bool,
+}
+
+/// A collection of layout spaces.
pub type LayoutSpaces = Vec<LayoutSpace>;
/// The space into which content is laid out.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct LayoutSpace {
/// The maximum size of the box to layout in.
- pub dimensions: Size,
+ pub size: Size,
/// Padding that should be respected on each side.
pub padding: Margins,
- /// Whether to expand the dimensions of the resulting layout to the full
- /// dimensions of this space or to shrink them to fit the content.
+ /// Whether to expand the size of the resulting layout to the full size of
+ /// this space or to shrink them to fit the content.
pub expansion: LayoutExpansion,
}
@@ -62,363 +105,63 @@ impl LayoutSpace {
Size::new(self.padding.left, self.padding.top)
}
- /// The actually usable area (dimensions minus padding).
+ /// The actually usable area (size minus padding).
pub fn usable(&self) -> Size {
- self.dimensions.unpadded(self.padding)
+ self.size.unpadded(self.padding)
}
- /// A layout space without padding and dimensions reduced by the padding.
+ /// A layout space without padding and size reduced by the padding.
pub fn usable_space(&self) -> LayoutSpace {
LayoutSpace {
- dimensions: self.usable(),
+ size: self.usable(),
padding: Margins::ZERO,
expansion: LayoutExpansion::new(false, false),
}
}
}
-/// Specifies along which axes content is laid out.
-#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
-pub struct LayoutAxes {
- /// The primary layouting direction.
- pub primary: Dir,
- /// The secondary layouting direction.
- pub secondary: Dir,
-}
-
-impl LayoutAxes {
- /// Create a new instance from the two values.
- ///
- /// # Panics
- /// This function panics if the axes are aligned, that is, they are
- /// on the same axis.
- pub fn new(primary: Dir, secondary: Dir) -> LayoutAxes {
- if primary.axis() == secondary.axis() {
- panic!("invalid aligned axes {} and {}", primary, secondary);
- }
-
- LayoutAxes { primary, secondary }
- }
-
- /// Return the direction of the specified generic axis.
- pub fn get(self, axis: GenAxis) -> Dir {
- match axis {
- Primary => self.primary,
- Secondary => self.secondary,
- }
- }
-
- /// Borrow the direction of the specified generic axis mutably.
- pub fn get_mut(&mut self, axis: GenAxis) -> &mut Dir {
- match axis {
- Primary => &mut self.primary,
- Secondary => &mut self.secondary,
- }
- }
-}
-
-/// Directions along which content is laid out.
-#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
-pub enum Dir {
- LTT,
- RTL,
- TTB,
- BTT,
-}
-
-impl Dir {
- /// The specific axis this direction belongs to.
- pub fn axis(self) -> SpecAxis {
- match self {
- LTT | RTL => Horizontal,
- TTB | BTT => Vertical,
- }
- }
-
- /// Whether this axis points into the positive coordinate direction.
- ///
- /// The positive axes are left-to-right and top-to-bottom.
- pub fn is_positive(self) -> bool {
- match self {
- LTT | TTB => true,
- RTL | BTT => false,
- }
- }
-
- /// The factor for this direction.
- ///
- /// - `1` if the direction is positive.
- /// - `-1` if the direction is negative.
- pub fn factor(self) -> f64 {
- if self.is_positive() { 1.0 } else { -1.0 }
- }
-
- /// The inverse axis.
- pub fn inv(self) -> Dir {
- match self {
- LTT => RTL,
- RTL => LTT,
- TTB => BTT,
- BTT => TTB,
- }
- }
-}
-
-impl Display for Dir {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- f.pad(match self {
- LTT => "ltr",
- RTL => "rtl",
- TTB => "ttb",
- BTT => "btt",
- })
- }
-}
-
-/// The two generic layouting axes.
-#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
-pub enum GenAxis {
- /// The primary axis along which words are laid out.
- Primary,
- /// The secondary axis along which lines and paragraphs are laid out.
- Secondary,
-}
-
-impl GenAxis {
- /// The specific version of this axis in the given system of axes.
- pub fn to_specific(self, axes: LayoutAxes) -> SpecAxis {
- axes.get(self).axis()
- }
-}
-
-impl Display for GenAxis {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- f.pad(match self {
- Primary => "primary",
- Secondary => "secondary",
- })
- }
-}
-
-/// The two specific layouting axes.
-#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
-pub enum SpecAxis {
- /// The horizontal layouting axis.
- Horizontal,
- /// The vertical layouting axis.
- Vertical,
-}
-
-impl SpecAxis {
- /// The generic version of this axis in the given system of axes.
- pub fn to_generic(self, axes: LayoutAxes) -> GenAxis {
- if self == axes.primary.axis() { Primary } else { Secondary }
- }
-}
-
-impl Display for SpecAxis {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- f.pad(match self {
- Horizontal => "horizontal",
- Vertical => "vertical",
- })
- }
-}
-
-/// Specifies where to align a layout in a parent container.
-#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
-pub struct LayoutAlign {
- /// The alignment along the primary axis.
- pub primary: GenAlign,
- /// The alignment along the secondary axis.
- pub secondary: GenAlign,
-}
-
-impl LayoutAlign {
- /// Create a new instance from the two values.
- pub fn new(primary: GenAlign, secondary: GenAlign) -> LayoutAlign {
- LayoutAlign { primary, secondary }
- }
-
- /// Return the alignment of the specified generic axis.
- pub fn get(self, axis: GenAxis) -> GenAlign {
- match axis {
- Primary => self.primary,
- Secondary => self.secondary,
- }
- }
-
- /// Borrow the alignment of the specified generic axis mutably.
- pub fn get_mut(&mut self, axis: GenAxis) -> &mut GenAlign {
- match axis {
- Primary => &mut self.primary,
- Secondary => &mut self.secondary,
- }
- }
-}
-
-/// Where to align content along a generic context.
-#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
-pub enum GenAlign {
- Start,
- Center,
- End,
-}
-
-impl GenAlign {
- /// The inverse alignment.
- pub fn inv(self) -> GenAlign {
- match self {
- Start => End,
- Center => Center,
- End => Start,
- }
- }
-}
-
-impl Display for GenAlign {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- f.pad(match self {
- Start => "start",
- Center => "center",
- End => "end",
- })
- }
-}
-
-/// Where to align content in a specific context.
-#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
-pub enum SpecAlign {
- Left,
- Right,
- Top,
- Bottom,
- Center,
-}
+/// A sequence of layouting commands.
+pub type Commands<'a> = Vec<Command<'a>>;
-impl SpecAlign {
- /// The specific axis this alignment refers to.
+/// Commands issued to the layouting engine by trees.
+#[derive(Debug, Clone)]
+pub enum Command<'a> {
+ /// Layout the given tree in the current context (i.e. not nested). The
+ /// content of the tree is not laid out into a separate box and then added,
+ /// but simply laid out flat in the active layouting process.
///
- /// Returns `None` if this is center.
- pub fn axis(self) -> Option<SpecAxis> {
- match self {
- Self::Left => Some(Horizontal),
- Self::Right => Some(Horizontal),
- Self::Top => Some(Vertical),
- Self::Bottom => Some(Vertical),
- Self::Center => None,
- }
- }
-
- /// Convert this to a generic alignment.
- pub fn to_generic(self, axes: LayoutAxes) -> GenAlign {
- let get = |spec: SpecAxis, align: GenAlign| {
- let axis = spec.to_generic(axes);
- if axes.get(axis).is_positive() { align } else { align.inv() }
- };
-
- match self {
- Self::Left => get(Horizontal, Start),
- Self::Right => get(Horizontal, End),
- Self::Top => get(Vertical, Start),
- Self::Bottom => get(Vertical, End),
- Self::Center => GenAlign::Center,
- }
- }
-}
-
-impl Display for SpecAlign {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- f.pad(match self {
- Self::Left => "left",
- Self::Right => "right",
- Self::Top => "top",
- Self::Bottom => "bottom",
- Self::Center => "center",
- })
- }
-}
-
-/// Specifies whether to expand a layout to the full size of the space it is
-/// laid out in or to shrink it to fit the content.
-#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
-pub struct LayoutExpansion {
- /// Whether to expand on the horizontal axis.
- pub horizontal: bool,
- /// Whether to expand on the vertical axis.
- pub vertical: bool,
-}
-
-impl LayoutExpansion {
- /// Create a new instance from the two values.
- pub fn new(horizontal: bool, vertical: bool) -> LayoutExpansion {
- LayoutExpansion { horizontal, vertical }
- }
-
- /// Return the expansion value for the given specific axis.
- pub fn get(self, axis: SpecAxis) -> bool {
- match axis {
- Horizontal => self.horizontal,
- Vertical => self.vertical,
- }
- }
-
- /// Borrow the expansion value for the given specific axis mutably.
- pub fn get_mut(&mut self, axis: SpecAxis) -> &mut bool {
- match axis {
- Horizontal => &mut self.horizontal,
- Vertical => &mut self.vertical,
- }
- }
-}
-
-/// Defines how a given spacing interacts with (possibly existing) surrounding
-/// spacing.
-///
-/// There are two options for interaction: Hard and soft spacing. Typically,
-/// hard spacing is used when a fixed amount of space needs to be inserted no
-/// matter what. In contrast, soft spacing can be used to insert a default
-/// spacing between e.g. two words or paragraphs that can still be overridden by
-/// a hard space.
-#[derive(Debug, Copy, Clone, Eq, PartialEq)]
-pub enum SpacingKind {
- /// Hard spaces are always laid out and consume surrounding soft space.
- Hard,
- /// Soft spaces are not laid out if they are touching a hard space and
- /// consume neighbouring soft spaces with higher levels.
- Soft(u32),
-}
-
-impl SpacingKind {
- /// The standard spacing kind used for paragraph spacing.
- pub const PARAGRAPH: SpacingKind = SpacingKind::Soft(1);
-
- /// The standard spacing kind used for line spacing.
- pub const LINE: SpacingKind = SpacingKind::Soft(2);
-
- /// The standard spacing kind used for word spacing.
- pub const WORD: SpacingKind = SpacingKind::Soft(1);
-}
-
-/// The spacing kind of the most recently inserted item in a layouting process.
-/// This is not about the last _spacing item_, but the last _item_, which is why
-/// this can be `None`.
-#[derive(Debug, Copy, Clone, PartialEq)]
-enum LastSpacing {
- /// The last item was hard spacing.
- Hard,
- /// The last item was soft spacing with the given width and level.
- Soft(f64, u32),
- /// The last item was not spacing.
- None,
-}
-
-impl LastSpacing {
- /// The width of the soft space if this is a soft space or zero otherwise.
- fn soft_or_zero(self) -> f64 {
- match self {
- LastSpacing::Soft(space, _) => space,
- _ => 0.0,
- }
- }
+ /// This has the effect that the content fits nicely into the active line
+ /// layouting, enabling functions to e.g. change the style of some piece of
+ /// text while keeping it integrated in the current paragraph.
+ LayoutSyntaxTree(&'a SyntaxTree),
+
+ /// Add a already computed layout.
+ Add(BoxLayout),
+ /// Add multiple layouts, one after another. This is equivalent to multiple
+ /// [Add](Command::Add) commands.
+ AddMultiple(MultiLayout),
+
+ /// Add spacing of given [kind](super::SpacingKind) along the primary or
+ /// secondary axis. The spacing kind defines how the spacing interacts with
+ /// surrounding spacing.
+ AddSpacing(f64, SpacingKind, GenAxis),
+
+ /// Start a new line.
+ BreakLine,
+ /// Start a new paragraph.
+ BreakParagraph,
+ /// Start a new page, which will exist in the finished layout even if it
+ /// stays empty (since the page break is a _hard_ space break).
+ BreakPage,
+
+ /// Update the text style.
+ SetTextStyle(TextStyle),
+ /// Update the page style.
+ SetPageStyle(PageStyle),
+
+ /// Update the alignment for future boxes added to this layouting process.
+ SetAlignment(LayoutAlign),
+ /// Update the layouting axes along which future boxes will be laid
+ /// out. This finishes the current line.
+ SetAxes(LayoutAxes),
}
diff --git a/src/layout/model.rs b/src/layout/model.rs
deleted file mode 100644
index db069870..00000000
--- a/src/layout/model.rs
+++ /dev/null
@@ -1,313 +0,0 @@
-//! The model layouter layouts models (i.e.
-//! [syntax models](crate::syntax::SyntaxModel) and [functions](crate::func))
-//! by executing commands issued by the models.
-
-use std::future::Future;
-use std::pin::Pin;
-
-use crate::{Pass, Feedback};
-use crate::SharedFontLoader;
-use crate::style::{LayoutStyle, PageStyle, TextStyle};
-use crate::geom::Size;
-use crate::syntax::decoration::Decoration;
-use crate::syntax::model::{Model, SyntaxModel, Node};
-use crate::syntax::span::{Span, Spanned};
-use super::line::{LineLayouter, LineContext};
-use super::text::{layout_text, TextContext};
-use super::*;
-
-/// Performs the model layouting.
-#[derive(Debug)]
-pub struct ModelLayouter<'a> {
- ctx: LayoutContext<'a>,
- layouter: LineLayouter,
- style: LayoutStyle,
- feedback: Feedback,
-}
-
-/// The context for layouting.
-#[derive(Debug, Clone)]
-pub struct LayoutContext<'a> {
- /// The font loader to retrieve fonts from when typesetting text
- /// using [`layout_text`].
- pub loader: &'a SharedFontLoader,
- /// The style for pages and text.
- pub style: &'a LayoutStyle,
- /// The base unpadded dimensions of this container (for relative sizing).
- pub base: Size,
- /// The spaces to layout in.
- pub spaces: LayoutSpaces,
- /// Whether to have repeated spaces or to use only the first and only once.
- pub repeat: bool,
- /// The initial axes along which content is laid out.
- pub axes: LayoutAxes,
- /// The alignment of the finished layout.
- pub align: LayoutAlign,
- /// Whether the layout that is to be created will be nested in a parent
- /// container.
- pub nested: bool,
-}
-
-/// A sequence of layouting commands.
-pub type Commands<'a> = Vec<Command<'a>>;
-
-/// Commands issued to the layouting engine by models.
-#[derive(Debug, Clone)]
-pub enum Command<'a> {
- /// Layout the given model in the current context (i.e. not nested). The
- /// content of the model is not laid out into a separate box and then added,
- /// but simply laid out flat in the active layouting process.
- ///
- /// This has the effect that the content fits nicely into the active line
- /// layouting, enabling functions to e.g. change the style of some piece of
- /// text while keeping it integrated in the current paragraph.
- LayoutSyntaxModel(&'a SyntaxModel),
-
- /// Add a already computed layout.
- Add(Layout),
- /// Add multiple layouts, one after another. This is equivalent to multiple
- /// [Add](Command::Add) commands.
- AddMultiple(MultiLayout),
-
- /// Add spacing of given [kind](super::SpacingKind) along the primary or
- /// secondary axis. The spacing kind defines how the spacing interacts with
- /// surrounding spacing.
- AddSpacing(f64, SpacingKind, GenAxis),
-
- /// Start a new line.
- BreakLine,
- /// Start a new paragraph.
- BreakParagraph,
- /// Start a new page, which will exist in the finished layout even if it
- /// stays empty (since the page break is a _hard_ space break).
- BreakPage,
-
- /// Update the text style.
- SetTextStyle(TextStyle),
- /// Update the page style.
- SetPageStyle(PageStyle),
-
- /// Update the alignment for future boxes added to this layouting process.
- SetAlignment(LayoutAlign),
- /// Update the layouting axes along which future boxes will be laid
- /// out. This finishes the current line.
- SetAxes(LayoutAxes),
-}
-
-/// Layout a syntax model into a list of boxes.
-pub async fn layout(model: &SyntaxModel, ctx: LayoutContext<'_>) -> Pass<MultiLayout> {
- let mut layouter = ModelLayouter::new(ctx);
- layouter.layout_syntax_model(model).await;
- layouter.finish()
-}
-
-/// A dynamic future type which allows recursive invocation of async functions
-/// when used as the return type. This is also how the async trait functions
-/// work internally.
-pub type DynFuture<'a, T> = Pin<Box<dyn Future<Output=T> + 'a>>;
-
-impl<'a> ModelLayouter<'a> {
- /// Create a new model layouter.
- pub fn new(ctx: LayoutContext<'a>) -> ModelLayouter<'a> {
- ModelLayouter {
- layouter: LineLayouter::new(LineContext {
- spaces: ctx.spaces.clone(),
- axes: ctx.axes,
- align: ctx.align,
- repeat: ctx.repeat,
- line_spacing: ctx.style.text.line_spacing(),
- }),
- style: ctx.style.clone(),
- ctx,
- feedback: Feedback::new(),
- }
- }
-
- /// Flatly layout a model into this layouting process.
- pub async fn layout<'r>(
- &'r mut self,
- model: Spanned<&'r dyn Model>
- ) {
- // Execute the model's layout function which generates the commands.
- let layouted = model.v.layout(LayoutContext {
- style: &self.style,
- spaces: self.layouter.remaining(),
- nested: true,
- .. self.ctx
- }).await;
-
- // Add the errors generated by the model to the error list.
- self.feedback.extend_offset(layouted.feedback, model.span.start);
-
- for command in layouted.output {
- self.execute_command(command, model.span).await;
- }
- }
-
- /// Layout a syntax model by directly processing the nodes instead of using
- /// the command based architecture.
- pub async fn layout_syntax_model<'r>(
- &'r mut self,
- model: &'r SyntaxModel
- ) {
- use Node::*;
-
- for Spanned { v: node, span } in &model.nodes {
- let decorate = |this: &mut ModelLayouter, deco| {
- this.feedback.decorations.push(Spanned::new(deco, *span));
- };
-
- match node {
- Space => self.layout_space(),
- Parbreak => self.layout_paragraph(),
- Linebreak => self.layouter.finish_line(),
-
- Text(text) => {
- if self.style.text.italic {
- decorate(self, Decoration::Italic);
- }
-
- if self.style.text.bolder {
- decorate(self, Decoration::Bold);
- }
-
- self.layout_text(text).await;
- }
-
- ToggleItalic => {
- self.style.text.italic = !self.style.text.italic;
- decorate(self, Decoration::Italic);
- }
-
- ToggleBolder => {
- self.style.text.bolder = !self.style.text.bolder;
- decorate(self, Decoration::Bold);
- }
-
- Raw(lines) => {
- // TODO: Make this more efficient.
- let fallback = self.style.text.fallback.clone();
- self.style.text.fallback.list_mut().insert(0, "monospace".to_string());
- self.style.text.fallback.flatten();
-
- // Layout the first line.
- let mut iter = lines.iter();
- if let Some(line) = iter.next() {
- self.layout_text(line).await;
- }
-
- // Put a newline before each following line.
- for line in iter {
- self.layouter.finish_line();
- self.layout_text(line).await;
- }
-
- self.style.text.fallback = fallback;
- }
-
- Model(model) => {
- self.layout(Spanned::new(model.as_ref(), *span)).await;
- }
- }
- }
- }
-
- /// Compute the finished list of boxes.
- pub fn finish(self) -> Pass<MultiLayout> {
- Pass::new(self.layouter.finish(), self.feedback)
- }
-
- /// Execute a command issued by a model. When the command is errorful, the
- /// given span is stored with the error.
- fn execute_command<'r>(
- &'r mut self,
- command: Command<'r>,
- model_span: Span,
- ) -> DynFuture<'r, ()> { Box::pin(async move {
- use Command::*;
-
- match command {
- LayoutSyntaxModel(model) => self.layout_syntax_model(model).await,
-
- Add(layout) => self.layouter.add(layout),
- AddMultiple(layouts) => self.layouter.add_multiple(layouts),
- AddSpacing(space, kind, axis) => match axis {
- Primary => self.layouter.add_primary_spacing(space, kind),
- Secondary => self.layouter.add_secondary_spacing(space, kind),
- }
-
- BreakLine => self.layouter.finish_line(),
- BreakParagraph => self.layout_paragraph(),
- BreakPage => {
- if self.ctx.nested {
- error!(
- @self.feedback, model_span,
- "page break cannot be issued from nested context",
- );
- } else {
- self.layouter.finish_space(true)
- }
- }
-
- SetTextStyle(style) => {
- self.layouter.set_line_spacing(style.line_spacing());
- self.style.text = style;
- }
- SetPageStyle(style) => {
- if self.ctx.nested {
- error!(
- @self.feedback, model_span,
- "page style cannot be changed from nested context",
- );
- } else {
- self.style.page = style;
-
- // The line layouter has no idea of page styles and thus we
- // need to recompute the layouting space resulting of the
- // new page style and update it within the layouter.
- let margins = style.margins();
- self.ctx.base = style.dimensions.unpadded(margins);
- self.layouter.set_spaces(vec![
- LayoutSpace {
- dimensions: style.dimensions,
- padding: margins,
- expansion: LayoutExpansion::new(true, true),
- }
- ], true);
- }
- }
-
- SetAlignment(align) => self.ctx.align = align,
- SetAxes(axes) => {
- self.layouter.set_axes(axes);
- self.ctx.axes = axes;
- }
- }
- }) }
-
- /// Layout a continous piece of text and add it to the line layouter.
- async fn layout_text(&mut self, text: &str) {
- self.layouter.add(layout_text(text, TextContext {
- loader: &self.ctx.loader,
- style: &self.style.text,
- axes: self.ctx.axes,
- align: self.ctx.align,
- }).await)
- }
-
- /// Add the spacing for a syntactic space node.
- fn layout_space(&mut self) {
- self.layouter.add_primary_spacing(
- self.style.text.word_spacing(),
- SpacingKind::WORD,
- );
- }
-
- /// Finish the paragraph and add paragraph spacing.
- fn layout_paragraph(&mut self) {
- self.layouter.add_secondary_spacing(
- self.style.text.paragraph_spacing(),
- SpacingKind::PARAGRAPH,
- );
- }
-}
diff --git a/src/layout/primitive.rs b/src/layout/primitive.rs
new file mode 100644
index 00000000..2eb5669b
--- /dev/null
+++ b/src/layout/primitive.rs
@@ -0,0 +1,350 @@
+//! Layouting primitives.
+
+use std::fmt::{self, Display, Formatter};
+use super::prelude::*;
+
+/// Specifies along which axes content is laid out.
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
+pub struct LayoutAxes {
+ /// The primary layouting direction.
+ pub primary: Dir,
+ /// The secondary layouting direction.
+ pub secondary: Dir,
+}
+
+impl LayoutAxes {
+ /// Create a new instance from the two values.
+ ///
+ /// # Panics
+ /// This function panics if the axes are aligned, that is, they are
+ /// on the same axis.
+ pub fn new(primary: Dir, secondary: Dir) -> LayoutAxes {
+ if primary.axis() == secondary.axis() {
+ panic!("invalid aligned axes {} and {}", primary, secondary);
+ }
+
+ LayoutAxes { primary, secondary }
+ }
+
+ /// Return the direction of the specified generic axis.
+ pub fn get(self, axis: GenAxis) -> Dir {
+ match axis {
+ Primary => self.primary,
+ Secondary => self.secondary,
+ }
+ }
+
+ /// Borrow the direction of the specified generic axis mutably.
+ pub fn get_mut(&mut self, axis: GenAxis) -> &mut Dir {
+ match axis {
+ Primary => &mut self.primary,
+ Secondary => &mut self.secondary,
+ }
+ }
+}
+
+/// Directions along which content is laid out.
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
+pub enum Dir {
+ LTT,
+ RTL,
+ TTB,
+ BTT,
+}
+
+impl Dir {
+ /// The specific axis this direction belongs to.
+ pub fn axis(self) -> SpecAxis {
+ match self {
+ LTT | RTL => Horizontal,
+ TTB | BTT => Vertical,
+ }
+ }
+
+ /// Whether this axis points into the positive coordinate direction.
+ ///
+ /// The positive axes are left-to-right and top-to-bottom.
+ pub fn is_positive(self) -> bool {
+ match self {
+ LTT | TTB => true,
+ RTL | BTT => false,
+ }
+ }
+
+ /// The factor for this direction.
+ ///
+ /// - `1` if the direction is positive.
+ /// - `-1` if the direction is negative.
+ pub fn factor(self) -> f64 {
+ if self.is_positive() { 1.0 } else { -1.0 }
+ }
+
+ /// The inverse axis.
+ pub fn inv(self) -> Dir {
+ match self {
+ LTT => RTL,
+ RTL => LTT,
+ TTB => BTT,
+ BTT => TTB,
+ }
+ }
+}
+
+impl Display for Dir {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ f.pad(match self {
+ LTT => "ltr",
+ RTL => "rtl",
+ TTB => "ttb",
+ BTT => "btt",
+ })
+ }
+}
+
+/// The two generic layouting axes.
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
+pub enum GenAxis {
+ /// The primary axis along which words are laid out.
+ Primary,
+ /// The secondary axis along which lines and paragraphs are laid out.
+ Secondary,
+}
+
+impl GenAxis {
+ /// The specific version of this axis in the given system of axes.
+ pub fn to_specific(self, axes: LayoutAxes) -> SpecAxis {
+ axes.get(self).axis()
+ }
+}
+
+impl Display for GenAxis {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ f.pad(match self {
+ Primary => "primary",
+ Secondary => "secondary",
+ })
+ }
+}
+
+/// The two specific layouting axes.
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
+pub enum SpecAxis {
+ /// The horizontal layouting axis.
+ Horizontal,
+ /// The vertical layouting axis.
+ Vertical,
+}
+
+impl SpecAxis {
+ /// The generic version of this axis in the given system of axes.
+ pub fn to_generic(self, axes: LayoutAxes) -> GenAxis {
+ if self == axes.primary.axis() { Primary } else { Secondary }
+ }
+}
+
+impl Display for SpecAxis {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ f.pad(match self {
+ Horizontal => "horizontal",
+ Vertical => "vertical",
+ })
+ }
+}
+
+/// Specifies where to align a layout in a parent container.
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
+pub struct LayoutAlign {
+ /// The alignment along the primary axis.
+ pub primary: GenAlign,
+ /// The alignment along the secondary axis.
+ pub secondary: GenAlign,
+}
+
+impl LayoutAlign {
+ /// Create a new instance from the two values.
+ pub fn new(primary: GenAlign, secondary: GenAlign) -> LayoutAlign {
+ LayoutAlign { primary, secondary }
+ }
+
+ /// Return the alignment of the specified generic axis.
+ pub fn get(self, axis: GenAxis) -> GenAlign {
+ match axis {
+ Primary => self.primary,
+ Secondary => self.secondary,
+ }
+ }
+
+ /// Borrow the alignment of the specified generic axis mutably.
+ pub fn get_mut(&mut self, axis: GenAxis) -> &mut GenAlign {
+ match axis {
+ Primary => &mut self.primary,
+ Secondary => &mut self.secondary,
+ }
+ }
+}
+
+/// Where to align content along a generic context.
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
+pub enum GenAlign {
+ Start,
+ Center,
+ End,
+}
+
+impl GenAlign {
+ /// The inverse alignment.
+ pub fn inv(self) -> GenAlign {
+ match self {
+ Start => End,
+ Center => Center,
+ End => Start,
+ }
+ }
+}
+
+impl Display for GenAlign {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ f.pad(match self {
+ Start => "start",
+ Center => "center",
+ End => "end",
+ })
+ }
+}
+
+/// Where to align content in a specific context.
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
+pub enum SpecAlign {
+ Left,
+ Right,
+ Top,
+ Bottom,
+ Center,
+}
+
+impl SpecAlign {
+ /// The specific axis this alignment refers to.
+ ///
+ /// Returns `None` if this is center.
+ pub fn axis(self) -> Option<SpecAxis> {
+ match self {
+ Self::Left => Some(Horizontal),
+ Self::Right => Some(Horizontal),
+ Self::Top => Some(Vertical),
+ Self::Bottom => Some(Vertical),
+ Self::Center => None,
+ }
+ }
+
+ /// Convert this to a generic alignment.
+ pub fn to_generic(self, axes: LayoutAxes) -> GenAlign {
+ let get = |spec: SpecAxis, align: GenAlign| {
+ let axis = spec.to_generic(axes);
+ if axes.get(axis).is_positive() { align } else { align.inv() }
+ };
+
+ match self {
+ Self::Left => get(Horizontal, Start),
+ Self::Right => get(Horizontal, End),
+ Self::Top => get(Vertical, Start),
+ Self::Bottom => get(Vertical, End),
+ Self::Center => GenAlign::Center,
+ }
+ }
+}
+
+impl Display for SpecAlign {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ f.pad(match self {
+ Self::Left => "left",
+ Self::Right => "right",
+ Self::Top => "top",
+ Self::Bottom => "bottom",
+ Self::Center => "center",
+ })
+ }
+}
+
+/// Specifies whether to expand a layout to the full size of the space it is
+/// laid out in or to shrink it to fit the content.
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
+pub struct LayoutExpansion {
+ /// Whether to expand on the horizontal axis.
+ pub horizontal: bool,
+ /// Whether to expand on the vertical axis.
+ pub vertical: bool,
+}
+
+impl LayoutExpansion {
+ /// Create a new instance from the two values.
+ pub fn new(horizontal: bool, vertical: bool) -> LayoutExpansion {
+ LayoutExpansion { horizontal, vertical }
+ }
+
+ /// Return the expansion value for the given specific axis.
+ pub fn get(self, axis: SpecAxis) -> bool {
+ match axis {
+ Horizontal => self.horizontal,
+ Vertical => self.vertical,
+ }
+ }
+
+ /// Borrow the expansion value for the given specific axis mutably.
+ pub fn get_mut(&mut self, axis: SpecAxis) -> &mut bool {
+ match axis {
+ Horizontal => &mut self.horizontal,
+ Vertical => &mut self.vertical,
+ }
+ }
+}
+
+/// Defines how a given spacing interacts with (possibly existing) surrounding
+/// spacing.
+///
+/// There are two options for interaction: Hard and soft spacing. Typically,
+/// hard spacing is used when a fixed amount of space needs to be inserted no
+/// matter what. In contrast, soft spacing can be used to insert a default
+/// spacing between e.g. two words or paragraphs that can still be overridden by
+/// a hard space.
+#[derive(Debug, Copy, Clone, Eq, PartialEq)]
+pub enum SpacingKind {
+ /// Hard spaces are always laid out and consume surrounding soft space.
+ Hard,
+ /// Soft spaces are not laid out if they are touching a hard space and
+ /// consume neighbouring soft spaces with higher levels.
+ Soft(u32),
+}
+
+impl SpacingKind {
+ /// The standard spacing kind used for paragraph spacing.
+ pub const PARAGRAPH: SpacingKind = SpacingKind::Soft(1);
+
+ /// The standard spacing kind used for line spacing.
+ pub const LINE: SpacingKind = SpacingKind::Soft(2);
+
+ /// The standard spacing kind used for word spacing.
+ pub const WORD: SpacingKind = SpacingKind::Soft(1);
+}
+
+/// The spacing kind of the most recently inserted item in a layouting process.
+/// This is not about the last _spacing item_, but the last _item_, which is why
+/// this can be `None`.
+#[derive(Debug, Copy, Clone, PartialEq)]
+pub(crate) enum LastSpacing {
+ /// The last item was hard spacing.
+ Hard,
+ /// The last item was soft spacing with the given width and level.
+ Soft(f64, u32),
+ /// The last item was not spacing.
+ None,
+}
+
+impl LastSpacing {
+ /// The width of the soft space if this is a soft space or zero otherwise.
+ pub(crate) fn soft_or_zero(self) -> f64 {
+ match self {
+ LastSpacing::Soft(space, _) => space,
+ _ => 0.0,
+ }
+ }
+}
diff --git a/src/layout/stack.rs b/src/layout/stack.rs
index 4f4d3d8b..28da74b7 100644
--- a/src/layout/stack.rs
+++ b/src/layout/stack.rs
@@ -59,12 +59,12 @@ struct Space {
/// Whether to add the layout for this space even if it would be empty.
hard: bool,
/// The so-far accumulated layouts.
- layouts: Vec<(LayoutAxes, Layout)>,
+ layouts: Vec<(LayoutAxes, BoxLayout)>,
/// The specialized size of this space.
size: Size,
/// The specialized remaining space.
usable: Size,
- /// The specialized extra-needed dimensions to affect the size at all.
+ /// The specialized extra-needed size to affect the size at all.
extra: Size,
/// The rulers of a space dictate which alignments for new boxes are still
/// allowed and which require a new space to be started.
@@ -85,7 +85,7 @@ impl StackLayouter {
}
/// Add a layout to the stack.
- pub fn add(&mut self, layout: Layout) {
+ pub fn add(&mut self, layout: BoxLayout) {
// If the alignment cannot be fitted in this space, finish it.
// TODO: Issue warning for non-fitting alignment in
// non-repeating context.
@@ -101,12 +101,12 @@ impl StackLayouter {
}
// TODO: Issue warning about overflow if there is overflow.
- if !self.space.usable.fits(layout.dimensions) && self.ctx.repeat {
- self.skip_to_fitting_space(layout.dimensions);
+ if !self.space.usable.fits(layout.size) && self.ctx.repeat {
+ self.skip_to_fitting_space(layout.size);
}
// Change the usable space and size of the space.
- self.update_metrics(layout.dimensions.generalized(self.ctx.axes));
+ self.update_metrics(layout.size.generalized(self.ctx.axes));
// Add the box to the vector and remember that spacings are allowed
// again.
@@ -130,11 +130,11 @@ impl StackLayouter {
SpacingKind::Hard => {
// Reduce the spacing such that it definitely fits.
spacing = spacing.min(self.space.usable.secondary(self.ctx.axes));
- let dimensions = Size::with_y(spacing);
+ let size = Size::with_y(spacing);
- self.update_metrics(dimensions);
- self.space.layouts.push((self.ctx.axes, Layout {
- dimensions: dimensions.specialized(self.ctx.axes),
+ self.update_metrics(size);
+ self.space.layouts.push((self.ctx.axes, BoxLayout {
+ size: size.specialized(self.ctx.axes),
align: LayoutAlign::new(Start, Start),
elements: LayoutElements::new(),
}));
@@ -159,22 +159,22 @@ impl StackLayouter {
}
/// Update the size metrics to reflect that a layout or spacing with the
- /// given generalized dimensions has been added.
- fn update_metrics(&mut self, dimensions: Size) {
+ /// given generalized size has been added.
+ fn update_metrics(&mut self, added: Size) {
let axes = self.ctx.axes;
let mut size = self.space.size.generalized(axes);
let mut extra = self.space.extra.generalized(axes);
- size.x += (dimensions.x - extra.x).max(0.0);
- size.y += (dimensions.y - extra.y).max(0.0);
+ size.x += (added.x - extra.x).max(0.0);
+ size.y += (added.y - extra.y).max(0.0);
- extra.x = extra.x.max(dimensions.x);
- extra.y = (extra.y - dimensions.y).max(0.0);
+ extra.x = extra.x.max(added.x);
+ extra.y = (extra.y - added.y).max(0.0);
self.space.size = size.specialized(axes);
self.space.extra = extra.specialized(axes);
- *self.space.usable.secondary_mut(axes) -= dimensions.y;
+ *self.space.usable.secondary_mut(axes) -= added.y;
}
/// Update the rulers to account for the new layout. Returns true if a
@@ -226,12 +226,12 @@ impl StackLayouter {
}
}
- /// Move to the first space that can fit the given dimensions or do nothing
+ /// Move to the first space that can fit the given size or do nothing
/// if no space is capable of that.
- pub fn skip_to_fitting_space(&mut self, dimensions: Size) {
+ pub fn skip_to_fitting_space(&mut self, size: Size) {
let start = self.next_space();
for (index, space) in self.ctx.spaces[start..].iter().enumerate() {
- if space.usable().fits(dimensions) {
+ if space.usable().fits(size) {
self.finish_space(true);
self.start_space(start + index, true);
return;
@@ -242,10 +242,10 @@ impl StackLayouter {
/// The remaining unpadded, unexpanding spaces. If a function is laid out
/// into these spaces, it will fit into this stack.
pub fn remaining(&self) -> LayoutSpaces {
- let dimensions = self.usable();
+ let size = self.usable();
let mut spaces = vec![LayoutSpace {
- dimensions,
+ size,
padding: Margins::ZERO,
expansion: LayoutExpansion::new(false, false),
}];
@@ -287,7 +287,7 @@ impl StackLayouter {
let space = self.ctx.spaces[self.space.index];
// ------------------------------------------------------------------ //
- // Step 1: Determine the full dimensions of the space.
+ // Step 1: Determine the full size of the space.
// (Mostly done already while collecting the boxes, but here we
// expand if necessary.)
@@ -295,7 +295,7 @@ impl StackLayouter {
if space.expansion.horizontal { self.space.size.x = usable.x; }
if space.expansion.vertical { self.space.size.y = usable.y; }
- let dimensions = self.space.size.padded(space.padding);
+ let size = self.space.size.padded(space.padding);
// ------------------------------------------------------------------ //
// Step 2: Forward pass. Create a bounding box for each layout in which
@@ -323,7 +323,7 @@ impl StackLayouter {
// the usable space for following layouts at it's origin by its
// extent along the secondary axis.
*bound.get_mut(axes.secondary, Start)
- += axes.secondary.factor() * layout.dimensions.secondary(*axes);
+ += axes.secondary.factor() * layout.size.secondary(*axes);
}
// ------------------------------------------------------------------ //
@@ -355,7 +355,7 @@ impl StackLayouter {
-= axes.secondary.factor() * extent.y;
// Then, we add this layout's secondary extent to the accumulator.
- let size = layout.dimensions.generalized(*axes);
+ let size = layout.size.generalized(*axes);
extent.x = extent.x.max(size.x);
extent.y += size.y;
}
@@ -368,7 +368,7 @@ impl StackLayouter {
let layouts = std::mem::take(&mut self.space.layouts);
for ((axes, layout), bound) in layouts.into_iter().zip(bounds) {
- let size = layout.dimensions.specialized(axes);
+ let size = layout.size.specialized(axes);
let align = layout.align;
// The space in which this layout is aligned is given by the
@@ -383,8 +383,8 @@ impl StackLayouter {
elements.extend_offset(pos, layout.elements);
}
- self.layouts.push(Layout {
- dimensions,
+ self.layouts.push(BoxLayout {
+ size,
align: self.ctx.align,
elements,
});
diff --git a/src/layout/text.rs b/src/layout/text.rs
index 477099e2..5c18cd32 100644
--- a/src/layout/text.rs
+++ b/src/layout/text.rs
@@ -40,7 +40,7 @@ pub struct TextContext<'a> {
}
/// Layouts text into a box.
-pub async fn layout_text(text: &str, ctx: TextContext<'_>) -> Layout {
+pub async fn layout_text(text: &str, ctx: TextContext<'_>) -> BoxLayout {
TextLayouter::new(text, ctx).layout().await
}
@@ -58,7 +58,7 @@ impl<'a> TextLayouter<'a> {
}
/// Do the layouting.
- async fn layout(mut self) -> Layout {
+ async fn layout(mut self) -> BoxLayout {
// If the primary axis is negative, we layout the characters reversed.
if self.ctx.axes.primary.is_positive() {
for c in self.text.chars() {
@@ -76,8 +76,8 @@ impl<'a> TextLayouter<'a> {
self.elements.push(pos, LayoutElement::Text(self.shaped));
}
- Layout {
- dimensions: Size::new(self.width, self.ctx.style.font_size()),
+ BoxLayout {
+ size: Size::new(self.width, self.ctx.style.font_size()),
align: self.ctx.align,
elements: self.elements,
}
diff --git a/src/layout/tree.rs b/src/layout/tree.rs
new file mode 100644
index 00000000..44c59211
--- /dev/null
+++ b/src/layout/tree.rs
@@ -0,0 +1,223 @@
+//! The tree layouter layouts trees (i.e.
+//! [syntax trees](crate::syntax::SyntaxTree) and [functions](crate::func))
+//! by executing commands issued by the trees.
+
+use crate::{Pass, Feedback, DynFuture};
+use crate::style::LayoutStyle;
+use crate::syntax::decoration::Decoration;
+use crate::syntax::tree::{SyntaxTree, SyntaxNode, DynamicNode};
+use crate::syntax::span::{Span, Spanned};
+use super::line::{LineLayouter, LineContext};
+use super::text::{layout_text, TextContext};
+use super::*;
+
+/// Performs the tree layouting.
+#[derive(Debug)]
+pub struct TreeLayouter<'a> {
+ ctx: LayoutContext<'a>,
+ layouter: LineLayouter,
+ style: LayoutStyle,
+ feedback: Feedback,
+}
+
+impl<'a> TreeLayouter<'a> {
+ /// Create a new tree layouter.
+ pub fn new(ctx: LayoutContext<'a>) -> TreeLayouter<'a> {
+ TreeLayouter {
+ layouter: LineLayouter::new(LineContext {
+ spaces: ctx.spaces.clone(),
+ axes: ctx.axes,
+ align: ctx.align,
+ repeat: ctx.repeat,
+ line_spacing: ctx.style.text.line_spacing(),
+ }),
+ style: ctx.style.clone(),
+ ctx,
+ feedback: Feedback::new(),
+ }
+ }
+
+ /// Layout a syntax tree by directly processing the nodes instead of using
+ /// the command based architecture.
+ pub async fn layout_tree(&mut self, tree: &SyntaxTree) {
+ for node in tree {
+ self.layout_node(node).await;
+ }
+ }
+
+ pub async fn layout_node(&mut self, node: &Spanned<SyntaxNode>) {
+ let decorate = |this: &mut TreeLayouter, deco| {
+ this.feedback.decorations.push(Spanned::new(deco, node.span));
+ };
+
+ match &node.v {
+ SyntaxNode::Space => self.layout_space(),
+ SyntaxNode::Parbreak => self.layout_paragraph(),
+ SyntaxNode::Linebreak => self.layouter.finish_line(),
+
+ SyntaxNode::Text(text) => {
+ if self.style.text.italic {
+ decorate(self, Decoration::Italic);
+ }
+
+ if self.style.text.bolder {
+ decorate(self, Decoration::Bold);
+ }
+
+ self.layout_text(text).await;
+ }
+
+ SyntaxNode::ToggleItalic => {
+ self.style.text.italic = !self.style.text.italic;
+ decorate(self, Decoration::Italic);
+ }
+
+ SyntaxNode::ToggleBolder => {
+ self.style.text.bolder = !self.style.text.bolder;
+ decorate(self, Decoration::Bold);
+ }
+
+ SyntaxNode::Raw(lines) => {
+ // TODO: Make this more efficient.
+ let fallback = self.style.text.fallback.clone();
+ self.style.text.fallback.list_mut().insert(0, "monospace".to_string());
+ self.style.text.fallback.flatten();
+
+ // Layout the first line.
+ let mut iter = lines.iter();
+ if let Some(line) = iter.next() {
+ self.layout_text(line).await;
+ }
+
+ // Put a newline before each following line.
+ for line in iter {
+ self.layouter.finish_line();
+ self.layout_text(line).await;
+ }
+
+ self.style.text.fallback = fallback;
+ }
+
+ SyntaxNode::Dyn(dynamic) => {
+ self.layout_dyn(Spanned::new(dynamic.as_ref(), node.span)).await;
+ }
+ }
+ }
+
+ /// Layout a node into this layouting process.
+ pub async fn layout_dyn(&mut self, dynamic: Spanned<&dyn DynamicNode>) {
+ // Execute the tree's layout function which generates the commands.
+ let layouted = dynamic.v.layout(LayoutContext {
+ style: &self.style,
+ spaces: self.layouter.remaining(),
+ nested: true,
+ .. self.ctx
+ }).await;
+
+ // Add the errors generated by the tree to the error list.
+ self.feedback.extend_offset(layouted.feedback, dynamic.span.start);
+
+ for command in layouted.output {
+ self.execute_command(command, dynamic.span).await;
+ }
+ }
+
+ /// Compute the finished list of boxes.
+ pub fn finish(self) -> Pass<MultiLayout> {
+ Pass::new(self.layouter.finish(), self.feedback)
+ }
+
+ /// Execute a command issued by a tree. When the command is errorful, the
+ /// given span is stored with the error.
+ fn execute_command<'r>(
+ &'r mut self,
+ command: Command<'r>,
+ tree_span: Span,
+ ) -> DynFuture<'r, ()> { Box::pin(async move {
+ use Command::*;
+
+ match command {
+ LayoutSyntaxTree(tree) => self.layout_tree(tree).await,
+
+ Add(layout) => self.layouter.add(layout),
+ AddMultiple(layouts) => self.layouter.add_multiple(layouts),
+ AddSpacing(space, kind, axis) => match axis {
+ Primary => self.layouter.add_primary_spacing(space, kind),
+ Secondary => self.layouter.add_secondary_spacing(space, kind),
+ }
+
+ BreakLine => self.layouter.finish_line(),
+ BreakParagraph => self.layout_paragraph(),
+ BreakPage => {
+ if self.ctx.nested {
+ error!(
+ @self.feedback, tree_span,
+ "page break cannot be issued from nested context",
+ );
+ } else {
+ self.layouter.finish_space(true)
+ }
+ }
+
+ SetTextStyle(style) => {
+ self.layouter.set_line_spacing(style.line_spacing());
+ self.style.text = style;
+ }
+ SetPageStyle(style) => {
+ if self.ctx.nested {
+ error!(
+ @self.feedback, tree_span,
+ "page style cannot be changed from nested context",
+ );
+ } else {
+ self.style.page = style;
+
+ // The line layouter has no idea of page styles and thus we
+ // need to recompute the layouting space resulting of the
+ // new page style and update it within the layouter.
+ let margins = style.margins();
+ self.ctx.base = style.size.unpadded(margins);
+ self.layouter.set_spaces(vec![
+ LayoutSpace {
+ size: style.size,
+ padding: margins,
+ expansion: LayoutExpansion::new(true, true),
+ }
+ ], true);
+ }
+ }
+
+ SetAlignment(align) => self.ctx.align = align,
+ SetAxes(axes) => {
+ self.layouter.set_axes(axes);
+ self.ctx.axes = axes;
+ }
+ }
+ }) }
+
+ /// Layout a continous piece of text and add it to the line layouter.
+ async fn layout_text(&mut self, text: &str) {
+ self.layouter.add(layout_text(text, TextContext {
+ loader: &self.ctx.loader,
+ style: &self.style.text,
+ axes: self.ctx.axes,
+ align: self.ctx.align,
+ }).await)
+ }
+
+ /// Add the spacing for a syntactic space node.
+ fn layout_space(&mut self) {
+ self.layouter.add_primary_spacing(
+ self.style.text.word_spacing(),
+ SpacingKind::WORD,
+ );
+ }
+
+ /// Finish the paragraph and add paragraph spacing.
+ fn layout_paragraph(&mut self) {
+ self.layouter.add_secondary_spacing(
+ self.style.text.paragraph_spacing(),
+ SpacingKind::PARAGRAPH,
+ );
+ }
+}