oxedyne/fe2o3/fe2o3_austenite/src/flow/page.rs
24.5 KiB, 80 runs
created by r1870400018:63532, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Original work copyright (c) the Typst project authors (typst-layout `pages/*`, version 0.15.1). |
| 3 | // Modified for Austenite: ported to Hematite's types, IR and error handling. |
| 4 | // U6b owns this file: the document's top level as pages, one page at a time, honouring `pagebreak(weak:, |
| 5 | // to:)`. The driver's `place_page` takes each page's body as it comes. |
| 6 | // |
| 7 | // A port of Typst 0.15.1's `typst-layout` pages (`pages/{mod,collect,run}.rs`), Apache-2.0, (c) the Typst |
| 8 | // authors, streamed. Typst slices the realised document at its page breaks into runs of uniform page |
| 9 | // styles and flows each run through pages of its size as the page's root flow (which hosts footnotes). |
| 10 | // Here the slicing is a pull: [`Level`] reads the realised pairs in order with a bounded lookahead, a run |
| 11 | // is an open feed into a [`FlowCursor`] that stops at the next page break, and the [`Paginator`] yields |
| 12 | // one [`PageBody`] per call. Nothing spans a run: no run, page or pair list is held beyond the page being |
| 13 | // laid and the pairs pending at a break. A `pagebreak(to:)` becomes a blank page when the page count so |
| 14 | // far needs one for the parity. Tags that fall between pages wait for the next page's top-left corner, |
| 15 | // or land at the foot of the last page. |
| 16 | // |
| 17 | // The run's page-wide styles (Typst's `Styles::root` of the run's pairs) are taken over the first |
| 18 | // `TRUNK_WINDOW` pairs of the run, so a run of any length opens with a bounded lookahead. Page styles cannot |
| 19 | // differ inside a run, since realisation brackets a change with boundary breaks; only styles such as the |
| 20 | // text size can differ, and a pair beyond the window that drops one of them from the trunk no longer moves it. |
| 21 | |
| 22 | use crate::diag::DiagnosticKind; |
| 23 | use crate::driver::{ |
| 24 | self, |
| 25 | Recorder, |
| 26 | }; |
| 27 | use crate::eval::content::{ |
| 28 | Content, |
| 29 | ElemKind, |
| 30 | }; |
| 31 | use crate::eval::lib::layout as lay; |
| 32 | use crate::eval::locate::Location; |
| 33 | use crate::eval::realise::{ |
| 34 | self, |
| 35 | Pair, |
| 36 | RealiseMode, |
| 37 | Tag, |
| 38 | }; |
| 39 | use crate::eval::styles::{ |
| 40 | StyleChain, |
| 41 | Styles, |
| 42 | }; |
| 43 | use crate::eval::value::{ |
| 44 | Direction, |
| 45 | HAlign, |
| 46 | Paint, |
| 47 | Value, |
| 48 | }; |
| 49 | use crate::eval::Engine; |
| 50 | use crate::flow::block::{ |
| 51 | Feed, |
| 52 | FlowCursor, |
| 53 | FlowMode, |
| 54 | Frame, |
| 55 | Regions, |
| 56 | Rel, |
| 57 | }; |
| 58 | use crate::flow::{ |
| 59 | carry, |
| 60 | decorate, |
| 61 | Parity, |
| 62 | RunSetup, |
| 63 | Slot, |
| 64 | }; |
| 65 | use crate::ir::Sp; |
| 66 | use crate::page::{ |
| 67 | Page, |
| 68 | PageGeometry, |
| 69 | Swap, |
| 70 | }; |
| 71 | use crate::syntax::Span; |
| 72 | use crate::timings::Phase; |
| 73 | |
| 74 | use oxedyne_fe2o3_core::prelude::*; |
| 75 | |
| 76 | use std::cell::RefCell; |
| 77 | use std::collections::{ |
| 78 | HashSet, |
| 79 | VecDeque, |
| 80 | }; |
| 81 | use std::rc::Rc; |
| 82 | use std::sync::Arc; |
| 83 | |
| 84 | const PT_PER_MM: f64 = 72.0 / 25.4; |
| 85 | const A4_WIDTH_MM: f64 = 210.0; |
| 86 | const TRUNK_WINDOW: usize = 1024; // pairs of a run read ahead to find its page-wide styles |
| 87 | |
| 88 | /// One page's body, as the flow leaves it and the driver takes it. |
| 89 | #[derive(Debug)] |
| 90 | pub struct PageBody { |
| 91 | pub setup: Arc<RunSetup>, |
| 92 | pub number: u32, |
| 93 | pub body: Frame, // inside the margins; empty for a parity blank |
| 94 | pub tags: Vec<Tag>, // tags waiting for this page's top-left corner |
| 95 | pub foot: Vec<Tag>, // tags after the last page, which land at its foot |
| 96 | pub run_start: bool, // flow state is canonical here: the run cache's boundary |
| 97 | } |
| 98 | |
| 99 | /// The document's realised pairs and the page-level state that slices them into runs. |
| 100 | #[derive(Debug)] |
| 101 | pub struct Level { |
| 102 | pub(super) src: Source, |
| 103 | pub(super) staged: bool, // a break is owed an empty page if nothing follows it |
| 104 | pub(super) initial: StyleChain, // the styles an empty run takes |
| 105 | pub(super) out: VecDeque<Item>, // items made but not yet handed on |
| 106 | pub(super) finished: bool, |
| 107 | pub(super) open: bool, // a run's pairs are being pulled |
| 108 | pub(super) ended: bool, // the open run has no more pairs |
| 109 | pub(super) held: VecDeque<Pair>, // pairs of the open run cleared to go out |
| 110 | } |
| 111 | |
| 112 | /// Where the realised pairs come from. Interim: the whole document realised at the first pull, then popped |
| 113 | /// from the front, until a pulled `realise::Stream` replaces it. |
| 114 | #[derive(Debug)] |
| 115 | pub(super) enum Source { |
| 116 | Lazy(Content, StyleChain), |
| 117 | Pairs(VecDeque<Pair>), |
| 118 | } |
| 119 | |
| 120 | impl Source { |
| 121 | fn ready(&mut self, engine: &mut Engine) -> Outcome<&mut VecDeque<Pair>> { |
| 122 | if let Source::Lazy(content, styles) = self { |
| 123 | let pairs = res!(realise::realise(engine, content, styles, RealiseMode::Document)); |
| 124 | // What the body realises to, with its contexts resolved and its show rules applied, decides |
| 125 | // whether it sets content, never the content as it was evaluated. |
| 126 | engine.body = Some(realise::sets_content(&pairs)); |
| 127 | *self = Source::Pairs(pairs.into()); |
| 128 | } |
| 129 | match self { |
| 130 | Source::Pairs(q) => Ok(q), |
| 131 | Source::Lazy(..) => Err(err!("The page source was not realised after being readied."; Bug)), |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | /// A piece of the document at page level: Typst's page `Item`. |
| 137 | #[derive(Debug)] |
| 138 | pub(super) enum Item { |
| 139 | Run(StyleChain), // content to lay out on pages of one style, from these initial styles |
| 140 | Pairs(Vec<Pair>, StyleChain), // a run of these pairs alone: tags with a page of their own, or none |
| 141 | Parity(Parity, StyleChain), // a blank page, if the page count needs one for the parity |
| 142 | Tags(Vec<Pair>), // tags between pages, for the next page's corner |
| 143 | } |
| 144 | |
| 145 | impl Level { |
| 146 | fn new(content: &Content, styles: &StyleChain) -> Self { |
| 147 | Self { |
| 148 | src: Source::Lazy(content.clone(), styles.clone()), |
| 149 | staged: true, |
| 150 | initial: styles.clone(), |
| 151 | out: VecDeque::new(), |
| 152 | finished: false, |
| 153 | open: false, |
| 154 | ended: false, |
| 155 | held: VecDeque::new(), |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | /// The next piece of the document: Typst's page `collect`, a step at a time. A strong break with nothing |
| 160 | /// laid out since the last one yields an empty page; the styles after a break are the next run's initial |
| 161 | /// ones, unless it is the boundary break that ends a `set page` scope. |
| 162 | fn next_item(&mut self, engine: &mut Engine) -> Outcome<Option<Item>> { |
| 163 | loop { |
| 164 | if let Some(item) = self.out.pop_front() { |
| 165 | return Ok(Some(item)); |
| 166 | } |
| 167 | if self.finished { |
| 168 | return Ok(None); |
| 169 | } |
| 170 | let q = res!(self.src.ready(engine)); |
| 171 | if q.is_empty() { |
| 172 | self.finished = true; |
| 173 | return Ok(if self.staged { Some(Item::Pairs(Vec::new(), self.initial.clone())) } else { None }); |
| 174 | } |
| 175 | if is_pagebreak(&q[0]) { |
| 176 | let p = match q.pop_front() { |
| 177 | Some(p) => p, |
| 178 | None => return Err(err!("A page break vanished between peeking and taking it."; Bug)), |
| 179 | }; |
| 180 | let strong = !res!(pagebreak_flag(&p, "weak")); |
| 181 | if strong && self.staged { |
| 182 | self.out.push_back(Item::Pairs(Vec::new(), self.initial.clone())); |
| 183 | } |
| 184 | if let Some(parity) = res!(pagebreak_to(&p)) { |
| 185 | self.out.push_back(Item::Parity(parity, p.styles.clone())); |
| 186 | } |
| 187 | if !res!(pagebreak_flag(&p, "boundary")) { |
| 188 | self.initial = p.styles.clone(); |
| 189 | } |
| 190 | self.staged |= strong; |
| 191 | continue; |
| 192 | } |
| 193 | let k = leading_tags(q); |
| 194 | if q.get(k).map(|p| !is_pagebreak(p)).unwrap_or(false) { |
| 195 | // Content before the next break: a run opens here. |
| 196 | self.open = true; |
| 197 | self.ended = false; |
| 198 | self.staged = false; |
| 199 | self.held.clear(); |
| 200 | return Ok(Some(Item::Run(self.initial.clone()))); |
| 201 | } |
| 202 | // Tags only, up to a break or the end. |
| 203 | let nb = leading_breaks(q, k); |
| 204 | let block: Vec<Pair> = q.drain(..k).collect(); |
| 205 | let (stay, go) = migrate(block); |
| 206 | let group = if stay.is_empty() { |
| 207 | if nb > 0 { |
| 208 | reinsert(q, nb, go); |
| 209 | continue; |
| 210 | } |
| 211 | // Unterminated start tags with no break after them stay where they are. |
| 212 | go |
| 213 | } else { |
| 214 | reinsert(q, nb, go); |
| 215 | stay |
| 216 | }; |
| 217 | let mut rest_boundary = true; |
| 218 | for p in q.iter() { |
| 219 | if !(is_pagebreak(p) && res!(pagebreak_flag(p, "boundary"))) { |
| 220 | rest_boundary = false; |
| 221 | break; |
| 222 | } |
| 223 | } |
| 224 | if !(self.staged && rest_boundary) { |
| 225 | return Ok(Some(Item::Tags(group))); |
| 226 | } |
| 227 | self.staged = false; |
| 228 | return Ok(Some(Item::Pairs(group, self.initial.clone()))); |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | /// The page-wide styles of the run that has just opened: the root styles of its first pairs, else |
| 233 | /// the initial ones. |
| 234 | fn run_styles(&mut self, engine: &mut Engine, initial: &StyleChain) -> Outcome<StyleChain> { |
| 235 | let q = res!(self.src.ready(engine)); |
| 236 | let mut chains = Vec::new(); |
| 237 | for p in q.iter().take(TRUNK_WINDOW) { |
| 238 | if is_pagebreak(p) { |
| 239 | break; |
| 240 | } |
| 241 | if !p.is_tag() { |
| 242 | chains.push(&p.styles); |
| 243 | } |
| 244 | } |
| 245 | Ok(root_styles(chains, initial)) |
| 246 | } |
| 247 | |
| 248 | /// The next pair of the open run. Tags that end the run before a break are sorted as Typst's |
| 249 | /// `migrate_unterminated_tags` has it: those that close an element stay, and start tags without their |
| 250 | /// end tags move on, after the break. |
| 251 | pub(crate) fn pull(&mut self, engine: &mut Engine) -> Outcome<Option<Pair>> { |
| 252 | if let Some(p) = self.held.pop_front() { |
| 253 | return Ok(Some(p)); |
| 254 | } |
| 255 | if !self.open || self.ended { |
| 256 | return Ok(None); |
| 257 | } |
| 258 | let q = res!(self.src.ready(engine)); |
| 259 | let k = leading_tags(q); |
| 260 | if q.get(k).map(|p| !is_pagebreak(p)).unwrap_or(false) { |
| 261 | return Ok(q.pop_front()); |
| 262 | } |
| 263 | if k == 0 { |
| 264 | self.ended = true; |
| 265 | return Ok(None); |
| 266 | } |
| 267 | let nb = leading_breaks(q, k); |
| 268 | let block: Vec<Pair> = q.drain(..k).collect(); |
| 269 | let (stay, go) = migrate(block); |
| 270 | reinsert(q, nb, go); |
| 271 | self.held.extend(stay); |
| 272 | self.ended = true; |
| 273 | Ok(self.held.pop_front()) |
| 274 | } |
| 275 | |
| 276 | /// Does the open run have another pair? |
| 277 | pub(crate) fn has_more(&mut self, engine: &mut Engine) -> Outcome<bool> { |
| 278 | if !self.held.is_empty() { |
| 279 | return Ok(true); |
| 280 | } |
| 281 | match res!(self.pull(engine)) { |
| 282 | Some(p) => { |
| 283 | self.held.push_front(p); |
| 284 | Ok(true) |
| 285 | }, |
| 286 | None => Ok(false), |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | /// The count of tags at the front of the queue. |
| 292 | fn leading_tags(q: &VecDeque<Pair>) -> usize { q.iter().take_while(|p| p.is_tag()).count() } |
| 293 | |
| 294 | /// The count of page breaks in the queue from `from` on. |
| 295 | fn leading_breaks(q: &VecDeque<Pair>, from: usize) -> usize { |
| 296 | q.iter().skip(from).take_while(|p| is_pagebreak(p)).count() |
| 297 | } |
| 298 | |
| 299 | /// Puts tags back into the queue after its first `at` pairs. |
| 300 | fn reinsert(q: &mut VecDeque<Pair>, at: usize, tags: Vec<Pair>) { |
| 301 | for (i, t) in tags.into_iter().enumerate() { |
| 302 | q.insert(at + i, t); |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | /// Splits a block of tags that ends a run into those that stay (the end tags, and the start tags whose end |
| 307 | /// tags are in the block) and the unterminated start tags that move after the page breaks that follow. |
| 308 | fn migrate(block: Vec<Pair>) -> (Vec<Pair>, Vec<Pair>) { |
| 309 | let excluded: HashSet<Location> = block.iter().filter_map(|p| match &p.tag { |
| 310 | Some(Tag::End(l)) => Some(*l), |
| 311 | _ => None, |
| 312 | }).collect(); |
| 313 | let (mut stay, mut go) = (Vec::new(), Vec::new()); |
| 314 | for p in block { |
| 315 | match tag_location(&p) { |
| 316 | Some(l) if excluded.contains(&l) => stay.push(p), |
| 317 | _ => go.push(p), |
| 318 | } |
| 319 | } |
| 320 | (stay, go) |
| 321 | } |
| 322 | |
| 323 | /// The open run: its setup, the cursor flowing its pairs, and the regions its pages are laid into. |
| 324 | #[derive(Debug)] |
| 325 | pub(super) struct Active { |
| 326 | pub(super) setup: Arc<RunSetup>, |
| 327 | pub(super) cursor: FlowCursor, |
| 328 | pub(super) regions: Regions, |
| 329 | pub(super) first: bool, |
| 330 | } |
| 331 | |
| 332 | /// The document as pages, one at a time. `next_page` yields each page's body; [`crate::driver::place_page`] |
| 333 | /// places it, and the caller drops it before asking for the next. |
| 334 | #[derive(Debug)] |
| 335 | pub struct Paginator { |
| 336 | pub(super) level: Rc<RefCell<Level>>, |
| 337 | pub(super) span: Span, |
| 338 | pub(super) active: Option<Active>, |
| 339 | pub(super) blank: Option<Arc<RunSetup>>, // a parity blank page owed before the next run |
| 340 | pub(super) count: u32, // pages yielded |
| 341 | pub(super) waiting: Vec<Tag>, // tags between pages, for the next page's corner |
| 342 | pub(super) started: bool, |
| 343 | pub(super) ended: bool, |
| 344 | } |
| 345 | |
| 346 | impl Paginator { |
| 347 | pub fn new(content: &Content, styles: &StyleChain) -> Self { |
| 348 | Self { |
| 349 | level: Rc::new(RefCell::new(Level::new(content, styles))), |
| 350 | span: content.span(), |
| 351 | active: None, |
| 352 | blank: None, |
| 353 | count: 0, |
| 354 | waiting: Vec::new(), |
| 355 | started: false, |
| 356 | ended: false, |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | /// The next page's body, or `None` after the last page. Under `--timings` it also records the carry state |
| 361 | /// the page began in and the pairs it took (see [`carry`]). |
| 362 | pub fn next_page(&mut self, engine: &mut Engine) -> Outcome<Option<PageBody>> { |
| 363 | if engine.timings.is_none() { |
| 364 | return self.page(engine); |
| 365 | } |
| 366 | let entry = engine.timed(Phase::Probe, |engine| { |
| 367 | if let Some(t) = engine.timings.as_mut() { |
| 368 | t.take_seen(); |
| 369 | } |
| 370 | carry::entry(self, &engine.locator) |
| 371 | }); |
| 372 | let page = res!(self.page(engine)); |
| 373 | if let Some(body) = &page { |
| 374 | engine.timed(Phase::Probe, |engine| { |
| 375 | if let Some(t) = engine.timings.as_mut() { |
| 376 | let seen = t.take_seen(); |
| 377 | t.page(carry::record(&body.setup, &seen, entry)); |
| 378 | } |
| 379 | }); |
| 380 | } |
| 381 | Ok(page) |
| 382 | } |
| 383 | |
| 384 | fn page(&mut self, engine: &mut Engine) -> Outcome<Option<PageBody>> { |
| 385 | if !self.started { |
| 386 | self.started = true; |
| 387 | res!(self.advance(engine)); |
| 388 | } |
| 389 | if let Some(setup) = self.blank.take() { |
| 390 | self.count += 1; |
| 391 | let body = blank_area(&setup); |
| 392 | let mut page = PageBody { |
| 393 | setup, |
| 394 | number: self.count, |
| 395 | body, |
| 396 | tags: std::mem::take(&mut self.waiting), |
| 397 | foot: Vec::new(), |
| 398 | run_start: true, |
| 399 | }; |
| 400 | res!(self.advance(engine)); |
| 401 | self.land_foot(&mut page); |
| 402 | return Ok(Some(page)); |
| 403 | } |
| 404 | let (mut page, done) = match &mut self.active { |
| 405 | None => return Ok(None), |
| 406 | Some(a) => { |
| 407 | let frame = res!(a.cursor.region(engine, &a.regions)); |
| 408 | self.count += 1; |
| 409 | let page = PageBody { |
| 410 | setup: a.setup.clone(), |
| 411 | number: self.count, |
| 412 | body: frame, |
| 413 | tags: std::mem::take(&mut self.waiting), |
| 414 | foot: Vec::new(), |
| 415 | run_start: a.first, |
| 416 | }; |
| 417 | a.first = false; |
| 418 | (page, res!(a.cursor.is_done(engine))) |
| 419 | }, |
| 420 | }; |
| 421 | if done { |
| 422 | self.active = None; |
| 423 | res!(self.advance(engine)); |
| 424 | self.land_foot(&mut page); |
| 425 | } |
| 426 | Ok(Some(page)) |
| 427 | } |
| 428 | |
| 429 | /// The next page placed: its furniture laid out ([`decorate::decorate_page`]) and its body put on its page |
| 430 | /// by [`driver::place_page`], the located elements they hold going to `rec`, with the setup of its run. |
| 431 | pub fn next_placed<R: Recorder>(&mut self, engine: &mut Engine, rec: &mut R) |
| 432 | -> Outcome<Option<(Page, Arc<RunSetup>)>> |
| 433 | { |
| 434 | match res!(engine.timed(Phase::Flow, |engine| self.next_page(engine))) { |
| 435 | None => Ok(None), |
| 436 | Some(body) => { |
| 437 | let setup = body.setup.clone(); |
| 438 | let marginals = res!(engine.timed(Phase::Decorate, |engine| |
| 439 | decorate::decorate_page(engine, &setup, (body.body.w, body.body.h)))); |
| 440 | let page = res!(engine.timed(Phase::Place, |_| driver::place_page(body, marginals, rec))); |
| 441 | Ok(Some((page, setup))) |
| 442 | }, |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | /// Tags still waiting once no page follows land at the foot of the page just made. |
| 447 | fn land_foot(&mut self, page: &mut PageBody) { |
| 448 | if self.ended && self.active.is_none() && self.blank.is_none() { |
| 449 | page.foot = std::mem::take(&mut self.waiting); |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | /// Takes the page-level pieces that follow the run just finished, up to the next that makes a page. |
| 454 | fn advance(&mut self, engine: &mut Engine) -> Outcome<()> { |
| 455 | loop { |
| 456 | let item = res!(self.level.borrow_mut().next_item(engine)); |
| 457 | match item { |
| 458 | None => { |
| 459 | self.ended = true; |
| 460 | return Ok(()); |
| 461 | }, |
| 462 | Some(Item::Run(initial)) => { |
| 463 | let styles = res!(self.level.borrow_mut().run_styles(engine, &initial)); |
| 464 | let feed = Feed::Run(self.level.clone()); |
| 465 | return self.open(engine, feed, styles); |
| 466 | }, |
| 467 | Some(Item::Pairs(pairs, initial)) => { |
| 468 | let styles = styles_of(&pairs, &initial); |
| 469 | return self.open(engine, Feed::list(pairs), styles); |
| 470 | }, |
| 471 | Some(Item::Parity(parity, styles)) => { |
| 472 | if parity_wants_blank(parity, self.count) { |
| 473 | let setup = res!(PageSetup::of(engine, &styles, self.span)); |
| 474 | self.blank = Some(Arc::new(setup.run(styles))); |
| 475 | return Ok(()); |
| 476 | } |
| 477 | }, |
| 478 | Some(Item::Tags(pairs)) => { |
| 479 | self.waiting.extend(pairs.into_iter().filter_map(|p| p.tag)); |
| 480 | }, |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | /// Opens a run of pages: its setup, and a cursor over `feed` as the root flow of its area. |
| 486 | fn open(&mut self, engine: &mut Engine, feed: Feed, styles: StyleChain) -> Outcome<()> { |
| 487 | let setup = res!(PageSetup::of(engine, &styles, self.span)); |
| 488 | let (aw, ah) = setup.area; |
| 489 | let regions = Regions::repeat(aw, ah, aw.is_finite(), ah.is_finite()); |
| 490 | let cursor = res!(FlowCursor::new( |
| 491 | engine, feed, &styles, ®ions, setup.columns, setup.gutter, FlowMode::Root, self.span)); |
| 492 | self.active = Some(Active { setup: Arc::new(setup.run(styles)), cursor, regions, first: true }); |
| 493 | Ok(()) |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | /// A parity blank page's body, the size of its run's area as Typst's flow makes it, so the furniture of a |
| 498 | /// blank page spans the page; nothing where the page fits its content. |
| 499 | fn blank_area(setup: &RunSetup) -> Frame { |
| 500 | let g = &setup.geom; |
| 501 | match (g.width == Sp::ZERO, g.height == Sp::ZERO) { |
| 502 | (false, false) => Frame::new(g.content_width().to_pt(), g.content_height().to_pt()), |
| 503 | (false, true) => Frame::new(g.content_width().to_pt(), 0.0), |
| 504 | (true, false) => Frame::new(0.0, g.content_height().to_pt()), |
| 505 | (true, true) => Frame::new(0.0, 0.0), |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | /// The page-wide styles of a run held as pairs: the trunk of its contentful pairs' styles, else the initial |
| 510 | /// ones. |
| 511 | fn styles_of(pairs: &[Pair], initial: &StyleChain) -> StyleChain { |
| 512 | root_styles(pairs.iter().filter(|p| !p.is_tag()).map(|p| &p.styles), initial) |
| 513 | } |
| 514 | |
| 515 | /// The styles page furniture and footnote entries take: Typst's `Styles::root` of the run's pairs, which |
| 516 | /// keeps only the outside styles that were in force where the run began or that a set rule could lift, never |
| 517 | /// those a show rule or a call such as `text(size: ..)[..]` put on its own content. |
| 518 | fn root_styles<'a, I: IntoIterator<Item = &'a StyleChain>>(chains: I, initial: &StyleChain) -> StyleChain { |
| 519 | StyleChain::root().chain(&Styles::root(chains, initial)) |
| 520 | } |
| 521 | |
| 522 | /// Does a `pagebreak(to: parity)` after `count` pages need a blank page first? Typst adds one when the |
| 523 | /// count itself has the parity asked of the next page's predecessor: `to: odd` after an odd count. |
| 524 | fn parity_wants_blank(parity: Parity, count: u32) -> bool { |
| 525 | match parity { |
| 526 | Parity::Even => count % 2 == 0, |
| 527 | Parity::Odd => count % 2 == 1, |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | fn is_pagebreak(p: &Pair) -> bool { !p.is_tag() && p.content.is(ElemKind::Pagebreak) } |
| 532 | |
| 533 | fn pagebreak_field(p: &Pair, name: &str) -> Outcome<Option<Value>> { |
| 534 | match ElemKind::Pagebreak.field_id(name) { |
| 535 | Some(id) => p.styles.resolve(&p.content, id), |
| 536 | None => Ok(None), |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | fn pagebreak_flag(p: &Pair, name: &str) -> Outcome<bool> { |
| 541 | Ok(matches!(res!(pagebreak_field(p, name)), Some(Value::Bool(true)))) |
| 542 | } |
| 543 | |
| 544 | fn pagebreak_to(p: &Pair) -> Outcome<Option<Parity>> { |
| 545 | Ok(match res!(pagebreak_field(p, "to")) { |
| 546 | Some(Value::Str(s)) if s.as_str() == "odd" => Some(Parity::Odd), |
| 547 | Some(Value::Str(s)) if s.as_str() == "even" => Some(Parity::Even), |
| 548 | _ => None, |
| 549 | }) |
| 550 | } |
| 551 | |
| 552 | fn tag_location(p: &Pair) -> Option<crate::eval::locate::Location> { |
| 553 | match &p.tag { |
| 554 | Some(Tag::Start(c)) => c.location(), |
| 555 | Some(Tag::End(l)) => Some(*l), |
| 556 | None => None, |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | // Page runs |
| 561 | |
| 562 | /// A run's page geometry and furniture, from its page-wide styles. |
| 563 | struct PageSetup { |
| 564 | geom: PageGeometry, |
| 565 | area: (f64, f64), // inside the margins; infinite on an axis the page fits to its content |
| 566 | columns: usize, |
| 567 | gutter: Rel, |
| 568 | gutter_pt: f64, |
| 569 | fill: Option<Paint>, |
| 570 | numbering: Value, |
| 571 | header: Slot, |
| 572 | footer: Slot, |
| 573 | background: Option<Content>, |
| 574 | foreground: Option<Content>, |
| 575 | } |
| 576 | |
| 577 | impl PageSetup { |
| 578 | /// Typst's page-run setup: the size (from `paper`, `width`, `height` and `flipped`, `auto` fitting the |
| 579 | /// content), the margins (`auto` is 2.5/21 of the shorter side, of A4's width when both fit), the |
| 580 | /// binding for two-sided margins, the columns and their gutter, and the furniture. |
| 581 | fn of(engine: &mut Engine, styles: &StyleChain, span: Span) -> Outcome<PageSetup> { |
| 582 | let (mut w, mut h) = page_size(styles); |
| 583 | if matches!(res!(page_field(styles, "flipped")), Some(Value::Bool(true))) { |
| 584 | std::mem::swap(&mut w, &mut h); |
| 585 | } |
| 586 | let mut min = w.min(h); |
| 587 | if !min.is_finite() { |
| 588 | min = A4_WIDTH_MM * PT_PER_MM; |
| 589 | } |
| 590 | let default = (2.5 / 21.0) * min; |
| 591 | let margin_v = res!(page_field(styles, "margin")); |
| 592 | let two_sided = matches!(&margin_v, Some(Value::Dict(d)) if d.contains("inside") || d.contains("outside")); |
| 593 | let parts = margin_parts(margin_v); |
| 594 | let side = |i: usize, whole: f64| -> f64 { |
| 595 | match &parts[i] { |
| 596 | None | Some(Value::Auto) => default, |
| 597 | Some(v) => match rel(styles, v) { |
| 598 | Some(r) => r.relative_to(whole), |
| 599 | None => default, |
| 600 | }, |
| 601 | } |
| 602 | }; |
| 603 | let (left, top, right, bottom) = (side(0, w), side(1, h), side(2, w), side(3, h)); |
| 604 | // A bleed extends the page past its trim, which the writers do not draw. |
| 605 | let bleed = margin_parts(res!(page_field(styles, "bleed"))); |
| 606 | if bleed.iter().flatten().any(|v| rel(styles, v).map(|r| !r.is_zero()).unwrap_or(false)) { |
| 607 | engine.warn(DiagnosticKind::Unsupported, span, "page bleed is not drawn"); |
| 608 | } |
| 609 | let dir = match ElemKind::Text.field_id("dir") { |
| 610 | Some(id) => res!(styles.get(ElemKind::Text, id)), |
| 611 | None => None, |
| 612 | }; |
| 613 | let binding_left = match res!(page_field(styles, "binding")) { |
| 614 | Some(Value::Alignment(a)) => !matches!(a.x, Some(HAlign::Right)), |
| 615 | _ => !matches!(dir, Some(Value::Direction(Direction::Rtl))), |
| 616 | }; |
| 617 | let swap = match (two_sided, binding_left) { |
| 618 | (false, _) => Swap::None, |
| 619 | (true, true) => Swap::Even, |
| 620 | (true, false) => Swap::Odd, |
| 621 | }; |
| 622 | let fit = |v: f64| if v.is_finite() { Sp::from_pt(v) } else { Sp::ZERO }; |
| 623 | let mut geom = PageGeometry::with_margins( |
| 624 | fit(w), fit(h), Sp::from_pt(left), Sp::from_pt(right), Sp::from_pt(top), Sp::from_pt(bottom)); |
| 625 | geom.swap = swap; |
| 626 | let columns = match res!(page_field(styles, "columns")) { |
| 627 | Some(Value::Int(n)) if n > 0 => n as usize, |
| 628 | _ => 1, |
| 629 | }; |
| 630 | let gutter_v = match ElemKind::Columns.field_id("gutter") { |
| 631 | Some(id) => res!(styles.get(ElemKind::Columns, id)), |
| 632 | None => None, |
| 633 | }; |
| 634 | let gutter = gutter_v.and_then(|v| rel(styles, &v)).unwrap_or(Rel { ratio: 0.04, abs: 0.0 }); |
| 635 | let area = (w - left - right, h - top - bottom); |
| 636 | let fill = match res!(page_field(styles, "fill")) { |
| 637 | Some(v) if !matches!(v, Value::None | Value::Auto) => res!(crate::eval::lib::visual::fill_of(&v)), |
| 638 | _ => None, |
| 639 | }; |
| 640 | let content = |name: &str| -> Outcome<Option<Content>> { |
| 641 | match res!(page_field(styles, name)) { |
| 642 | None | Some(Value::None) | Some(Value::Auto) => Ok(None), |
| 643 | Some(v) => Ok(Some(res!(v.cast::<Content>()))), |
| 644 | } |
| 645 | }; |
| 646 | // A header or footer left `auto` is the page numbering's, and `none` clears it. |
| 647 | let slot = |name: &str| -> Outcome<Slot> { |
| 648 | match res!(page_field(styles, name)) { |
| 649 | None | Some(Value::Auto) => Ok(Slot::Auto), |
| 650 | Some(Value::None) => Ok(Slot::Off), |
| 651 | Some(v) => Ok(Slot::On(res!(v.cast::<Content>()))), |
| 652 | } |
| 653 | }; |
| 654 | Ok(PageSetup { |
| 655 | geom, |
| 656 | area, |
| 657 | columns, |
| 658 | gutter, |
| 659 | gutter_pt: gutter.relative_to(area.0), |
| 660 | fill, |
| 661 | numbering: res!(page_field(styles, "numbering")).unwrap_or(Value::None), |
| 662 | header: res!(slot("header")), |
| 663 | footer: res!(slot("footer")), |
| 664 | background: res!(content("background")), |
| 665 | foreground: res!(content("foreground")), |
| 666 | }) |
| 667 | } |
| 668 | |
| 669 | fn run(&self, styles: StyleChain) -> RunSetup { |
| 670 | RunSetup { |
| 671 | geom: self.geom, |
| 672 | columns: self.columns, |
| 673 | gutter: if self.gutter_pt.is_finite() { Sp::from_pt(self.gutter_pt) } else { Sp::ZERO }, |
| 674 | fill: self.fill.clone(), |
| 675 | numbering: self.numbering.clone(), |
| 676 | header: self.header.clone(), |
| 677 | footer: self.footer.clone(), |
| 678 | background: self.background.clone(), |
| 679 | foreground: self.foreground.clone(), |
| 680 | styles, |
| 681 | } |
| 682 | } |
| 683 | } |
| 684 | |
| 685 | /// A `page` field as the chain has it. |
| 686 | pub(crate) fn page_field(styles: &StyleChain, name: &str) -> Outcome<Option<Value>> { |
| 687 | match ElemKind::Page.field_id(name) { |
| 688 | Some(id) => styles.get(ElemKind::Page, id), |
| 689 | None => Ok(None), |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | /// The page's width and height in points, infinite for `auto`. |
| 694 | fn page_size(styles: &StyleChain) -> (f64, f64) { |
| 695 | let (w, h) = lay::page_dims(styles); |
| 696 | (length_or_inf(styles, &w), length_or_inf(styles, &h)) |
| 697 | } |
| 698 | |
| 699 | fn length_or_inf(styles: &StyleChain, v: &Value) -> f64 { |
| 700 | match v { |
| 701 | Value::Length(l) => styles.resolve_length(*l), |
| 702 | _ => f64::INFINITY, |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | pub(crate) fn rel(styles: &StyleChain, v: &Value) -> Option<Rel> { |
| 707 | match v { |
| 708 | Value::Length(l) => Some(Rel::pt(styles.resolve_length(*l))), |
| 709 | Value::Ratio(r) => Some(Rel { ratio: r.0, abs: 0.0 }), |
| 710 | Value::Relative(r) => Some(Rel { ratio: r.rel.0, abs: styles.resolve_length(r.abs) }), |
| 711 | _ => None, |
| 712 | } |
| 713 | } |
| 714 | |
| 715 | /// A margin's four sides (left or inside, top, right or outside, bottom), each possibly unset or `auto`, |
| 716 | /// by Typst's precedence of a side over its axis over `rest`. |
| 717 | fn margin_parts(v: Option<Value>) -> [Option<Value>; 4] { |
| 718 | match v { |
| 719 | None | Some(Value::Auto) | Some(Value::None) => [None, None, None, None], |
| 720 | Some(Value::Dict(d)) => { |
| 721 | let get = |k: &str| d.get(k).cloned(); |
| 722 | let rest = get("rest"); |
| 723 | let x = get("x").or_else(|| rest.clone()); |
| 724 | let y = get("y").or_else(|| rest.clone()); |
| 725 | [ |
| 726 | get("inside").or_else(|| get("left")).or_else(|| x.clone()), |
| 727 | get("top").or_else(|| y.clone()), |
| 728 | get("outside").or_else(|| get("right")).or_else(|| x.clone()), |
| 729 | get("bottom").or_else(|| y.clone()), |
| 730 | ] |
| 731 | }, |
| 732 | Some(other) => [Some(other.clone()), Some(other.clone()), Some(other.clone()), Some(other)], |
| 733 | } |
| 734 | } |