Refactor alignments & directions 📐

- Adds lang function
- Refactors execution context
- Adds StackChild and ParChild enums
This commit is contained in:
Laurenz 2021-03-25 21:32:33 +01:00
parent e8057a5385
commit 76fc4cca62
35 changed files with 539 additions and 707 deletions

View File

@ -39,7 +39,6 @@ pub fn eval(env: &mut Env, tree: &Tree, scope: &Scope) -> Pass<NodeMap> {
pub type NodeMap = HashMap<*const Node, Value>; pub type NodeMap = HashMap<*const Node, Value>;
/// The context for evaluation. /// The context for evaluation.
#[derive(Debug)]
pub struct EvalContext<'a> { pub struct EvalContext<'a> {
/// The environment from which resources are gathered. /// The environment from which resources are gathered.
pub env: &'a mut Env, pub env: &'a mut Env,

View File

@ -4,15 +4,14 @@ use super::{Exec, FontFamily, State};
use crate::diag::{Diag, DiagSet, Pass}; use crate::diag::{Diag, DiagSet, Pass};
use crate::env::Env; use crate::env::Env;
use crate::eval::TemplateValue; use crate::eval::TemplateValue;
use crate::geom::{Dir, Gen, Linear, Sides, Size}; use crate::geom::{Align, Dir, Gen, GenAxis, Length, Linear, Sides, Size};
use crate::layout::{ use crate::layout::{
Node, PadNode, PageRun, ParNode, SpacingNode, StackNode, TextNode, Tree, AnyNode, PadNode, PageRun, ParChild, ParNode, StackChild, StackNode, TextNode, Tree,
}; };
use crate::parse::{is_newline, Scanner}; use crate::parse::{is_newline, Scanner};
use crate::syntax::{Span, Spanned}; use crate::syntax::Span;
/// The context for execution. /// The context for execution.
#[derive(Debug)]
pub struct ExecContext<'a> { pub struct ExecContext<'a> {
/// The environment from which resources are gathered. /// The environment from which resources are gathered.
pub env: &'a mut Env, pub env: &'a mut Env,
@ -22,13 +21,11 @@ pub struct ExecContext<'a> {
pub diags: DiagSet, pub diags: DiagSet,
/// The tree of finished page runs. /// The tree of finished page runs.
tree: Tree, tree: Tree,
/// Metrics of the active page. /// When we are building the top-level stack, this contains metrics of the
page: Option<PageInfo>, /// page. While building a group stack through `exec_group`, this is `None`.
/// The content of the active stack. This may be the top-level stack for the page: Option<PageBuilder>,
/// page or a lower one created by [`exec`](Self::exec). /// The currently built stack of paragraphs.
stack: StackNode, stack: StackBuilder,
/// The content of the active paragraph.
par: ParNode,
} }
impl<'a> ExecContext<'a> { impl<'a> ExecContext<'a> {
@ -38,9 +35,8 @@ impl<'a> ExecContext<'a> {
env, env,
diags: DiagSet::new(), diags: DiagSet::new(),
tree: Tree { runs: vec![] }, tree: Tree { runs: vec![] },
page: Some(PageInfo::new(&state, true)), page: Some(PageBuilder::new(&state, true)),
stack: StackNode::new(&state), stack: StackBuilder::new(&state),
par: ParNode::new(&state),
state, state,
} }
} }
@ -50,45 +46,23 @@ impl<'a> ExecContext<'a> {
self.diags.insert(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. /// Set the font to monospace.
pub fn set_monospace(&mut self) { pub fn set_monospace(&mut self) {
let families = self.state.font.families_mut(); let families = self.state.font.families_mut();
families.list.insert(0, FontFamily::Monospace); families.list.insert(0, FontFamily::Monospace);
} }
/// Push a layout node into the active paragraph. /// Execute a template and return the result as a stack node.
/// pub fn exec_group(&mut self, template: &TemplateValue) -> StackNode {
/// Spacing nodes will be handled according to their let snapshot = self.state.clone();
/// [`softness`](SpacingNode::softness). let page = self.page.take();
pub fn push(&mut self, node: impl Into<Node>) { let stack = mem::replace(&mut self.stack, StackBuilder::new(&self.state));
push(&mut self.par.children, node.into());
}
/// Push a word space into the active paragraph. template.exec(self);
pub fn push_space(&mut self) {
let em = self.state.font.resolve_size(); self.state = snapshot;
self.push(SpacingNode { self.page = page;
amount: self.state.par.word_spacing.resolve(em), mem::replace(&mut self.stack, stack).build()
softness: 1,
});
} }
/// Push text into the active paragraph. /// Push text into the active paragraph.
@ -97,96 +71,85 @@ impl<'a> ExecContext<'a> {
pub fn push_text(&mut self, text: &str) { pub fn push_text(&mut self, text: &str) {
let mut scanner = Scanner::new(text); let mut scanner = Scanner::new(text);
let mut line = String::new(); let mut line = String::new();
let push = |this: &mut Self, text| {
let props = this.state.font.resolve_props();
let node = TextNode { text, props };
let align = this.state.aligns.cross;
this.stack.par.folder.push(ParChild::Text(node, align))
};
while let Some(c) = scanner.eat_merging_crlf() { while let Some(c) = scanner.eat_merging_crlf() {
if is_newline(c) { if is_newline(c) {
self.push(TextNode::new(mem::take(&mut line), &self.state)); push(self, mem::take(&mut line));
self.push_linebreak(); self.push_linebreak();
} else { } else {
line.push(c); line.push(c);
} }
} }
self.push(TextNode::new(line, &self.state)); push(self, line);
}
/// Push a word space.
pub fn push_word_space(&mut self) {
let em = self.state.font.resolve_size();
let amount = self.state.par.word_spacing.resolve(em);
self.push_spacing(GenAxis::Cross, amount, 1);
} }
/// Apply a forced line break. /// Apply a forced line break.
pub fn push_linebreak(&mut self) { pub fn push_linebreak(&mut self) {
let em = self.state.font.resolve_size(); let em = self.state.font.resolve_size();
self.push_into_stack(SpacingNode { let amount = self.state.par.leading.resolve(em);
amount: self.state.par.leading.resolve(em), self.push_spacing(GenAxis::Main, amount, 2);
softness: 2,
});
} }
/// Apply a forced paragraph break. /// Apply a forced paragraph break.
pub fn push_parbreak(&mut self) { pub fn push_parbreak(&mut self) {
let em = self.state.font.resolve_size(); let em = self.state.font.resolve_size();
self.push_into_stack(SpacingNode { let amount = self.state.par.spacing.resolve(em);
amount: self.state.par.spacing.resolve(em), self.push_spacing(GenAxis::Main, amount, 1);
softness: 1,
});
} }
/// Push a node directly into the stack above the paragraph. This finishes /// Push spacing into paragraph or stack depending on `axis`.
/// the active paragraph and starts a new one. ///
pub fn push_into_stack(&mut self, node: impl Into<Node>) { /// The `softness` configures how the spacing interacts with surrounding
self.finish_par(); /// spacing.
push(&mut self.stack.children, node.into()); pub fn push_spacing(&mut self, axis: GenAxis, amount: Length, softness: u8) {
match axis {
GenAxis::Main => {
let spacing = StackChild::Spacing(amount);
self.stack.finish_par(&self.state);
self.stack.folder.push_soft(spacing, softness);
} }
GenAxis::Cross => {
/// Execute a template and return the result as a stack node. let spacing = ParChild::Spacing(amount);
pub fn exec(&mut self, template: &TemplateValue) -> StackNode { self.stack.par.folder.push_soft(spacing, softness);
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
} }
/// 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. /// Push any node into the active paragraph.
fn finish_stack(&mut self) -> StackNode { pub fn push_into_par(&mut self, node: impl Into<AnyNode>) {
self.finish_par(); let align = self.state.aligns.cross;
self.stack.par.folder.push(ParChild::Any(node.into(), align));
}
let mut stack = mem::replace(&mut self.stack, StackNode::new(&self.state)); /// Push any node directly into the stack of paragraphs.
trim(&mut stack.children); ///
/// This finishes the active paragraph and starts a new one.
stack pub fn push_into_stack(&mut self, node: impl Into<AnyNode>) {
let aligns = self.state.aligns;
self.stack.finish_par(&self.state);
self.stack.folder.push(StackChild::Any(node.into(), aligns));
} }
/// Finish the active page. /// Finish the active page.
pub fn finish_page(&mut self, keep: bool, hard: bool, source: Span) { pub fn finish_page(&mut self, keep: bool, hard: bool, source: Span) {
if let Some(info) = &mut self.page { if let Some(builder) = &mut self.page {
let info = mem::replace(info, PageInfo::new(&self.state, hard)); let page = mem::replace(builder, PageBuilder::new(&self.state, hard));
let stack = self.finish_stack(); let stack = mem::replace(&mut self.stack, StackBuilder::new(&self.state));
self.tree.runs.extend(page.build(stack.build(), keep));
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 { } else {
self.diag(error!(source, "cannot modify page from here")); self.diag(error!(source, "cannot modify page from here"));
} }
@ -200,44 +163,13 @@ impl<'a> ExecContext<'a> {
} }
} }
/// Push a node into a list, taking care of spacing softness. struct PageBuilder {
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, size: Size,
padding: Sides<Linear>, padding: Sides<Linear>,
hard: bool, hard: bool,
} }
impl PageInfo { impl PageBuilder {
fn new(state: &State, hard: bool) -> Self { fn new(state: &State, hard: bool) -> Self {
Self { Self {
size: state.page.size, size: state.page.size,
@ -245,37 +177,119 @@ impl PageInfo {
hard, hard,
} }
} }
fn build(self, child: StackNode, keep: bool) -> Option<PageRun> {
let Self { size, padding, hard } = self;
(!child.children.is_empty() || (keep && hard)).then(|| PageRun {
size,
child: PadNode { padding, child: child.into() }.into(),
})
}
} }
impl StackNode { struct StackBuilder {
dirs: Gen<Dir>,
folder: SoftFolder<StackChild>,
par: ParBuilder,
}
impl StackBuilder {
fn new(state: &State) -> Self { fn new(state: &State) -> Self {
Self { Self {
dirs: state.dirs, dirs: Gen::new(Dir::TTB, state.lang.dir),
aligns: state.aligns, folder: SoftFolder::new(),
children: vec![], par: ParBuilder::new(state),
} }
} }
fn finish_par(&mut self, state: &State) {
let par = mem::replace(&mut self.par, ParBuilder::new(state));
self.folder.extend(par.build());
}
fn build(self) -> StackNode {
let Self { dirs, mut folder, par } = self;
folder.extend(par.build());
StackNode { dirs, children: folder.finish() }
}
} }
impl ParNode { struct ParBuilder {
aligns: Gen<Align>,
dir: Dir,
line_spacing: Length,
folder: SoftFolder<ParChild>,
}
impl ParBuilder {
fn new(state: &State) -> Self { fn new(state: &State) -> Self {
let em = state.font.resolve_size(); let em = state.font.resolve_size();
Self { Self {
dirs: state.dirs,
aligns: state.aligns, aligns: state.aligns,
dir: state.lang.dir,
line_spacing: state.par.leading.resolve(em), line_spacing: state.par.leading.resolve(em),
children: vec![], folder: SoftFolder::new(),
} }
} }
fn build(self) -> Option<StackChild> {
let Self { aligns, dir, line_spacing, folder } = self;
let children = folder.finish();
(!children.is_empty()).then(|| {
let node = ParNode { dir, line_spacing, children };
StackChild::Any(node.into(), aligns)
})
}
} }
impl TextNode { /// This is used to remove leading and trailing word/line/paragraph spacing
fn new(text: String, state: &State) -> Self { /// as well as collapse sequences of spacings into just one.
Self { struct SoftFolder<N> {
text, nodes: Vec<N>,
dir: state.dirs.cross, last: Last<N>,
aligns: state.aligns, }
props: state.font.resolve_props(),
enum Last<N> {
None,
Hard,
Soft(N, u8),
}
impl<N> SoftFolder<N> {
fn new() -> Self {
Self { nodes: vec![], last: Last::Hard }
}
fn push(&mut self, node: N) {
let last = mem::replace(&mut self.last, Last::None);
if let Last::Soft(soft, _) = last {
self.nodes.push(soft);
}
self.nodes.push(node);
}
fn push_soft(&mut self, node: N, softness: u8) {
if softness == 0 {
self.last = Last::Hard;
self.nodes.push(node);
} else {
match self.last {
Last::Hard => {}
Last::Soft(_, other) if softness >= other => {}
_ => self.last = Last::Soft(node, softness),
}
}
}
fn finish(self) -> Vec<N> {
self.nodes
}
}
impl<N> Extend<N> for SoftFolder<N> {
fn extend<T: IntoIterator<Item = N>>(&mut self, iter: T) {
for elem in iter {
self.push(elem);
} }
} }
} }

View File

@ -65,7 +65,7 @@ impl ExecWithMap for Node {
fn exec_with_map(&self, ctx: &mut ExecContext, map: &NodeMap) { fn exec_with_map(&self, ctx: &mut ExecContext, map: &NodeMap) {
match self { match self {
Node::Text(text) => ctx.push_text(text), Node::Text(text) => ctx.push_text(text),
Node::Space => ctx.push_space(), Node::Space => ctx.push_word_space(),
_ => map[&(self as *const _)].exec(ctx), _ => map[&(self as *const _)].exec(ctx),
} }
} }

View File

@ -12,30 +12,43 @@ use crate::paper::{Paper, PaperClass, PAPER_A4};
/// The evaluation state. /// The evaluation state.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct State { pub struct State {
/// The current directions along which layouts are placed in their parents. /// The current language-related settings.
pub dirs: LayoutDirs, pub lang: LangState,
/// The current alignments of layouts in their parents.
pub aligns: LayoutAligns,
/// The current page settings. /// The current page settings.
pub page: PageState, pub page: PageState,
/// The current paragraph settings. /// The current paragraph settings.
pub par: ParState, pub par: ParState,
/// The current font settings. /// The current font settings.
pub font: FontState, pub font: FontState,
/// The current alignments of layouts in their parents.
pub aligns: Gen<Align>,
} }
impl Default for State { impl Default for State {
fn default() -> Self { fn default() -> Self {
Self { Self {
dirs: LayoutDirs::new(Dir::TTB, Dir::LTR), lang: LangState::default(),
aligns: LayoutAligns::new(Align::Start, Align::Start),
page: PageState::default(), page: PageState::default(),
par: ParState::default(), par: ParState::default(),
font: FontState::default(), font: FontState::default(),
aligns: Gen::new(Align::Start, Align::Start),
} }
} }
} }
/// Defines language properties.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct LangState {
/// The direction for text and other inline objects.
pub dir: Dir,
}
impl Default for LangState {
fn default() -> Self {
Self { dir: Dir::LTR }
}
}
/// Defines page properties. /// Defines page properties.
#[derive(Debug, Copy, Clone, PartialEq)] #[derive(Debug, Copy, Clone, PartialEq)]
pub struct PageState { pub struct PageState {

View File

@ -1,8 +1,5 @@
use super::*; use super::*;
/// The alignments of a layout in its parent.
pub type LayoutAligns = Gen<Align>;
/// Where to align something along a directed axis. /// Where to align something along a directed axis.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum Align { pub enum Align {

View File

@ -1,8 +1,5 @@
use super::*; use super::*;
/// The directions along which layouts are placed in their parent.
pub type LayoutDirs = Gen<Dir>;
/// The four directions into which content can be laid out. /// The four directions into which content can be laid out.
#[derive(Debug, Copy, Clone, Eq, PartialEq)] #[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Dir { pub enum Dir {

View File

@ -50,8 +50,8 @@ impl<T> Get<GenAxis> for Gen<T> {
impl<T> Switch for Gen<T> { impl<T> Switch for Gen<T> {
type Other = Spec<T>; type Other = Spec<T>;
fn switch(self, dirs: LayoutDirs) -> Self::Other { fn switch(self, main: SpecAxis) -> Self::Other {
match dirs.main.axis() { match main {
SpecAxis::Horizontal => Spec::new(self.main, self.cross), SpecAxis::Horizontal => Spec::new(self.main, self.cross),
SpecAxis::Vertical => Spec::new(self.cross, self.main), SpecAxis::Vertical => Spec::new(self.cross, self.main),
} }
@ -86,10 +86,10 @@ impl GenAxis {
impl Switch for GenAxis { impl Switch for GenAxis {
type Other = SpecAxis; type Other = SpecAxis;
fn switch(self, dirs: LayoutDirs) -> Self::Other { fn switch(self, main: SpecAxis) -> Self::Other {
match self { match self {
Self::Main => dirs.main.axis(), Self::Main => main,
Self::Cross => dirs.cross.axis(), Self::Cross => main.other(),
} }
} }
} }

View File

@ -53,7 +53,6 @@ pub trait Switch {
/// The type of the other version. /// The type of the other version.
type Other; type Other;
/// The other version of this type based on the current layouting /// The other version of this type based on the current main axis.
/// directions. fn switch(self, main: SpecAxis) -> Self::Other;
fn switch(self, dirs: LayoutDirs) -> Self::Other;
} }

View File

@ -45,8 +45,8 @@ impl Get<SpecAxis> for Point {
impl Switch for Point { impl Switch for Point {
type Other = Gen<Length>; type Other = Gen<Length>;
fn switch(self, dirs: LayoutDirs) -> Self::Other { fn switch(self, main: SpecAxis) -> Self::Other {
match dirs.main.axis() { match main {
SpecAxis::Horizontal => Gen::new(self.x, self.y), SpecAxis::Horizontal => Gen::new(self.x, self.y),
SpecAxis::Vertical => Gen::new(self.y, self.x), SpecAxis::Vertical => Gen::new(self.y, self.x),
} }

View File

@ -74,8 +74,8 @@ impl Get<SpecAxis> for Size {
impl Switch for Size { impl Switch for Size {
type Other = Gen<Length>; type Other = Gen<Length>;
fn switch(self, dirs: LayoutDirs) -> Self::Other { fn switch(self, main: SpecAxis) -> Self::Other {
match dirs.main.axis() { match main {
SpecAxis::Horizontal => Gen::new(self.width, self.height), SpecAxis::Horizontal => Gen::new(self.width, self.height),
SpecAxis::Vertical => Gen::new(self.height, self.width), SpecAxis::Vertical => Gen::new(self.height, self.width),
} }

View File

@ -66,8 +66,8 @@ impl<T> Get<SpecAxis> for Spec<T> {
impl<T> Switch for Spec<T> { impl<T> Switch for Spec<T> {
type Other = Gen<T>; type Other = Gen<T>;
fn switch(self, dirs: LayoutDirs) -> Self::Other { fn switch(self, main: SpecAxis) -> Self::Other {
match dirs.main.axis() { match main {
SpecAxis::Horizontal => Gen::new(self.horizontal, self.vertical), SpecAxis::Horizontal => Gen::new(self.horizontal, self.vertical),
SpecAxis::Vertical => Gen::new(self.vertical, self.horizontal), SpecAxis::Vertical => Gen::new(self.vertical, self.horizontal),
} }
@ -102,13 +102,8 @@ impl SpecAxis {
impl Switch for SpecAxis { impl Switch for SpecAxis {
type Other = GenAxis; type Other = GenAxis;
fn switch(self, dirs: LayoutDirs) -> Self::Other { fn switch(self, main: SpecAxis) -> Self::Other {
if self == dirs.main.axis() { if self == main { GenAxis::Main } else { GenAxis::Cross }
GenAxis::Main
} else {
debug_assert_eq!(self, dirs.cross.axis());
GenAxis::Cross
}
} }
} }

View File

@ -8,7 +8,7 @@ pub struct BackgroundNode {
/// The background fill. /// The background fill.
pub fill: Fill, pub fill: Fill,
/// The child node to be filled. /// The child node to be filled.
pub child: Node, pub child: AnyNode,
} }
/// The kind of shape to use as a background. /// The kind of shape to use as a background.
@ -19,10 +19,10 @@ pub enum BackgroundShape {
} }
impl Layout for BackgroundNode { impl Layout for BackgroundNode {
fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Fragment { fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Vec<Frame> {
let mut fragment = self.child.layout(ctx, areas); let mut frames = self.child.layout(ctx, areas);
for frame in fragment.frames_mut() { for frame in &mut frames {
let (point, shape) = match self.shape { let (point, shape) = match self.shape {
BackgroundShape::Rect => (Point::ZERO, Shape::Rect(frame.size)), BackgroundShape::Rect => (Point::ZERO, Shape::Rect(frame.size)),
BackgroundShape::Ellipse => { BackgroundShape::Ellipse => {
@ -34,7 +34,7 @@ impl Layout for BackgroundNode {
frame.elements.insert(0, (point, element)); frame.elements.insert(0, (point, element));
} }
fragment frames
} }
} }

View File

@ -12,11 +12,11 @@ pub struct FixedNode {
/// The resulting frame will satisfy `width = aspect * height`. /// The resulting frame will satisfy `width = aspect * height`.
pub aspect: Option<f64>, pub aspect: Option<f64>,
/// The child node whose size to fix. /// The child node whose size to fix.
pub child: Node, pub child: AnyNode,
} }
impl Layout for FixedNode { impl Layout for FixedNode {
fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Fragment { fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Vec<Frame> {
let Areas { current, full, .. } = areas; let Areas { current, full, .. } = areas;
let full = Size::new( let full = Size::new(

View File

@ -3,24 +3,21 @@
mod background; mod background;
mod fixed; mod fixed;
mod frame; mod frame;
mod node;
mod pad; mod pad;
mod par; mod par;
mod shaping; mod shaping;
mod spacing;
mod stack; mod stack;
mod text;
pub use background::*; pub use background::*;
pub use fixed::*; pub use fixed::*;
pub use frame::*; pub use frame::*;
pub use node::*;
pub use pad::*; pub use pad::*;
pub use par::*; pub use par::*;
pub use shaping::*; pub use shaping::*;
pub use spacing::*;
pub use stack::*; pub use stack::*;
pub use text::*;
use std::any::Any;
use std::fmt::{self, Debug, Formatter};
use crate::env::Env; use crate::env::Env;
use crate::geom::*; use crate::geom::*;
@ -51,25 +48,88 @@ pub struct PageRun {
pub size: Size, pub size: Size,
/// The layout node that produces the actual pages (typically a /// The layout node that produces the actual pages (typically a
/// [`StackNode`]). /// [`StackNode`]).
pub child: Node, pub child: AnyNode,
} }
impl PageRun { impl PageRun {
/// Layout the page run. /// Layout the page run.
pub fn layout(&self, ctx: &mut LayoutContext) -> Vec<Frame> { pub fn layout(&self, ctx: &mut LayoutContext) -> Vec<Frame> {
let areas = Areas::repeat(self.size, Spec::uniform(Expand::Fill)); let areas = Areas::repeat(self.size, Spec::uniform(Expand::Fill));
self.child.layout(ctx, &areas).into_frames() self.child.layout(ctx, &areas)
}
}
/// A wrapper around a dynamic layouting node.
pub struct AnyNode(Box<dyn Bounds>);
impl AnyNode {
/// Create a new instance from any node that satisifies the required bounds.
pub fn new<T>(any: T) -> Self
where
T: Layout + Debug + Clone + PartialEq + 'static,
{
Self(Box::new(any))
}
}
impl Layout for AnyNode {
fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Vec<Frame> {
self.0.layout(ctx, areas)
}
}
impl Clone for AnyNode {
fn clone(&self) -> Self {
Self(self.0.dyn_clone())
}
}
impl PartialEq for AnyNode {
fn eq(&self, other: &Self) -> bool {
self.0.dyn_eq(other.0.as_ref())
}
}
impl Debug for AnyNode {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
trait Bounds: Layout + Debug + 'static {
fn as_any(&self) -> &dyn Any;
fn dyn_eq(&self, other: &dyn Bounds) -> bool;
fn dyn_clone(&self) -> Box<dyn Bounds>;
}
impl<T> Bounds for T
where
T: Layout + Debug + PartialEq + Clone + 'static,
{
fn as_any(&self) -> &dyn Any {
self
}
fn dyn_eq(&self, other: &dyn Bounds) -> bool {
if let Some(other) = other.as_any().downcast_ref::<Self>() {
self == other
} else {
false
}
}
fn dyn_clone(&self) -> Box<dyn Bounds> {
Box::new(self.clone())
} }
} }
/// Layout a node. /// Layout a node.
pub trait Layout { pub trait Layout {
/// Layout the node into the given areas. /// Layout the node into the given areas.
fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Fragment; fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Vec<Frame>;
} }
/// The context for layouting. /// The context for layouting.
#[derive(Debug)]
pub struct LayoutContext<'a> { pub struct LayoutContext<'a> {
/// The environment from which fonts are gathered. /// The environment from which fonts are gathered.
pub env: &'a mut Env, pub env: &'a mut Env,
@ -183,44 +243,3 @@ impl Expand {
} }
} }
} }
/// The result of layouting a node.
#[derive(Debug, Clone, PartialEq)]
pub enum Fragment {
/// Spacing that should be added to the parent.
Spacing(Length),
/// A layout that should be added to and aligned in the parent.
Frame(Frame, LayoutAligns),
/// Multiple layouts.
Frames(Vec<Frame>, LayoutAligns),
}
impl Fragment {
/// Return a reference to all frames contained in this variant (zero, one or
/// arbitrarily many).
pub fn frames(&self) -> &[Frame] {
match self {
Self::Spacing(_) => &[],
Self::Frame(frame, _) => std::slice::from_ref(frame),
Self::Frames(frames, _) => frames,
}
}
/// Return a mutable reference to all frames contained in this variant.
pub fn frames_mut(&mut self) -> &mut [Frame] {
match self {
Self::Spacing(_) => &mut [],
Self::Frame(frame, _) => std::slice::from_mut(frame),
Self::Frames(frames, _) => frames,
}
}
/// Return all frames contained in this varian.
pub fn into_frames(self) -> Vec<Frame> {
match self {
Self::Spacing(_) => vec![],
Self::Frame(frame, _) => vec![frame],
Self::Frames(frames, _) => frames,
}
}
}

View File

@ -1,108 +0,0 @@
use std::any::Any;
use std::fmt::{self, Debug, Formatter};
use super::*;
/// A self-contained layout node.
#[derive(Clone, PartialEq)]
pub enum Node {
/// A text node.
Text(TextNode),
/// A spacing node.
Spacing(SpacingNode),
/// A dynamic node that can implement custom layouting behaviour.
Any(AnyNode),
}
impl Layout for Node {
fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Fragment {
match self {
Self::Spacing(spacing) => spacing.layout(ctx, areas),
Self::Text(text) => text.layout(ctx, areas),
Self::Any(any) => any.layout(ctx, areas),
}
}
}
impl Debug for Node {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Spacing(spacing) => spacing.fmt(f),
Self::Text(text) => text.fmt(f),
Self::Any(any) => any.fmt(f),
}
}
}
/// A wrapper around a dynamic layouting node.
pub struct AnyNode(Box<dyn Bounds>);
impl AnyNode {
/// Create a new instance from any node that satisifies the required bounds.
pub fn new<T>(any: T) -> Self
where
T: Layout + Debug + Clone + PartialEq + 'static,
{
Self(Box::new(any))
}
}
impl Layout for AnyNode {
fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Fragment {
self.0.layout(ctx, areas)
}
}
impl Clone for AnyNode {
fn clone(&self) -> Self {
Self(self.0.dyn_clone())
}
}
impl PartialEq for AnyNode {
fn eq(&self, other: &Self) -> bool {
self.0.dyn_eq(other.0.as_ref())
}
}
impl Debug for AnyNode {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl<T> From<T> for Node
where
T: Into<AnyNode>,
{
fn from(t: T) -> Self {
Self::Any(t.into())
}
}
trait Bounds: Layout + Debug + 'static {
fn as_any(&self) -> &dyn Any;
fn dyn_eq(&self, other: &dyn Bounds) -> bool;
fn dyn_clone(&self) -> Box<dyn Bounds>;
}
impl<T> Bounds for T
where
T: Layout + Debug + PartialEq + Clone + 'static,
{
fn as_any(&self) -> &dyn Any {
self
}
fn dyn_eq(&self, other: &dyn Bounds) -> bool {
if let Some(other) = other.as_any().downcast_ref::<Self>() {
self == other
} else {
false
}
}
fn dyn_clone(&self) -> Box<dyn Bounds> {
Box::new(self.clone())
}
}

View File

@ -6,19 +6,17 @@ pub struct PadNode {
/// The amount of padding. /// The amount of padding.
pub padding: Sides<Linear>, pub padding: Sides<Linear>,
/// The child node whose sides to pad. /// The child node whose sides to pad.
pub child: Node, pub child: AnyNode,
} }
impl Layout for PadNode { impl Layout for PadNode {
fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Fragment { fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Vec<Frame> {
let areas = shrink(areas, self.padding); let areas = shrink(areas, self.padding);
let mut frames = self.child.layout(ctx, &areas);
let mut fragment = self.child.layout(ctx, &areas); for frame in &mut frames {
for frame in fragment.frames_mut() {
pad(frame, self.padding); pad(frame, self.padding);
} }
frames
fragment
} }
} }

View File

@ -1,38 +1,63 @@
use std::fmt::{self, Debug, Formatter};
use super::*; use super::*;
use crate::exec::FontProps;
/// A node that arranges its children into a paragraph. /// A node that arranges its children into a paragraph.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct ParNode { pub struct ParNode {
/// The `main` and `cross` directions of this paragraph. /// The inline direction of this paragraph.
/// pub dir: Dir,
/// The children are placed in lines along the `cross` direction. The lines /// The spacing to insert between each line.
/// are stacked along the `main` direction.
pub dirs: LayoutDirs,
/// How to align this paragraph in its parent.
pub aligns: LayoutAligns,
/// The spacing to insert after each line.
pub line_spacing: Length, pub line_spacing: Length,
/// The nodes to be arranged in a paragraph. /// The nodes to be arranged in a paragraph.
pub children: Vec<Node>, pub children: Vec<ParChild>,
}
/// A child of a paragraph node.
#[derive(Debug, Clone, PartialEq)]
pub enum ParChild {
/// Spacing between other nodes.
Spacing(Length),
/// A run of text and how to align it in its line.
Text(TextNode, Align),
/// Any child node and how to align it in its line.
Any(AnyNode, Align),
}
/// A consecutive, styled run of text.
#[derive(Clone, PartialEq)]
pub struct TextNode {
/// The text.
pub text: String,
/// Properties used for font selection and layout.
pub props: FontProps,
}
impl Debug for TextNode {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Text({})", self.text)
}
} }
impl Layout for ParNode { impl Layout for ParNode {
fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Fragment { fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Vec<Frame> {
let mut layouter = ParLayouter::new(self.dirs, self.line_spacing, areas.clone()); let mut layouter = ParLayouter::new(self.dir, self.line_spacing, areas.clone());
for child in &self.children { for child in &self.children {
match child.layout(ctx, &layouter.areas) { match *child {
Fragment::Spacing(spacing) => layouter.push_spacing(spacing), ParChild::Spacing(amount) => layouter.push_spacing(amount),
Fragment::Frame(frame, aligns) => { ParChild::Text(ref node, align) => {
layouter.push_frame(frame, aligns.cross) let frame = shape(&node.text, &mut ctx.env.fonts, &node.props);
layouter.push_frame(frame, align);
} }
Fragment::Frames(frames, aligns) => { ParChild::Any(ref node, align) => {
for frame in frames { for frame in node.layout(ctx, &layouter.areas) {
layouter.push_frame(frame, aligns.cross); layouter.push_frame(frame, align);
} }
} }
} }
} }
Fragment::Frames(layouter.finish(), self.aligns) layouter.finish()
} }
} }
@ -43,30 +68,30 @@ impl From<ParNode> for AnyNode {
} }
struct ParLayouter { struct ParLayouter {
dirs: Gen<Dir>,
main: SpecAxis, main: SpecAxis,
cross: SpecAxis, cross: SpecAxis,
dirs: LayoutDirs,
line_spacing: Length, line_spacing: Length,
areas: Areas, areas: Areas,
finished: Vec<Frame>, finished: Vec<Frame>,
lines: Vec<(Length, Frame, Align)>, stack: Vec<(Length, Frame, Align)>,
lines_size: Gen<Length>, stack_size: Gen<Length>,
line: Vec<(Length, Frame, Align)>, line: Vec<(Length, Frame, Align)>,
line_size: Gen<Length>, line_size: Gen<Length>,
line_ruler: Align, line_ruler: Align,
} }
impl ParLayouter { impl ParLayouter {
fn new(dirs: LayoutDirs, line_spacing: Length, areas: Areas) -> Self { fn new(dir: Dir, line_spacing: Length, areas: Areas) -> Self {
Self { Self {
main: dirs.main.axis(), dirs: Gen::new(Dir::TTB, dir),
cross: dirs.cross.axis(), main: SpecAxis::Vertical,
dirs, cross: SpecAxis::Horizontal,
line_spacing, line_spacing,
areas, areas,
finished: vec![], finished: vec![],
lines: vec![], stack: vec![],
lines_size: Gen::ZERO, stack_size: Gen::ZERO,
line: vec![], line: vec![],
line_size: Gen::ZERO, line_size: Gen::ZERO,
line_ruler: Align::Start, line_ruler: Align::Start,
@ -122,12 +147,10 @@ impl ParLayouter {
} }
} }
let size = frame.size.switch(self.dirs);
// A line can contain frames with different alignments. They exact // A line can contain frames with different alignments. They exact
// positions are calculated later depending on the alignments. // positions are calculated later depending on the alignments.
let size = frame.size.switch(self.main);
self.line.push((self.line_size.cross, frame, align)); self.line.push((self.line_size.cross, frame, align));
self.line_size.cross += size.cross; self.line_size.cross += size.cross;
self.line_size.main = self.line_size.main.max(size.main); self.line_size.main = self.line_size.main.max(size.main);
self.line_ruler = align; self.line_ruler = align;
@ -135,15 +158,15 @@ impl ParLayouter {
fn finish_line(&mut self) { fn finish_line(&mut self) {
let full_size = { let full_size = {
let expand = self.areas.expand.switch(self.dirs); let expand = self.areas.expand.get(self.cross);
let full = self.areas.full.switch(self.dirs); let full = self.areas.full.get(self.cross);
Gen::new( Gen::new(
self.line_size.main, self.line_size.main,
expand.cross.resolve(self.line_size.cross, full.cross), expand.resolve(self.line_size.cross, full),
) )
}; };
let mut output = Frame::new(full_size.switch(self.dirs).to_size()); let mut output = Frame::new(full_size.switch(self.main).to_size());
for (before, frame, align) in std::mem::take(&mut self.line) { for (before, frame, align) in std::mem::take(&mut self.line) {
let child_cross_size = frame.size.get(self.cross); let child_cross_size = frame.size.get(self.cross);
@ -158,49 +181,47 @@ impl ParLayouter {
full_size.cross - before_with_self .. after full_size.cross - before_with_self .. after
}); });
let pos = Gen::new(Length::ZERO, cross).switch(self.dirs).to_point(); let pos = Gen::new(Length::ZERO, cross).switch(self.main).to_point();
output.push_frame(pos, frame); output.push_frame(pos, frame);
} }
// Add line spacing, but only between lines. // Add line spacing, but only between lines.
if !self.lines.is_empty() { if !self.stack.is_empty() {
self.lines_size.main += self.line_spacing; self.stack_size.main += self.line_spacing;
*self.areas.current.get_mut(self.main) -= self.line_spacing; *self.areas.current.get_mut(self.main) -= self.line_spacing;
} }
// Update metrics of the whole paragraph. // Update metrics of paragraph and reset for line.
self.lines.push((self.lines_size.main, output, self.line_ruler)); self.stack.push((self.stack_size.main, output, self.line_ruler));
self.lines_size.main += full_size.main; self.stack_size.main += full_size.main;
self.lines_size.cross = self.lines_size.cross.max(full_size.cross); self.stack_size.cross = self.stack_size.cross.max(full_size.cross);
*self.areas.current.get_mut(self.main) -= full_size.main; *self.areas.current.get_mut(self.main) -= full_size.main;
// Reset metrics for the single line.
self.line_size = Gen::ZERO; self.line_size = Gen::ZERO;
self.line_ruler = Align::Start; self.line_ruler = Align::Start;
} }
fn finish_area(&mut self) { fn finish_area(&mut self) {
let size = self.lines_size; let full_size = self.stack_size;
let mut output = Frame::new(size.switch(self.dirs).to_size()); let mut output = Frame::new(full_size.switch(self.main).to_size());
for (before, line, cross_align) in std::mem::take(&mut self.lines) { for (before, line, cross_align) in std::mem::take(&mut self.stack) {
let child_size = line.size.switch(self.dirs); let child_size = line.size.switch(self.main);
// Position along the main axis. // Position along the main axis.
let main = if self.dirs.main.is_positive() { let main = if self.dirs.main.is_positive() {
before before
} else { } else {
size.main - (before + child_size.main) full_size.main - (before + child_size.main)
}; };
// Align along the cross axis. // Align along the cross axis.
let cross = cross_align.resolve(if self.dirs.cross.is_positive() { let cross = cross_align.resolve(if self.dirs.cross.is_positive() {
Length::ZERO .. size.cross - child_size.cross Length::ZERO .. full_size.cross - child_size.cross
} else { } else {
size.cross - child_size.cross .. Length::ZERO full_size.cross - child_size.cross .. Length::ZERO
}); });
let pos = Gen::new(main, cross).switch(self.dirs).to_point(); let pos = Gen::new(main, cross).switch(self.main).to_point();
output.push_frame(pos, line); output.push_frame(pos, line);
} }
@ -208,7 +229,7 @@ impl ParLayouter {
self.areas.next(); self.areas.next();
// Reset metrics for the whole paragraph. // Reset metrics for the whole paragraph.
self.lines_size = Gen::ZERO; self.stack_size = Gen::ZERO;
} }
fn finish(mut self) -> Vec<Frame> { fn finish(mut self) -> Vec<Frame> {

View File

@ -1,35 +0,0 @@
use std::fmt::{self, Debug, Formatter};
use super::*;
/// A node that adds spacing to its parent.
#[derive(Copy, Clone, PartialEq)]
pub struct SpacingNode {
/// The amount of spacing to insert.
pub amount: Length,
/// Defines how spacing interacts with surrounding spacing.
///
/// Hard spacing (`softness = 0`) assures that a fixed amount of spacing
/// will always be inserted. Soft spacing (`softness >= 1`) will be consumed
/// by other spacing with lower softness and can be used to insert
/// overridable spacing, e.g. between words or paragraphs.
pub softness: u8,
}
impl Layout for SpacingNode {
fn layout(&self, _: &mut LayoutContext, _: &Areas) -> Fragment {
Fragment::Spacing(self.amount)
}
}
impl Debug for SpacingNode {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Spacing({}, {})", self.amount, self.softness)
}
}
impl From<SpacingNode> for Node {
fn from(spacing: SpacingNode) -> Self {
Self::Spacing(spacing)
}
}

View File

@ -7,28 +7,34 @@ pub struct StackNode {
/// ///
/// The children are stacked along the `main` direction. The `cross` /// The children are stacked along the `main` direction. The `cross`
/// direction is required for aligning the children. /// direction is required for aligning the children.
pub dirs: LayoutDirs, pub dirs: Gen<Dir>,
/// How to align this stack in its parent.
pub aligns: LayoutAligns,
/// The nodes to be stacked. /// The nodes to be stacked.
pub children: Vec<Node>, pub children: Vec<StackChild>,
}
/// A child of a stack node.
#[derive(Debug, Clone, PartialEq)]
pub enum StackChild {
/// Spacing between other nodes.
Spacing(Length),
/// Any child node and how to align it in the stack.
Any(AnyNode, Gen<Align>),
} }
impl Layout for StackNode { impl Layout for StackNode {
fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Fragment { fn layout(&self, ctx: &mut LayoutContext, areas: &Areas) -> Vec<Frame> {
let mut layouter = StackLayouter::new(self.dirs, areas.clone()); let mut layouter = StackLayouter::new(self.dirs, areas.clone());
for child in &self.children { for child in &self.children {
match child.layout(ctx, &layouter.areas) { match *child {
Fragment::Spacing(spacing) => layouter.push_spacing(spacing), StackChild::Spacing(amount) => layouter.push_spacing(amount),
Fragment::Frame(frame, aligns) => layouter.push_frame(frame, aligns), StackChild::Any(ref node, aligns) => {
Fragment::Frames(frames, aligns) => { for frame in node.layout(ctx, &layouter.areas) {
for frame in frames {
layouter.push_frame(frame, aligns); layouter.push_frame(frame, aligns);
} }
} }
} }
} }
Fragment::Frames(layouter.finish(), self.aligns) layouter.finish()
} }
} }
@ -39,24 +45,24 @@ impl From<StackNode> for AnyNode {
} }
struct StackLayouter { struct StackLayouter {
dirs: Gen<Dir>,
main: SpecAxis, main: SpecAxis,
dirs: LayoutDirs,
areas: Areas, areas: Areas,
finished: Vec<Frame>, finished: Vec<Frame>,
frames: Vec<(Length, Frame, LayoutAligns)>, frames: Vec<(Length, Frame, Gen<Align>)>,
used: Gen<Length>, size: Gen<Length>,
ruler: Align, ruler: Align,
} }
impl StackLayouter { impl StackLayouter {
fn new(dirs: LayoutDirs, areas: Areas) -> Self { fn new(dirs: Gen<Dir>, areas: Areas) -> Self {
Self { Self {
main: dirs.main.axis(),
dirs, dirs,
main: dirs.main.axis(),
areas, areas,
finished: vec![], finished: vec![],
frames: vec![], frames: vec![],
used: Gen::ZERO, size: Gen::ZERO,
ruler: Align::Start, ruler: Align::Start,
} }
} }
@ -65,10 +71,10 @@ impl StackLayouter {
let main_rest = self.areas.current.get_mut(self.main); let main_rest = self.areas.current.get_mut(self.main);
let capped = amount.min(*main_rest); let capped = amount.min(*main_rest);
*main_rest -= capped; *main_rest -= capped;
self.used.main += capped; self.size.main += capped;
} }
fn push_frame(&mut self, frame: Frame, aligns: LayoutAligns) { fn push_frame(&mut self, frame: Frame, aligns: Gen<Align>) {
if self.ruler > aligns.main { if self.ruler > aligns.main {
self.finish_area(); self.finish_area();
} }
@ -82,21 +88,18 @@ impl StackLayouter {
} }
} }
let size = frame.size.switch(self.dirs); let size = frame.size.switch(self.main);
self.frames.push((self.used.main, frame, aligns)); self.frames.push((self.size.main, frame, aligns));
*self.areas.current.get_mut(self.main) -= size.main;
self.used.main += size.main;
self.used.cross = self.used.cross.max(size.cross);
self.ruler = aligns.main; self.ruler = aligns.main;
self.size.main += size.main;
self.size.cross = self.size.cross.max(size.cross);
*self.areas.current.get_mut(self.main) -= size.main;
} }
fn finish_area(&mut self) { fn finish_area(&mut self) {
let full_size = { let full_size = {
let expand = self.areas.expand; let Areas { current, full, expand, .. } = self.areas;
let full = self.areas.full; let used = self.size.switch(self.main).to_size();
let current = self.areas.current;
let used = self.used.switch(self.dirs).to_size();
let mut size = Size::new( let mut size = Size::new(
expand.horizontal.resolve(used.width, full.width), expand.horizontal.resolve(used.width, full.width),
@ -113,21 +116,21 @@ impl StackLayouter {
size = Size::new(width, width / aspect); size = Size::new(width, width / aspect);
} }
size.switch(self.dirs) size.switch(self.main)
}; };
let mut output = Frame::new(full_size.switch(self.dirs).to_size()); let mut output = Frame::new(full_size.switch(self.main).to_size());
for (before, frame, aligns) in std::mem::take(&mut self.frames) { for (before, frame, aligns) in std::mem::take(&mut self.frames) {
let child_size = frame.size.switch(self.dirs); let child_size = frame.size.switch(self.main);
// Align along the main axis. // Align along the main axis.
let main = aligns.main.resolve(if self.dirs.main.is_positive() { let main = aligns.main.resolve(if self.dirs.main.is_positive() {
let after_with_self = self.used.main - before; let after_with_self = self.size.main - before;
before .. full_size.main - after_with_self before .. full_size.main - after_with_self
} else { } else {
let before_with_self = before + child_size.main; let before_with_self = before + child_size.main;
let after = self.used.main - (before + child_size.main); let after = self.size.main - (before + child_size.main);
full_size.main - before_with_self .. after full_size.main - before_with_self .. after
}); });
@ -138,15 +141,14 @@ impl StackLayouter {
full_size.cross - child_size.cross .. Length::ZERO full_size.cross - child_size.cross .. Length::ZERO
}); });
let pos = Gen::new(main, cross).switch(self.dirs).to_point(); let pos = Gen::new(main, cross).switch(self.main).to_point();
output.push_frame(pos, frame); output.push_frame(pos, frame);
} }
self.finished.push(output); self.finished.push(output);
self.areas.next(); self.areas.next();
self.used = Gen::ZERO;
self.ruler = Align::Start; self.ruler = Align::Start;
self.size = Gen::ZERO;
} }
fn finish(mut self) -> Vec<Frame> { fn finish(mut self) -> Vec<Frame> {

View File

@ -1,36 +0,0 @@
use std::fmt::{self, Debug, Formatter};
use super::*;
use crate::exec::FontProps;
/// A consecutive, styled run of text.
#[derive(Clone, PartialEq)]
pub struct TextNode {
/// The text direction.
pub dir: Dir,
/// How to align this text node in its parent.
pub aligns: LayoutAligns,
/// The text.
pub text: String,
/// Properties used for font selection and layout.
pub props: FontProps,
}
impl Layout for TextNode {
fn layout(&self, ctx: &mut LayoutContext, _: &Areas) -> Fragment {
let frame = shape(&self.text, &mut ctx.env.fonts, &self.props);
Fragment::Frame(frame, self.aligns)
}
}
impl Debug for TextNode {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Text({})", self.text)
}
}
impl From<TextNode> for Node {
fn from(text: TextNode) -> Self {
Self::Text(text)
}
}

View File

@ -6,11 +6,6 @@ use super::*;
/// - Alignments: variadic, of type `alignment`. /// - Alignments: variadic, of type `alignment`.
/// - Body: optional, of type `template`. /// - Body: optional, of type `template`.
/// ///
/// Which axis an alignment should apply to (main or cross) is inferred from
/// either the argument itself (for anything other than `center`) or from the
/// second argument if present, defaulting to the cross axis for a single
/// `center` alignment.
///
/// # Named parameters /// # Named parameters
/// - Horizontal alignment: `horizontal`, of type `alignment`. /// - Horizontal alignment: `horizontal`, of type `alignment`.
/// - Vertical alignment: `vertical`, of type `alignment`. /// - Vertical alignment: `vertical`, of type `alignment`.
@ -21,33 +16,45 @@ use super::*;
/// ///
/// # Relevant types and constants /// # Relevant types and constants
/// - Type `alignment` /// - Type `alignment`
/// - `start`
/// - `center`
/// - `end`
/// - `left` /// - `left`
/// - `right` /// - `right`
/// - `top` /// - `top`
/// - `bottom` /// - `bottom`
/// - `center`
pub fn align(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value { pub fn align(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
let first = args.find(ctx); let first = args.find::<AlignValue>(ctx);
let second = args.find(ctx); let second = args.find::<AlignValue>(ctx);
let hor = args.get(ctx, "horizontal"); let mut horizontal = args.get::<AlignValue>(ctx, "horizontal");
let ver = args.get(ctx, "vertical"); let mut vertical = args.get::<AlignValue>(ctx, "vertical");
let body = args.find::<TemplateValue>(ctx); let body = args.find::<TemplateValue>(ctx);
for value in first.into_iter().chain(second) {
match value.axis() {
Some(SpecAxis::Horizontal) | None if horizontal.is_none() => {
horizontal = Some(value);
}
Some(SpecAxis::Vertical) | None if vertical.is_none() => {
vertical = Some(value);
}
_ => {}
}
}
Value::template("align", move |ctx| { Value::template("align", move |ctx| {
let snapshot = ctx.state.clone(); let snapshot = ctx.state.clone();
let values = first if let Some(horizontal) = horizontal {
.into_iter() ctx.state.aligns.cross = horizontal.to_align(ctx.state.lang.dir);
.chain(second.into_iter()) }
.map(|arg: Spanned<AlignValue>| (arg.v.axis(), arg))
.chain(hor.into_iter().map(|arg| (Some(SpecAxis::Horizontal), arg)))
.chain(ver.into_iter().map(|arg| (Some(SpecAxis::Vertical), arg)));
apply(ctx, values);
if let Some(vertical) = vertical {
ctx.state.aligns.main = vertical.to_align(Dir::TTB);
if ctx.state.aligns.main != snapshot.aligns.main { if ctx.state.aligns.main != snapshot.aligns.main {
ctx.push_linebreak(); ctx.push_linebreak();
} }
}
if let Some(body) = &body { if let Some(body) = &body {
body.exec(ctx); body.exec(ctx);
@ -56,109 +63,48 @@ pub fn align(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
}) })
} }
/// Deduplicate and apply the alignments. /// An alignment specifier passed to `align`.
fn apply(
ctx: &mut ExecContext,
values: impl Iterator<Item = (Option<SpecAxis>, Spanned<AlignValue>)>,
) {
let mut had = Gen::uniform(false);
let mut had_center = false;
for (axis, Spanned { v: arg, span }) in values {
// Check whether we know which axis this alignment belongs to.
if let Some(axis) = axis {
// We know the axis.
let gen_axis = axis.switch(ctx.state.dirs);
let gen_align = arg.switch(ctx.state.dirs);
if arg.axis().map_or(false, |a| a != axis) {
ctx.diag(error!(span, "invalid alignment for {} axis", axis));
} else if had.get(gen_axis) {
ctx.diag(error!(span, "duplicate alignment for {} axis", axis));
} else {
*ctx.state.aligns.get_mut(gen_axis) = gen_align;
*had.get_mut(gen_axis) = true;
}
} else {
// We don't know the axis: This has to be a `center` alignment for a
// positional argument.
debug_assert_eq!(arg, AlignValue::Center);
if had.main && had.cross {
ctx.diag(error!(span, "duplicate alignment"));
} else if had_center {
// Both this and the previous one are unspecified `center`
// alignments. Both axes should be centered.
ctx.state.aligns.main = Align::Center;
ctx.state.aligns.cross = Align::Center;
had = Gen::uniform(true);
} else {
had_center = true;
}
}
// If we we know the other alignment, we can handle the unspecified
// `center` alignment.
if had_center && (had.main || had.cross) {
if had.main {
ctx.state.aligns.cross = Align::Center;
} else {
ctx.state.aligns.main = Align::Center;
}
had = Gen::uniform(true);
had_center = false;
}
}
// If `had_center` wasn't flushed by now, it's the only argument and
// then we default to applying it to the cross axis.
if had_center {
ctx.state.aligns.cross = Align::Center;
}
}
/// An alignment value.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub(super) enum AlignValue { pub(super) enum AlignValue {
Left, Start,
Center, Center,
End,
Left,
Right, Right,
Top, Top,
Bottom, Bottom,
} }
impl AlignValue { impl AlignValue {
/// The specific axis this alignment refers to.
fn axis(self) -> Option<SpecAxis> { fn axis(self) -> Option<SpecAxis> {
match self { match self {
Self::Start => None,
Self::Center => None,
Self::End => None,
Self::Left => Some(SpecAxis::Horizontal), Self::Left => Some(SpecAxis::Horizontal),
Self::Right => Some(SpecAxis::Horizontal), Self::Right => Some(SpecAxis::Horizontal),
Self::Top => Some(SpecAxis::Vertical), Self::Top => Some(SpecAxis::Vertical),
Self::Bottom => Some(SpecAxis::Vertical), Self::Bottom => Some(SpecAxis::Vertical),
Self::Center => None,
} }
} }
}
impl Switch for AlignValue { fn to_align(self, dir: Dir) -> Align {
type Other = Align; let side = |is_at_positive_start| {
if dir.is_positive() == is_at_positive_start {
fn switch(self, dirs: LayoutDirs) -> Self::Other {
let get = |dir: Dir, at_positive_start| {
if dir.is_positive() == at_positive_start {
Align::Start Align::Start
} else { } else {
Align::End Align::End
} }
}; };
let dirs = dirs.switch(dirs);
match self { match self {
Self::Left => get(dirs.horizontal, true), Self::Start => Align::Start,
Self::Right => get(dirs.horizontal, false),
Self::Top => get(dirs.vertical, true),
Self::Bottom => get(dirs.vertical, false),
Self::Center => Align::Center, Self::Center => Align::Center,
Self::End => Align::End,
Self::Left => side(true),
Self::Right => side(false),
Self::Top => side(true),
Self::Bottom => side(false),
} }
} }
} }
@ -166,8 +112,10 @@ impl Switch for AlignValue {
impl Display for AlignValue { impl Display for AlignValue {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(match self { f.pad(match self {
Self::Left => "left", Self::Start => "start",
Self::Center => "center", Self::Center => "center",
Self::End => "end",
Self::Left => "left",
Self::Right => "right", Self::Right => "right",
Self::Top => "top", Self::Top => "top",
Self::Bottom => "bottom", Self::Bottom => "bottom",

View File

@ -2,9 +2,7 @@ use ::image::GenericImageView;
use super::*; use super::*;
use crate::env::{ImageResource, ResourceId}; use crate::env::{ImageResource, ResourceId};
use crate::layout::{ use crate::layout::{AnyNode, Areas, Element, Frame, Image, Layout, LayoutContext};
AnyNode, Areas, Element, Fragment, Frame, Image, Layout, LayoutContext,
};
/// `image`: An image. /// `image`: An image.
/// ///
@ -25,13 +23,7 @@ pub fn image(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
let loaded = ctx.env.resources.load(&path.v, ImageResource::parse); let loaded = ctx.env.resources.load(&path.v, ImageResource::parse);
if let Some((res, img)) = loaded { if let Some((res, img)) = loaded {
let dimensions = img.buf.dimensions(); let dimensions = img.buf.dimensions();
ctx.push(ImageNode { ctx.push_into_par(ImageNode { res, dimensions, width, height });
res,
dimensions,
width,
height,
aligns: ctx.state.aligns,
});
} else { } else {
ctx.diag(error!(path.span, "failed to load image")); ctx.diag(error!(path.span, "failed to load image"));
} }
@ -42,8 +34,6 @@ pub fn image(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
/// An image node. /// An image node.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
struct ImageNode { struct ImageNode {
/// How to align this image node in its parent.
aligns: LayoutAligns,
/// The resource id of the image file. /// The resource id of the image file.
res: ResourceId, res: ResourceId,
/// The pixel dimensions of the image. /// The pixel dimensions of the image.
@ -55,7 +45,7 @@ struct ImageNode {
} }
impl Layout for ImageNode { impl Layout for ImageNode {
fn layout(&self, _: &mut LayoutContext, areas: &Areas) -> Fragment { fn layout(&self, _: &mut LayoutContext, areas: &Areas) -> Vec<Frame> {
let Areas { current, full, .. } = areas; let Areas { current, full, .. } = areas;
let pixel_width = self.dimensions.0 as f64; let pixel_width = self.dimensions.0 as f64;
@ -86,7 +76,7 @@ impl Layout for ImageNode {
let mut frame = Frame::new(size); let mut frame = Frame::new(size);
frame.push(Point::ZERO, Element::Image(Image { res: self.res, size })); frame.push(Point::ZERO, Element::Image(Image { res: self.res, size }));
Fragment::Frame(frame, self.aligns) vec![frame]
} }
} }

45
src/library/lang.rs Normal file
View File

@ -0,0 +1,45 @@
use super::*;
/// `lang`: Configure the language.
///
/// # Positional parameters
/// - Language: of type `string`. Has to be a valid ISO 639-1 code.
///
/// # Named parameters
/// - Text direction: `dir`, of type `direction`, must be horizontal.
///
/// # Return value
/// A template that configures language properties.
///
/// # Relevant types and constants
/// - Type `direction`
/// - `ltr`
/// - `rtl`
pub fn lang(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
let iso = args.find::<String>(ctx).map(|s| s.to_ascii_lowercase());
let dir = args.get::<Spanned<Dir>>(ctx, "dir");
Value::template("lang", move |ctx| {
if let Some(iso) = &iso {
ctx.state.lang.dir = lang_dir(iso);
}
if let Some(dir) = dir {
if dir.v.axis() == SpecAxis::Horizontal {
ctx.state.lang.dir = dir.v;
} else {
ctx.diag(error!(dir.span, "must be horizontal"));
}
}
ctx.push_parbreak();
})
}
/// The default direction for the language identified by `iso`.
fn lang_dir(iso: &str) -> Dir {
match iso {
"ar" | "he" | "fa" | "ur" | "ps" | "yi" => Dir::RTL,
"en" | "fr" | "de" | _ => Dir::LTR,
}
}

View File

@ -7,6 +7,7 @@ mod align;
mod base; mod base;
mod font; mod font;
mod image; mod image;
mod lang;
mod markup; mod markup;
mod pad; mod pad;
mod page; mod page;
@ -18,6 +19,7 @@ pub use self::image::*;
pub use align::*; pub use align::*;
pub use base::*; pub use base::*;
pub use font::*; pub use font::*;
pub use lang::*;
pub use markup::*; pub use markup::*;
pub use pad::*; pub use pad::*;
pub use page::*; pub use page::*;
@ -31,7 +33,7 @@ use fontdock::{FontStyle, FontWeight};
use crate::eval::{AnyValue, FuncValue, Scope}; use crate::eval::{AnyValue, FuncValue, Scope};
use crate::eval::{EvalContext, FuncArgs, TemplateValue, Value}; use crate::eval::{EvalContext, FuncArgs, TemplateValue, Value};
use crate::exec::{Exec, ExecContext, FontFamily}; use crate::exec::{Exec, FontFamily};
use crate::font::VerticalFontMetric; use crate::font::VerticalFontMetric;
use crate::geom::*; use crate::geom::*;
use crate::syntax::{Node, Spanned}; use crate::syntax::{Node, Spanned};
@ -67,6 +69,7 @@ pub fn _new() -> Scope {
func!("font", font); func!("font", font);
func!("h", h); func!("h", h);
func!("image", image); func!("image", image);
func!("lang", lang);
func!("pad", pad); func!("pad", pad);
func!("page", page); func!("page", page);
func!("pagebreak", pagebreak); func!("pagebreak", pagebreak);
@ -79,8 +82,10 @@ pub fn _new() -> Scope {
func!("v", v); func!("v", v);
// Constants. // Constants.
constant!("left", AlignValue::Left); constant!("start", AlignValue::Start);
constant!("center", AlignValue::Center); constant!("center", AlignValue::Center);
constant!("end", AlignValue::End);
constant!("left", AlignValue::Left);
constant!("right", AlignValue::Right); constant!("right", AlignValue::Right);
constant!("top", AlignValue::Top); constant!("top", AlignValue::Top);
constant!("bottom", AlignValue::Bottom); constant!("bottom", AlignValue::Bottom);

View File

@ -31,9 +31,7 @@ pub fn pad(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
); );
Value::template("pad", move |ctx| { Value::template("pad", move |ctx| {
let snapshot = ctx.state.clone(); let child = ctx.exec_group(&body).into();
let child = ctx.exec(&body).into(); ctx.push_into_par(PadNode { padding, child });
ctx.push(PadNode { padding, child });
ctx.state = snapshot;
}) })
} }

View File

@ -17,19 +17,10 @@ use crate::paper::{Paper, PaperClass};
/// - Top margin: `top`, of type `linear` relative to height. /// - Top margin: `top`, of type `linear` relative to height.
/// - Bottom margin: `bottom`, of type `linear` relative to height. /// - Bottom margin: `bottom`, of type `linear` relative to height.
/// - Flip width and height: `flip`, of type `bool`. /// - Flip width and height: `flip`, of type `bool`.
/// - Main layouting direction: `main-dir`, of type `direction`.
/// - Cross layouting direction: `cross-dir`, of type `direction`.
/// ///
/// # Return value /// # Return value
/// A template that configures page properties. The effect is scoped to the body /// A template that configures page properties. The effect is scoped to the body
/// if present. /// if present.
///
/// # Relevant types and constants
/// - Type `direction`
/// - `ltr` (left to right)
/// - `rtl` (right to left)
/// - `ttb` (top to bottom)
/// - `btt` (bottom to top)
pub fn page(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value { pub fn page(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
let paper = args.find::<Spanned<String>>(ctx).and_then(|name| { let paper = args.find::<Spanned<String>>(ctx).and_then(|name| {
Paper::from_name(&name.v).or_else(|| { Paper::from_name(&name.v).or_else(|| {
@ -46,8 +37,6 @@ pub fn page(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
let right = args.get(ctx, "right"); let right = args.get(ctx, "right");
let bottom = args.get(ctx, "bottom"); let bottom = args.get(ctx, "bottom");
let flip = args.get(ctx, "flip"); let flip = args.get(ctx, "flip");
let main = args.get(ctx, "main-dir");
let cross = args.get(ctx, "cross-dir");
let body = args.find::<TemplateValue>(ctx); let body = args.find::<TemplateValue>(ctx);
let span = args.span; let span = args.span;
@ -94,7 +83,6 @@ pub fn page(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
std::mem::swap(&mut page.size.width, &mut page.size.height); std::mem::swap(&mut page.size.width, &mut page.size.height);
} }
ctx.set_dirs(Gen::new(main, cross));
ctx.finish_page(false, true, span); ctx.finish_page(false, true, span);
if let Some(body) = &body { if let Some(body) = &body {

View File

@ -2,26 +2,19 @@ use super::*;
/// `par`: Configure paragraphs. /// `par`: Configure paragraphs.
/// ///
/// # Positional parameters
/// - Body: optional, of type `template`.
///
/// # Named parameters /// # Named parameters
/// - Paragraph spacing: `spacing`, of type `linear` relative to current font size. /// - Paragraph spacing: `spacing`, of type `linear` relative to current font size.
/// - Line leading: `leading`, of type `linear` relative to current font size. /// - Line leading: `leading`, of type `linear` relative to current font size.
/// - Word spacing: `word-spacing`, of type `linear` relative to current font size. /// - Word spacing: `word-spacing`, of type `linear` relative to current font size.
/// ///
/// # Return value /// # Return value
/// A template that configures paragraph properties. The effect is scoped to the /// A template that configures paragraph properties.
/// body if present.
pub fn par(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value { pub fn par(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
let spacing = args.get(ctx, "spacing"); let spacing = args.get(ctx, "spacing");
let leading = args.get(ctx, "leading"); let leading = args.get(ctx, "leading");
let word_spacing = args.get(ctx, "word-spacing"); let word_spacing = args.get(ctx, "word-spacing");
let body = args.find::<TemplateValue>(ctx);
Value::template("par", move |ctx| { Value::template("par", move |ctx| {
let snapshot = ctx.state.clone();
if let Some(spacing) = spacing { if let Some(spacing) = spacing {
ctx.state.par.spacing = spacing; ctx.state.par.spacing = spacing;
} }
@ -35,10 +28,5 @@ pub fn par(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
} }
ctx.push_parbreak(); ctx.push_parbreak();
if let Some(body) = &body {
body.exec(ctx);
ctx.state = snapshot;
}
}) })
} }

View File

@ -59,21 +59,18 @@ fn rect_impl(
body: TemplateValue, body: TemplateValue,
) -> Value { ) -> Value {
Value::template(name, move |ctx| { Value::template(name, move |ctx| {
let snapshot = ctx.state.clone(); let child = ctx.exec_group(&body).into();
let child = ctx.exec(&body).into();
let node = FixedNode { width, height, aspect, child }; let node = FixedNode { width, height, aspect, child };
if let Some(color) = fill { if let Some(color) = fill {
ctx.push(BackgroundNode { ctx.push_into_par(BackgroundNode {
shape: BackgroundShape::Rect, shape: BackgroundShape::Rect,
fill: Fill::Color(color), fill: Fill::Color(color),
child: node.into(), child: node.into(),
}); });
} else { } else {
ctx.push(node); ctx.push_into_par(node);
} }
ctx.state = snapshot;
}) })
} }
@ -136,8 +133,7 @@ fn ellipse_impl(
// perfectly into the ellipse. // perfectly into the ellipse.
const PAD: f64 = 0.5 - SQRT_2 / 4.0; const PAD: f64 = 0.5 - SQRT_2 / 4.0;
let snapshot = ctx.state.clone(); let child = ctx.exec_group(&body).into();
let child = ctx.exec(&body).into();
let node = FixedNode { let node = FixedNode {
width, width,
height, height,
@ -150,15 +146,13 @@ fn ellipse_impl(
}; };
if let Some(color) = fill { if let Some(color) = fill {
ctx.push(BackgroundNode { ctx.push_into_par(BackgroundNode {
shape: BackgroundShape::Ellipse, shape: BackgroundShape::Ellipse,
fill: Fill::Color(color), fill: Fill::Color(color),
child: node.into(), child: node.into(),
}); });
} else { } else {
ctx.push(node); ctx.push_into_par(node);
} }
ctx.state = snapshot;
}) })
} }

View File

@ -1,5 +1,4 @@
use super::*; use super::*;
use crate::layout::SpacingNode;
/// `h`: Horizontal spacing. /// `h`: Horizontal spacing.
/// ///
@ -9,7 +8,7 @@ use crate::layout::SpacingNode;
/// # Return value /// # Return value
/// A template that inserts horizontal spacing. /// A template that inserts horizontal spacing.
pub fn h(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value { pub fn h(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
spacing_impl(ctx, args, SpecAxis::Horizontal) spacing_impl("h", ctx, args, GenAxis::Cross)
} }
/// `v`: Vertical spacing. /// `v`: Vertical spacing.
@ -20,20 +19,20 @@ pub fn h(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
/// # Return value /// # Return value
/// A template that inserts vertical spacing. /// A template that inserts vertical spacing.
pub fn v(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value { pub fn v(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
spacing_impl(ctx, args, SpecAxis::Vertical) spacing_impl("v", ctx, args, GenAxis::Main)
} }
fn spacing_impl(ctx: &mut EvalContext, args: &mut FuncArgs, axis: SpecAxis) -> Value { fn spacing_impl(
name: &str,
ctx: &mut EvalContext,
args: &mut FuncArgs,
axis: GenAxis,
) -> Value {
let spacing: Option<Linear> = args.require(ctx, "spacing"); let spacing: Option<Linear> = args.require(ctx, "spacing");
Value::template("spacing", move |ctx| { Value::template(name, move |ctx| {
if let Some(linear) = spacing { if let Some(linear) = spacing {
let amount = linear.resolve(ctx.state.font.resolve_size()); let amount = linear.resolve(ctx.state.font.resolve_size());
let spacing = SpacingNode { amount, softness: 0 }; ctx.push_spacing(axis, amount, 0);
if axis == ctx.state.dirs.main.axis() {
ctx.push_into_stack(spacing);
} else {
ctx.push(spacing);
}
} }
}) })
} }

BIN
tests/ref/library/lang.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.0 KiB

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

View File

@ -0,0 +1,16 @@
// Test the `lang` function.
---
Left to right.
#lang("ar")
Right to left.
#lang(dir: ltr)
Back again.
---
// Ref: false
// Error: 12-15 must be horizontal
#lang(dir: ttb)

View File

@ -27,9 +27,6 @@
// Error: 7-18 unknown variable // Error: 7-18 unknown variable
#page(nonexistant) #page(nonexistant)
// Error: 17-20 aligned axis
#page(main-dir: ltr)
// Flipped predefined paper. // Flipped predefined paper.
#page("a11", flip: true)[Flipped A11] #page("a11", flip: true)[Flipped A11]
@ -38,10 +35,6 @@
#page(flip: true) #page(flip: true)
Wide Wide
// Test changing the layouting directions of pages.
#page(height: 50pt, main-dir: btt, cross-dir: rtl)
Right to left!
--- ---
// Test a combination of pages with bodies and normal content. // Test a combination of pages with bodies and normal content.

View File

@ -16,10 +16,3 @@ Relative #h(100%) spacing
// Missing spacing. // Missing spacing.
// Error: 12 missing argument: spacing // Error: 12 missing argument: spacing
Totally #h() ignored Totally #h() ignored
// Swapped axes.
#page(main-dir: rtl, cross-dir: ttb, height: 80pt)[
1 #h(1cm) 2
3 #v(1cm) 4 #v(-1cm) 5
]