summaryrefslogtreecommitdiff
path: root/src/model
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2022-05-26 11:59:53 +0200
committerLaurenz <laurmaedje@gmail.com>2022-05-26 11:59:53 +0200
commit66d8f4569a9f13270c5f477e0730f127a22333e2 (patch)
treeebb60254e69d7f65ec2245aeae3543f6efff0cbb /src/model
parent99cb655832161d4ebec73273a15453a8f6acc1b7 (diff)
Locate me!
Diffstat (limited to 'src/model')
-rw-r--r--src/model/content.rs50
-rw-r--r--src/model/layout.rs14
-rw-r--r--src/model/locate.rs125
-rw-r--r--src/model/mod.rs2
-rw-r--r--src/model/recipe.rs20
5 files changed, 195 insertions, 16 deletions
diff --git a/src/model/content.rs b/src/model/content.rs
index c09979d5..effe84ae 100644
--- a/src/model/content.rs
+++ b/src/model/content.rs
@@ -7,8 +7,8 @@ use std::ops::{Add, AddAssign};
use typed_arena::Arena;
use super::{
- Barrier, CollapsingBuilder, Interruption, Key, Layout, LayoutNode, Property, Show,
- ShowNode, StyleEntry, StyleMap, StyleVecBuilder, Target,
+ Barrier, CollapsingBuilder, Interruption, Key, Layout, LayoutNode, LocateNode,
+ Property, Show, ShowNode, StyleEntry, StyleMap, StyleVecBuilder, Target,
};
use crate::diag::StrResult;
use crate::library::layout::{FlowChild, FlowNode, PageNode, PlaceNode, Spacing};
@@ -20,7 +20,35 @@ use crate::library::text::{
use crate::util::EcoString;
/// Layout content into a collection of pages.
+///
+/// Relayouts until all pinned locations are converged.
pub fn layout(ctx: &mut Context, content: &Content) -> TypResult<Vec<Arc<Frame>>> {
+ let mut pass = 0;
+ let mut frames;
+
+ loop {
+ let prev = ctx.pins.clone();
+ let result = layout_once(ctx, content);
+ ctx.pins.reset();
+ frames = result?;
+ pass += 1;
+
+ ctx.pins.locate(&frames);
+
+ let count = ctx.pins.len();
+ let resolved = ctx.pins.resolved(&prev);
+
+ // Quit if we're done or if we've had five passes.
+ if resolved == count || pass >= 5 {
+ break;
+ }
+ }
+
+ Ok(frames)
+}
+
+/// Layout content into a collection of pages once.
+fn layout_once(ctx: &mut Context, content: &Content) -> TypResult<Vec<Arc<Frame>>> {
let copy = ctx.config.styles.clone();
let styles = StyleChain::with_root(&copy);
let scratch = Scratch::default();
@@ -88,6 +116,10 @@ pub enum Content {
/// A node that can be realized with styles, optionally with attached
/// properties.
Show(ShowNode, Option<Dict>),
+ /// A node that can be realized with its location on the page.
+ Locate(LocateNode),
+ /// A pin identified by index.
+ Pin(usize),
/// Content with attached styles.
Styled(Arc<(Self, StyleMap)>),
/// A sequence of multiple nodes.
@@ -272,6 +304,8 @@ impl Debug for Content {
Self::Pagebreak { weak } => write!(f, "Pagebreak({weak})"),
Self::Page(page) => page.fmt(f),
Self::Show(node, _) => node.fmt(f),
+ Self::Locate(node) => node.fmt(f),
+ Self::Pin(idx) => write!(f, "Pin({idx})"),
Self::Styled(styled) => {
let (sub, map) = styled.as_ref();
map.fmt(f)?;
@@ -388,6 +422,7 @@ impl<'a, 'ctx> Builder<'a, 'ctx> {
}
Content::Show(node, _) => return self.show(node, styles),
+ Content::Locate(node) => return self.locate(node, styles),
Content::Styled(styled) => return self.styled(styled, styles),
Content::Sequence(seq) => return self.sequence(seq, styles),
@@ -436,6 +471,12 @@ impl<'a, 'ctx> Builder<'a, 'ctx> {
Ok(())
}
+ fn locate(&mut self, node: &LocateNode, styles: StyleChain<'a>) -> TypResult<()> {
+ let realized = node.realize(self.ctx)?;
+ let stored = self.scratch.templates.alloc(realized);
+ self.accept(stored, styles)
+ }
+
fn styled(
&mut self,
(content, map): &'a (Content, StyleMap),
@@ -641,6 +682,9 @@ impl<'a> ParBuilder<'a> {
Content::Inline(node) => {
self.0.supportive(ParChild::Node(node.clone()), styles);
}
+ &Content::Pin(idx) => {
+ self.0.ignorant(ParChild::Pin(idx), styles);
+ }
_ => return false,
}
@@ -660,7 +704,7 @@ impl<'a> ParBuilder<'a> {
&& children
.items()
.find_map(|child| match child {
- ParChild::Spacing(_) => None,
+ ParChild::Spacing(_) | ParChild::Pin(_) => None,
ParChild::Text(_) | ParChild::Quote { .. } => Some(true),
ParChild::Node(_) => Some(false),
})
diff --git a/src/model/layout.rs b/src/model/layout.rs
index 6dfbcb90..49720be4 100644
--- a/src/model/layout.rs
+++ b/src/model/layout.rs
@@ -221,13 +221,19 @@ impl Layout for LayoutNode {
regions: &Regions,
styles: StyleChain,
) -> TypResult<Vec<Arc<Frame>>> {
- crate::memo::memoized(
- (self, ctx, regions, styles),
+ let (result, cursor) = crate::memo::memoized(
+ (self, &mut *ctx, regions, styles),
|(node, ctx, regions, styles)| {
let entry = StyleEntry::Barrier(Barrier::new(node.id()));
- node.0.layout(ctx, regions, entry.chain(&styles))
+ let result = node.0.layout(ctx, regions, entry.chain(&styles));
+ (result, ctx.pins.cursor())
},
- )
+ );
+
+ // Replay the side effect in case of caching. This should currently be
+ // more or less the only relevant side effect on the context.
+ ctx.pins.jump(cursor);
+ result
}
fn pack(self) -> LayoutNode {
diff --git a/src/model/locate.rs b/src/model/locate.rs
new file mode 100644
index 00000000..9b0d13e7
--- /dev/null
+++ b/src/model/locate.rs
@@ -0,0 +1,125 @@
+use std::sync::Arc;
+
+use super::Content;
+use crate::diag::TypResult;
+use crate::eval::{Args, Func, Value};
+use crate::frame::{Element, Frame};
+use crate::geom::{Point, Transform};
+use crate::syntax::Spanned;
+use crate::Context;
+
+/// A node that can realize itself with its own location.
+#[derive(Debug, Clone, PartialEq, Hash)]
+pub struct LocateNode(Spanned<Func>);
+
+impl LocateNode {
+ /// Create a new locate node.
+ pub fn new(recipe: Spanned<Func>) -> Self {
+ Self(recipe)
+ }
+
+ /// Realize the node.
+ pub fn realize(&self, ctx: &mut Context) -> TypResult<Content> {
+ let idx = ctx.pins.cursor();
+ let location = ctx.pins.next();
+ let dict = dict! {
+ "page" => Value::Int(location.page as i64),
+ "x" => Value::Length(location.pos.x.into()),
+ "y" => Value::Length(location.pos.y.into()),
+ };
+
+ let args = Args::new(self.0.span, [Value::Dict(dict)]);
+ Ok(Content::Pin(idx) + self.0.v.call_detached(ctx, args)?.display())
+ }
+}
+
+/// Manages ordered pins.
+#[derive(Debug, Clone, PartialEq, Hash)]
+pub struct PinBoard {
+ /// All currently pinned locations.
+ pins: Vec<Location>,
+ /// The index of the next pin in order.
+ cursor: usize,
+}
+
+impl PinBoard {
+ /// Create an empty pin board.
+ pub fn new() -> Self {
+ Self { pins: vec![], cursor: 0 }
+ }
+
+ /// The number of pins on the board.
+ pub fn len(&self) -> usize {
+ self.pins.len()
+ }
+
+ /// How many pins are resolved in comparison to an earlier snapshot.
+ pub fn resolved(&self, prev: &Self) -> usize {
+ self.pins.iter().zip(&prev.pins).filter(|(a, b)| a == b).count()
+ }
+
+ /// Access the next pin location.
+ pub fn next(&mut self) -> Location {
+ let cursor = self.cursor;
+ self.jump(self.cursor + 1);
+ self.pins[cursor]
+ }
+
+ /// The current cursor.
+ pub fn cursor(&self) -> usize {
+ self.cursor
+ }
+
+ /// Set the current cursor.
+ pub fn jump(&mut self, cursor: usize) {
+ if cursor >= self.pins.len() {
+ let loc = self.pins.last().copied().unwrap_or_default();
+ self.pins.resize(cursor + 1, loc);
+ }
+ self.cursor = cursor;
+ }
+
+ /// Reset the cursor and remove all unused pins.
+ pub fn reset(&mut self) {
+ self.pins.truncate(self.cursor);
+ self.cursor = 0;
+ }
+
+ /// Locate all pins in the frames.
+ pub fn locate(&mut self, frames: &[Arc<Frame>]) {
+ for (i, frame) in frames.iter().enumerate() {
+ self.locate_impl(1 + i, frame, Transform::identity());
+ }
+ }
+
+ /// Locate all pins in a frame.
+ fn locate_impl(&mut self, page: usize, frame: &Frame, ts: Transform) {
+ for &(pos, ref element) in &frame.elements {
+ match element {
+ Element::Group(group) => {
+ let ts = ts
+ .pre_concat(Transform::translate(pos.x, pos.y))
+ .pre_concat(group.transform);
+ self.locate_impl(page, &group.frame, ts);
+ }
+
+ Element::Pin(idx) => {
+ let pin = &mut self.pins[*idx];
+ pin.page = page;
+ pin.pos = pos.transform(ts);
+ }
+
+ _ => {}
+ }
+ }
+ }
+}
+
+/// A physical location in a document.
+#[derive(Debug, Default, Copy, Clone, PartialEq, Hash)]
+pub struct Location {
+ /// The page, starting at 1.
+ pub page: usize,
+ /// The exact coordinates on the page (from the top left, as usual).
+ pub pos: Point,
+}
diff --git a/src/model/mod.rs b/src/model/mod.rs
index 5c8b82c0..379b633f 100644
--- a/src/model/mod.rs
+++ b/src/model/mod.rs
@@ -5,6 +5,7 @@ mod styles;
mod collapse;
mod content;
mod layout;
+mod locate;
mod property;
mod recipe;
mod show;
@@ -12,6 +13,7 @@ mod show;
pub use collapse::*;
pub use content::*;
pub use layout::*;
+pub use locate::*;
pub use property::*;
pub use recipe::*;
pub use show::*;
diff --git a/src/model/recipe.rs b/src/model/recipe.rs
index e4417adf..6261e704 100644
--- a/src/model/recipe.rs
+++ b/src/model/recipe.rs
@@ -4,7 +4,7 @@ use super::{Content, Interruption, NodeId, Show, ShowNode, StyleChain, StyleEntr
use crate::diag::TypResult;
use crate::eval::{Args, Func, Regex, Value};
use crate::library::structure::{EnumNode, ListNode};
-use crate::syntax::Span;
+use crate::syntax::Spanned;
use crate::Context;
/// A show rule recipe.
@@ -13,9 +13,7 @@ pub struct Recipe {
/// The patterns to customize.
pub pattern: Pattern,
/// The function that defines the recipe.
- pub func: Func,
- /// The span to report all erros with.
- pub span: Span,
+ pub func: Spanned<Func>,
}
impl Recipe {
@@ -81,13 +79,13 @@ impl Recipe {
where
F: FnOnce() -> Value,
{
- let args = if self.func.argc() == Some(0) {
- Args::new(self.span, [])
+ let args = if self.func.v.argc() == Some(0) {
+ Args::new(self.func.span, [])
} else {
- Args::new(self.span, [arg()])
+ Args::new(self.func.span, [arg()])
};
- Ok(self.func.call_detached(ctx, args)?.display())
+ Ok(self.func.v.call_detached(ctx, args)?.display())
}
/// What kind of structure the property interrupts.
@@ -104,7 +102,11 @@ impl Recipe {
impl Debug for Recipe {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- write!(f, "Recipe matching {:?} from {:?}", self.pattern, self.span)
+ write!(
+ f,
+ "Recipe matching {:?} from {:?}",
+ self.pattern, self.func.span
+ )
}
}