Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/flow/par.rs

15.2 KiB, 51 runs

created by r1870400018:63534, 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 `inline/{mod,finalize}.rs`, version 0.15.1).
3// Modified for Austenite: ported to Hematite's types, IR and error handling.
4// U6a owns this file: a paragraph's realised children into justified lines through `linebreak.rs`, with
5// Typst's `par` settings (leading, spacing, justify, first-line-indent, hanging-indent, linebreaks).
6//
7// The configuration and the finishing of lines follow Typst 0.15.1's `typst-layout/src/inline/{mod,
8// finalize}.rs` (Apache-2.0, (c) the Typst project authors): `linebreaks: auto` is optimised when the
9// paragraph justifies and simple otherwise, `hyphenate: auto` follows `justify`, a first-line indent
10// applies after another paragraph (or everywhere with `all: true`, never to a first paragraph inside a
11// list), and a paragraph fills its region's width unless it may shrink to its longest line.
12
13use crate::caches::PAR_BUDGET;
14use crate::eval::content::{
15 Content,
16 ElemKind,
17};
18use crate::eval::lib::model::list::in_list;
19use crate::eval::realise::{
20 realise,
21 Pair,
22 RealiseMode,
23};
24use crate::eval::styles::StyleChain;
25use crate::eval::value::Value;
26use crate::eval::Engine;
27use crate::flow::inline::{
28 commit,
29 fixed_align,
30 keepable,
31 lang_of,
32 Keep,
33 prepare,
34 Config,
35 Frame,
36 LineBox,
37 Linebreaks,
38 ParSituation,
39};
40use crate::flow::text::{
41 self as ftext,
42 elem_field,
43 text_field,
44};
45use crate::flow::Region;
46use crate::ir::{
47 Glue,
48 Node,
49 Penalty,
50 Sp,
51};
52use crate::linebreak::{
53 linebreak,
54 rebuild,
55 LineEnd,
56};
57
58use oxedyne_fe2o3_core::prelude::*;
59use oxedyne_fe2o3_data::gen_map::GenMap;
60use oxedyne_fe2o3_hash::fingerprint::Fingerprint;
61use oxedyne_fe2o3_hash::fingerprint::Fingerprinter;
62
63use std::sync::Arc;
64
65/// The `par` settings an inline layout starts from: a paragraph's own, or the chain's for inline content
66/// that is not a paragraph.
67#[derive(Clone, Debug)]
68pub struct ConfigBase {
69 pub justify: bool,
70 pub linebreaks: Option<Linebreaks>, // `auto` as `None`
71 pub first_line_indent: (f64, bool), // amount in points, and whether it applies to all
72 pub hanging_indent: f64,
73}
74
75/// Sets a `par` element, Typst's `layout_par`: its body realised in `Inline` mode, broken into lines
76/// under its own fields folded onto the chain, and the lines stacked its `leading` apart. `situation` is
77/// where the flow met the paragraph, which decides the first-line indent.
78///
79/// The lines depend only on the paragraph, its chain, `region` (the width, and the base and height that
80/// relative and fractional inline boxes resolve against), `situation` and the faces of `engine.fonts`; an
81/// inline box or equation inside may also read the introspector, take locations and warn, through
82/// `engine`, as any layout does. [`layout_with`] keeps the breaks of a paragraph that does none of that.
83pub fn layout_par(
84 engine: &mut Engine,
85 par: &Content,
86 styles: &StyleChain,
87 region: Region,
88 situation: ParSituation,
89)
90 -> Outcome<Vec<Node>>
91{
92 let body = match par.kind().and_then(|k| k.field_id("body")).and_then(|id| par.get(id)) {
93 Some(Value::Content(c)) => c.clone(),
94 _ => Content::empty(),
95 };
96 let children = res!(realise(engine, &body, styles, RealiseMode::Inline));
97 let base = res!(base_of(styles, Some(par)));
98 let lines = res!(layout_with(engine, &children, styles, region, region.expand_x, Some(situation), &base));
99 let leading = match res!(par_value(styles, Some(par), "leading")) {
100 Some(Value::Length(l)) => l.resolve(styles.font_size()),
101 _ => 0.65 * styles.font_size(),
102 };
103 stack_with(styles, lines, leading)
104}
105
106/// Inline content that is not a paragraph -- a container's body that is inline only -- as lines with no
107/// first-line or hanging indent, filling the region only when `expand`: Typst's `layout_inline`.
108pub fn layout_lines(
109 engine: &mut Engine,
110 children: &[Pair],
111 styles: &StyleChain,
112 region: Region,
113 expand: bool,
114)
115 -> Outcome<Vec<LineBox>>
116{
117 let base = res!(base_of(styles, None));
118 layout_with(engine, children, styles, region, expand, None, &base)
119}
120
121/// As [`layout_lines`], stacked `par.leading` apart.
122pub fn layout_inline(
123 engine: &mut Engine,
124 children: &[Pair],
125 styles: &StyleChain,
126 region: Region,
127 expand: bool,
128)
129 -> Outcome<Vec<Node>>
130{
131 let lines = res!(layout_lines(engine, children, styles, region, expand));
132 stack(styles, lines)
133}
134
135/// A `par` field from the element when given, else the chain.
136fn par_value(styles: &StyleChain, par: Option<&Content>, name: &str) -> Outcome<Option<Value>> {
137 match (par, ElemKind::Par.field_id(name)) {
138 (Some(p), Some(id)) => styles.resolve(p, id),
139 (None, Some(id)) => styles.get(ElemKind::Par, id),
140 (_, None) => Ok(None),
141 }
142}
143
144fn base_of(styles: &StyleChain, par: Option<&Content>) -> Outcome<ConfigBase> {
145 let size = styles.font_size();
146 let justify = matches!(res!(par_value(styles, par, "justify")), Some(Value::Bool(true)));
147 let linebreaks = match res!(par_value(styles, par, "linebreaks")) {
148 Some(Value::Str(s)) if s.as_str() == "simple" => Some(Linebreaks::Simple),
149 Some(Value::Str(s)) if s.as_str() == "optimized" => Some(Linebreaks::Optimized),
150 _ => None,
151 };
152 let first_line_indent = match res!(par_value(styles, par, "first-line-indent")) {
153 Some(Value::Length(l)) => (l.resolve(size), false),
154 Some(Value::Dict(d)) => (
155 match d.get("amount") {
156 Some(Value::Length(l)) => l.resolve(size),
157 _ => 0.0,
158 },
159 matches!(d.get("all"), Some(Value::Bool(true))),
160 ),
161 _ => (0.0, false),
162 };
163 let hanging_indent = match res!(par_value(styles, par, "hanging-indent")) {
164 Some(Value::Length(l)) => l.resolve(size),
165 _ => 0.0,
166 };
167 Ok(ConfigBase { justify, linebreaks, first_line_indent, hanging_indent })
168}
169
170/// The value a style property takes for every child, or `None` when the children differ.
171fn shared<T: PartialEq, F: Fn(&StyleChain) -> Outcome<T>>(children: &[Pair], styles: &StyleChain, get: F)
172 -> Outcome<Option<T>>
173{
174 let v = res!(get(styles));
175 for c in children {
176 if c.is_tag() {
177 continue;
178 }
179 if res!(get(&c.styles)) != v {
180 return Ok(None);
181 }
182 }
183 Ok(Some(v))
184}
185
186fn configuration(
187 base: &ConfigBase,
188 children: &[Pair],
189 styles: &StyleChain,
190 situation: Option<ParSituation>,
191)
192 -> Outcome<Config>
193{
194 let justify = base.justify;
195 let size = styles.font_size();
196 let props = res!(ftext::props(styles));
197 let rtl = props.rtl;
198 let align = res!(fixed_align(styles, rtl));
199 let (amount, all) = base.first_line_indent;
200 let first_line_indent = if amount != 0.0
201 && match situation {
202 // An indent under a list's marker just looks bad.
203 Some(ParSituation::First) => all && !in_list(styles),
204 Some(ParSituation::Consecutive) => true,
205 Some(ParSituation::Other) => all,
206 None => false,
207 }
208 && align == crate::flow::inline::FixedAlign::Start
209 {
210 amount
211 } else {
212 0.0
213 };
214 let hyphenate = res!(shared(children, styles, |s| Ok(match res!(text_field(s, "hyphenate")) {
215 Some(Value::Bool(b)) => Some(b),
216 _ => None,
217 }))).map(|uniform| uniform.unwrap_or(justify));
218 Ok(Config {
219 justify,
220 linebreaks: base.linebreaks.unwrap_or(if justify { Linebreaks::Optimized } else { Linebreaks::Simple }),
221 first_line_indent,
222 hanging_indent: if situation.is_some() { base.hanging_indent } else { 0.0 },
223 align,
224 font_size: size,
225 rtl,
226 hyphenate,
227 lang: res!(shared(children, styles, lang_of)),
228 cjk_latin_spacing: props.cjk_latin_spacing,
229 costs: props.costs,
230 })
231}
232
233// ┌───────────────────────────────────────────────────────────────────────────┐
234// │ MEMO │
235// └───────────────────────────────────────────────────────────────────────────┘
236
237/// The paragraphs a session has broken into lines, as the break that ends each line, on a generation-swept
238/// map under the `pars` budget. A paragraph is kept only where [`keepable`] says its preparation depends on
239/// nothing but the key below, and where the preparation asked the introspector nothing, which the read
240/// log's ask count proves. A hit prepares the paragraph again, which puts the current source's tags and
241/// spans in its items and repeats whatever the preparation reads or says, and builds each line from its
242/// kept break, taking its shaped runs from the shaped-run cache; only the search for the breaks is saved.
243///
244/// The key is the configuration the caches stand under, the paragraph's [`Config`], the region's width
245/// and each child [`Pair`]'s fingerprint in order. A paragraph holding an inline box or equation
246/// ([`Keep::Region`]) adds the region's height, base and expansion, which laying those out reads. A
247/// text-like paragraph leaves them out, with `expand`: nothing it prepares reads them, and the width the
248/// lines fill is worked out again from `expand` and the lines on every call, as is each line's box.
249#[derive(Debug)]
250pub struct ParMemo {
251 map: GenMap<Fingerprint, Arc<Vec<LineEnd>>>,
252}
253
254impl Default for ParMemo {
255 fn default() -> Self { Self { map: GenMap::new(PAR_BUDGET) } }
256}
257
258impl ParMemo {
259 /// Opens a compile under the budget given.
260 pub fn begin(&mut self, ceiling: usize) {
261 self.map.set_ceiling(ceiling);
262 self.map.begin();
263 }
264
265 /// Drops what neither this compile nor the one before touched.
266 pub fn sweep(&mut self) { self.map.sweep(); }
267
268 pub fn clear(&mut self) { self.map.clear(); }
269
270 /// Is anything kept at all? A budget of nothing turns the memo off, key and all.
271 pub fn on(&self) -> bool { self.map.ceiling() > 0 }
272
273 /// The paragraphs held.
274 pub fn len(&self) -> usize { self.map.len() }
275
276 /// The estimated bytes held.
277 pub fn bytes(&self) -> usize { self.map.bytes() }
278
279 /// The paragraphs refused at the budget since the memo was made.
280 pub fn refused(&self) -> u64 { self.map.refused() }
281
282 fn get(&mut self, key: &Fingerprint) -> Option<Arc<Vec<LineEnd>>> { self.map.get(key).cloned() }
283
284 fn store(&mut self, key: Fingerprint, breaks: Vec<LineEnd>) {
285 let size = std::mem::size_of::<Vec<LineEnd>>() + breaks.len() * std::mem::size_of::<LineEnd>();
286 self.map.insert(key, Arc::new(breaks), size);
287 }
288}
289
290fn memo_key(caches: Option<Fingerprint>, config: &Config, region: Region, keep: Keep, children: &[Pair]) -> Fingerprint {
291 let mut f = Fingerprinter::new();
292 match caches {
293 Some(c) => { f.write_u8(1); f.write_fingerprint(c); }
294 None => f.write_u8(0),
295 }
296 f.write_fingerprint(config.fingerprint());
297 f.write_i32(region.width.raw());
298 if keep == Keep::Region {
299 f.write_i32(region.height.raw());
300 f.write_i32(region.base.0.raw());
301 f.write_i32(region.base.1.raw());
302 f.write_bool(region.expand_x);
303 f.write_bool(region.expand_y);
304 }
305 f.write_usize(children.len());
306 for c in children {
307 f.write_fingerprint(c.fingerprint());
308 }
309 f.finish()
310}
311
312/// Lines under an explicit configuration base, for a caller that holds the `par` settings itself.
313///
314/// A paragraph already broken under the same key takes its breaks from the memo ([`ParMemo`]) and builds
315/// its lines from them over a fresh preparation, so a hit makes the same boxes as a miss.
316pub fn layout_with(
317 engine: &mut Engine,
318 children: &[Pair],
319 styles: &StyleChain,
320 region: Region,
321 expand: bool,
322 situation: Option<ParSituation>,
323 base: &ConfigBase,
324)
325 -> Outcome<Vec<LineBox>>
326{
327 let config = res!(configuration(base, children, styles, situation));
328 let hang = config.hanging_indent;
329 let region_w = region.width.to_pt();
330 let keep = if engine.caches.pars.on() { keepable(children) } else { Keep::No };
331 let key = match keep {
332 Keep::No => None,
333 _ => Some(memo_key(engine.caches.config(), &config, region, keep, children)),
334 };
335 let asks = engine.reads.asks();
336 let p = res!(prepare(engine, children, config, region));
337 // A preparation that asked the introspector made its items from answers the key does not hold, so its
338 // breaks are neither taken nor kept. A repeated question counts too, which the read log alone would not
339 // show.
340 let key = key.filter(|_| engine.reads.asks() == asks);
341
342 // Kept breaks are taken only when they end at the end of the text, which a key that matches assures.
343 let kept = match &key {
344 Some(k) => engine.caches.pars.get(k).filter(|b| b.last().map_or(0, |(end, _)| *end) == p.text.len()),
345 None => None,
346 };
347 let lines = match kept {
348 Some(breaks) => {
349 engine.caches.counters.par_hits += 1;
350 res!(rebuild(&p, &breaks))
351 }
352 None => {
353 engine.caches.counters.par_misses += 1;
354 let (lines, breaks) = res!(linebreak(&p, region_w - hang));
355 if let Some(k) = key {
356 engine.caches.pars.store(k, breaks);
357 }
358 lines
359 }
360 };
361
362 // The width the lines fill: the region's, unless the content may shrink to its longest line and has
363 // no fractional spacing.
364 let finite = region.width.raw() < (1 << 30);
365 let width = if !finite || (!expand && lines.iter().all(|l| l.fr() == 0.0)) {
366 let longest = lines.iter().map(|l| l.width).fold(0.0f64, f64::max);
367 if finite { region_w.min(hang + longest) } else { hang + longest }
368 } else {
369 region_w
370 };
371 let full = region.height.to_pt();
372 let mut out = Vec::with_capacity(lines.len());
373 for l in &lines {
374 out.push(res!(commit(engine, &p, l, width, full)));
375 }
376 Ok(out)
377}
378
379/// The lines stacked `par.leading` apart, with the breaks between them a page may not take: after the
380/// first line (an orphan) and before the last (a widow) while `text.costs` prices them, and none at all
381/// in a paragraph of three lines guarding both. A forbidden break is an infinite penalty before the
382/// leading glue, which a page breaker reads as TeX does: glue after a penalty is no breakpoint.
383pub fn stack(styles: &StyleChain, lines: Vec<LineBox>) -> Outcome<Vec<Node>> {
384 let size = styles.font_size();
385 let leading = match res!(elem_field(styles, ElemKind::Par, "leading")) {
386 Some(Value::Length(l)) => l.resolve(size),
387 _ => 0.65 * size,
388 };
389 stack_with(styles, lines, leading)
390}
391
392/// As [`stack`], `leading` points apart.
393fn stack_with(styles: &StyleChain, lines: Vec<LineBox>, leading: f64) -> Outcome<Vec<Node>> {
394 let costs = res!(ftext::props(styles)).costs;
395 let len = lines.len();
396 let non_empty = |l: &LineBox| match &l.node {
397 Node::HBox(b) => !b.list.is_empty(),
398 _ => true,
399 };
400 let orphans = costs.orphan > 0.0 && len >= 2 && non_empty(&lines[1]);
401 let widows = costs.widow > 0.0 && len >= 2 && non_empty(&lines[len - 2]);
402 let all = len == 3 && orphans && widows;
403 let mut out = Vec::with_capacity(len * 3);
404 for (i, l) in lines.into_iter().enumerate() {
405 if i > 0 {
406 // The break between line i - 1 and line i.
407 let keep = all || (orphans && i == 1) || (widows && i + 1 == len);
408 if keep {
409 out.push(Node::Penalty(Penalty::new(Penalty::INFINITY, false)));
410 }
411 out.push(Node::Glue(Glue::fixed(Sp::from_pt(leading))));
412 }
413 out.push(l.node);
414 }
415 Ok(out)
416}
417
418/// Lines stacked into one frame, as an inline box holds them, its baseline its first line's.
419pub fn stack_frame(styles: &StyleChain, lines: Vec<LineBox>) -> Outcome<Frame> {
420 let width = lines.iter().map(|l| l.width).fold(0.0f64, f64::max);
421 let first_top = lines.first().map_or(0.0, |l| l.top);
422 let nodes = res!(stack(styles, lines));
423 let height: f64 = nodes.iter().map(|n| n.vextent().to_pt()).sum();
424 Ok(Frame::new(nodes, width, first_top, height))
425}