Oregami
Repositories/oxedyne/fe2o3

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

45.2 KiB, 26 runs

created by r1870400018:63524, 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/{collect,prepare,line}.rs`, version 0.15.1).
3// Modified for Austenite: ported to Hematite's types, IR and error handling.
4// U6a owns this file: inline items -- shaped text, spacing, inline boxes, equations, footnote marks,
5// link spans -- collected from a paragraph's children for the line breaker. Internal to U6a.
6//
7// A port of Typst 0.15.1's inline layout (`typst-layout/src/inline/{collect,prepare,line}.rs`,
8// Apache-2.0, (c) the Typst project authors). A paragraph's children become one string -- text as it
9// is, spacing as a space, an inline object as U+FFFC -- with a segment per style run; the text is
10// shaped per bidi level and script; a line is any slice of it, whose end runs are re-shaped where the
11// slice cuts them; and a chosen line is committed to a line box, justified and aligned as Typst does,
12// with punctuation hanging into the end margin.
13
14use crate::diag::DiagnosticKind;
15use crate::eval::content::{
16 Content,
17 ElemKind,
18};
19use crate::eval::lib::model::quote::smart_quotes;
20use crate::eval::realise::{
21 Pair,
22 Tag as RealiseTag,
23};
24use crate::eval::styles::{
25 Property,
26 Style,
27 StyleChain,
28 Styles,
29};
30use crate::eval::value::{
31 HAlign,
32 Value,
33};
34use crate::eval::Engine;
35use crate::flow::text::{
36 self as ftext,
37 is_of_cj_script,
38 is_space,
39 shape_run,
40 text_field,
41 Costs,
42 ShapedRun,
43 TextProps,
44 BEGIN_PUNCT,
45 END_PUNCT,
46};
47use crate::flow::Region;
48use crate::fonts::{
49 is_default_ignorable,
50 FontBook,
51};
52use crate::ir::{
53 BoxNode,
54 Dims,
55 Glue,
56 Graphic,
57 Leaf,
58 LinkTarget,
59 Node,
60 Sp,
61};
62use crate::linebreak::{
63 dash_of,
64 Breakpoint,
65 Trim,
66};
67
68use oxedyne_fe2o3_core::prelude::*;
69use oxedyne_fe2o3_hash::fingerprint::Fingerprint;
70use oxedyne_fe2o3_hash::fingerprint::Fingerprinter;
71use oxedyne_fe2o3_text::unicode::bidi;
72use oxedyne_fe2o3_text::unicode::lookup::Partitioned;
73use oxedyne_fe2o3_text::unicode::prop::Script;
74
75use std::sync::Arc;
76
77const SPACING_REPLACE: &str = " ";
78const OBJ_REPLACE: &str = "\u{FFFC}";
79const LTR_EMBEDDING: &str = "\u{202A}";
80const RTL_EMBEDDING: &str = "\u{202B}";
81const POP_EMBEDDING: &str = "\u{202C}";
82const LTR_ISOLATE: &str = "\u{2066}";
83const POP_ISOLATE: &str = "\u{2069}";
84const LINE_SEPARATOR: char = '\u{2028}';
85
86/// Is an item in a line a placeholder for the start hyphen, the end hyphen, or item `i` of the prepared
87/// paragraph (`i + 1`)? Lines keep items in visual order; this keeps their logical order.
88const START_HYPHEN: usize = 0;
89const END_HYPHEN: usize = usize::MAX;
90
91/// How a paragraph chooses its breaks.
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93pub enum Linebreaks {
94 Simple,
95 Optimized,
96}
97
98/// Where a paragraph stands in its flow, which decides its first-line indent.
99#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
100pub enum ParSituation {
101 First, // first in its container or page run, or after a column break
102 Consecutive, // right after another paragraph
103 Other,
104}
105
106/// A horizontal alignment fixed against the text direction.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub enum FixedAlign {
109 Start,
110 Center,
111 End,
112}
113
114impl FixedAlign {
115 fn position(self, extent: f64) -> f64 {
116 match self {
117 FixedAlign::Start => 0.0,
118 FixedAlign::Center => extent / 2.0,
119 FixedAlign::End => extent,
120 }
121 }
122}
123
124/// The paragraph-wide settings of one inline layout.
125#[derive(Clone, Debug)]
126pub struct Config {
127 pub justify: bool,
128 pub linebreaks: Linebreaks,
129 pub first_line_indent: f64,
130 pub hanging_indent: f64,
131 pub align: FixedAlign,
132 pub font_size: f64,
133 pub rtl: bool,
134 pub hyphenate: Option<bool>, // set only when the same for every child
135 pub lang: Option<String>, // ditto
136 pub cjk_latin_spacing: bool,
137 pub costs: Costs,
138}
139
140impl Config {
141 /// The fingerprint of every setting, for a key that must change when any of them does. The pattern
142 /// names each field, so a field added to the struct fails to compile here until it is hashed.
143 pub fn fingerprint(&self) -> Fingerprint {
144 let Config {
145 justify, linebreaks, first_line_indent, hanging_indent, align, font_size, rtl, hyphenate, lang,
146 cjk_latin_spacing, costs,
147 } = self;
148 let Costs { hyphenation, runt, widow, orphan } = costs;
149 let mut f = Fingerprinter::new();
150 f.write_bool(*justify);
151 f.write_u8(match linebreaks {
152 Linebreaks::Simple => 0,
153 Linebreaks::Optimized => 1,
154 });
155 f.write_f64(*first_line_indent);
156 f.write_f64(*hanging_indent);
157 f.write_u8(match align {
158 FixedAlign::Start => 0,
159 FixedAlign::Center => 1,
160 FixedAlign::End => 2,
161 });
162 f.write_f64(*font_size);
163 f.write_bool(*rtl);
164 f.write_u8(match hyphenate {
165 None => 0,
166 Some(false) => 1,
167 Some(true) => 2,
168 });
169 match lang {
170 Some(l) => { f.write_u8(1); f.write_str(l); }
171 None => f.write_u8(0),
172 }
173 f.write_bool(*cjk_latin_spacing);
174 f.write_f64(*hyphenation);
175 f.write_f64(*runt);
176 f.write_f64(*widow);
177 f.write_f64(*orphan);
178 f.finish()
179 }
180}
181
182/// Laid-out inline content: a list set from its top-left, `baseline` below which a line seats it.
183#[derive(Clone, Debug)]
184pub struct Frame {
185 pub nodes: Arc<Vec<Node>>,
186 pub width: f64,
187 pub baseline: f64, // from the top
188 pub height: f64,
189 pub link: Option<LinkTarget>, // where the whole frame links (`link.current`)
190 pub shift: (f64, f64), // its contents moved right and down, the frame staying put
191}
192
193impl Frame {
194 pub fn new(nodes: Vec<Node>, width: f64, baseline: f64, height: f64) -> Self {
195 Self { nodes: Arc::new(nodes), width, baseline, height, link: None, shift: (0.0, 0.0) }
196 }
197
198 pub fn empty(width: f64) -> Self { Self::new(Vec::new(), width, 0.0, 0.0) }
199}
200
201/// One item of a prepared paragraph.
202#[derive(Clone, Debug)]
203pub enum Item {
204 Text(ShapedRun),
205 Absolute(f64, bool), // spacing in points, and whether it is weak
206 Fractional(f64, Option<Arc<(Content, StyleChain)>>), // fractional spacing, or a box of fractional width
207 Frame(Frame),
208 Tag(RealiseTag), // where a located element starts or ends
209 Skip(&'static str), // invisible, as a bidi isolate
210}
211
212impl Item {
213 pub fn is_tag(&self) -> bool { matches!(self, Item::Tag(_)) }
214
215 pub fn text(&self) -> Option<&ShapedRun> {
216 match self {
217 Item::Text(t) => Some(t),
218 _ => None,
219 }
220 }
221
222 pub fn text_mut(&mut self) -> Option<&mut ShapedRun> {
223 match self {
224 Item::Text(t) => Some(t),
225 _ => None,
226 }
227 }
228
229 /// What the item stands for in the paragraph's text.
230 pub fn textual(&self) -> &str {
231 match self {
232 Item::Text(t) => &t.text,
233 Item::Absolute(..) | Item::Fractional(..) => SPACING_REPLACE,
234 Item::Frame(_) => OBJ_REPLACE,
235 Item::Tag(_) => "",
236 Item::Skip(s) => s,
237 }
238 }
239
240 pub fn natural_width(&self) -> f64 {
241 match self {
242 Item::Text(t) => t.width(),
243 Item::Absolute(v, _) => *v,
244 Item::Frame(f) => f.width,
245 _ => 0.0,
246 }
247 }
248}
249
250/// A stretch of the text still to be shaped, or an item already made.
251enum Segment {
252 Text(usize, StyleChain),
253 Item(Item),
254}
255
256impl Segment {
257 fn textual_len(&self) -> usize {
258 match self {
259 Segment::Text(n, _) => *n,
260 Segment::Item(i) => i.textual().len(),
261 }
262 }
263}
264
265/// A paragraph ready for breaking: its text, its items with their byte ranges, and the bidi levels.
266pub struct Prep {
267 pub text: String,
268 pub config: Config,
269 pub bidi: Option<Vec<u8>>, // a level per byte, when any is not the base's
270 pub items: Vec<((usize, usize), Item)>,
271 pub indices: Vec<usize>, // the item holding each byte
272 pub book: Arc<FontBook>,
273}
274
275impl Prep {
276 /// The item holding byte `offset`.
277 pub fn get(&self, offset: usize) -> &((usize, usize), Item) {
278 let idx = self.indices.get(offset).copied().unwrap_or(0);
279 &self.items[idx.min(self.items.len().saturating_sub(1))]
280 }
281
282 /// The items meeting `start..end`, with their indices; a line starting mid-text leaves out the
283 /// empty items before it, which belong to the line before.
284 fn slice(&self, start: usize, end: usize) -> Vec<usize> {
285 let first = if start == 0 { 0 } else { self.indices.get(start).copied().unwrap_or(0) };
286 let mut out = Vec::new();
287 for i in first..self.items.len() {
288 let (r, _) = &self.items[i];
289 if r.0 < end || r.1 <= end {
290 out.push(i);
291 } else {
292 break;
293 }
294 }
295 out
296 }
297
298}
299
300// ┌───────────────────────────────────────────────────────────────────────────┐
301// │ COLLECTION │
302// └───────────────────────────────────────────────────────────────────────────┘
303
304/// Text properties, resolved once per style chain of a paragraph.
305#[derive(Default)]
306pub struct PropsCache {
307 map: Vec<(StyleChain, Arc<TextProps>)>,
308}
309
310impl PropsCache {
311 pub fn get(&mut self, styles: &StyleChain) -> Outcome<Arc<TextProps>> {
312 for (c, p) in &self.map {
313 if c.ptr_eq(styles) {
314 return Ok(p.clone());
315 }
316 }
317 let p = Arc::new(res!(ftext::props(styles)));
318 self.map.push((styles.clone(), p.clone()));
319 Ok(p)
320 }
321}
322
323struct Collector {
324 full: String,
325 segments: Vec<Segment>,
326}
327
328impl Collector {
329 fn push_text(&mut self, text: &str, styles: &StyleChain) {
330 self.full.push_str(text);
331 let n = text.len();
332 if let Some(Segment::Text(len, last)) = self.segments.last_mut() {
333 if last.ptr_eq(styles) {
334 *len += n;
335 return;
336 }
337 }
338 self.segments.push(Segment::Text(n, styles.clone()));
339 }
340
341 fn push_item(&mut self, item: Item) {
342 if let (Some(Segment::Item(Item::Absolute(prev, true))), Item::Absolute(amount, true)) = (self.segments.last_mut(), &item) {
343 *prev = prev.max(*amount);
344 return;
345 }
346 self.full.push_str(item.textual());
347 self.segments.push(Segment::Item(item));
348 }
349}
350
351/// Tracks open quotation marks, as Typst's smart quoter does.
352struct Quoter {
353 depth: u32,
354 kinds: u32,
355}
356
357impl Quoter {
358 fn top(&self) -> Option<bool> {
359 self.depth.checked_sub(1).map(|i| (self.kinds >> i) & 1 == 1)
360 }
361
362 fn push(&mut self, double: bool) {
363 if self.depth < 32 {
364 self.kinds |= (double as u32) << self.depth;
365 self.depth += 1;
366 }
367 }
368
369 fn pop(&mut self) {
370 self.depth -= 1;
371 self.kinds &= (1 << self.depth) - 1;
372 }
373
374 fn quote(&mut self, before: Option<char>, q: &Quotes, double: bool) -> String {
375 let opened = self.top();
376 let before = before.unwrap_or(' ');
377 if before.is_numeric() && opened != Some(double) {
378 return if double { "\u{2033}".to_string() } else { "\u{2032}".to_string() };
379 }
380 if !double && opened != Some(false) && (before.is_alphabetic() || before == '\u{FFFC}') {
381 return "\u{2019}".to_string();
382 }
383 if opened == Some(double)
384 && !before.is_whitespace()
385 && !matches!(before, '\n' | '\r' | '\u{000B}' | '\u{000C}' | '\u{0085}' | '\u{2028}' | '\u{2029}')
386 && !matches!(before, '(' | '{' | '[')
387 {
388 self.pop();
389 return if double { q.double_close.clone() } else { q.single_close.clone() };
390 }
391 self.push(double);
392 if double { q.double_open.clone() } else { q.single_open.clone() }
393 }
394}
395
396struct Quotes {
397 single_open: String,
398 single_close: String,
399 double_open: String,
400 double_close: String,
401}
402
403/// The quotation marks in force for a quote: the language's, from the model's table under the chain with
404/// the element's own `alternative`, then any `quotes` given, as Typst's `SmartQuotes::get` takes them.
405fn quotes_for(styles: &StyleChain, alternative: bool, custom: Option<&Value>) -> Quotes {
406 let chain = match ElemKind::SmartQuote.field_id("alternative") {
407 Some(id) => styles.chain(&Styles::from_style(Style::Property(Property::new(
408 ElemKind::SmartQuote, id, Value::Bool(alternative), crate::syntax::Span::detached())))),
409 None => styles.clone(),
410 };
411 let [so, sc, dopen, dc] = smart_quotes(&chain);
412 let mut q = Quotes {
413 single_open: so.to_string(),
414 single_close: sc.to_string(),
415 double_open: dopen.to_string(),
416 double_close: dc.to_string(),
417 };
418 // A set is two graphemes in a string, or two strings; a bare set is the double quotes.
419 let pair = |v: &Value| -> Option<(String, String)> {
420 match v {
421 Value::Str(s) => {
422 let g = oxedyne_fe2o3_text::unicode::segment::graphemes(s);
423 if g.len() == 2 { Some((g[0].to_string(), g[1].to_string())) } else { None }
424 }
425 Value::Array(a) if a.len() == 2 => match (&a[0], &a[1]) {
426 (Value::Str(o), Value::Str(c)) => Some((o.to_string(), c.to_string())),
427 _ => None,
428 },
429 _ => None,
430 }
431 };
432 match custom {
433 Some(Value::Dict(d)) => {
434 if let Some((o, c)) = d.get("double").and_then(|v| pair(v)) { q.double_open = o; q.double_close = c; }
435 if let Some((o, c)) = d.get("single").and_then(|v| pair(v)) { q.single_open = o; q.single_close = c; }
436 }
437 Some(v) => if let Some((o, c)) = pair(v) { q.double_open = o; q.double_close = c; },
438 None => (),
439 }
440 q
441}
442
443/// A field of the element in hand, else the chain's.
444fn own(pair: &Pair, name: &str) -> Outcome<Option<Value>> {
445 match pair.content.kind().and_then(|k| k.field_id(name)) {
446 Some(id) => pair.styles.resolve(&pair.content, id),
447 None => Ok(None),
448 }
449}
450
451fn bool_of(v: Option<Value>, dflt: bool) -> bool {
452 match v {
453 Some(Value::Bool(b)) => b,
454 _ => dflt,
455 }
456}
457
458/// Gathers the children into one string and its segments.
459fn collect(
460 engine: &mut Engine,
461 children: &[Pair],
462 config: &Config,
463 region: Region,
464 cache: &mut PropsCache,
465)
466 -> Outcome<(String, Vec<Segment>)>
467{
468 let mut c = Collector { full: String::new(), segments: Vec::with_capacity(children.len() + 2) };
469 let mut quoter = Quoter { depth: 0, kinds: 0 };
470 if config.first_line_indent != 0.0 {
471 c.push_item(Item::Absolute(config.first_line_indent, false));
472 }
473 if config.hanging_indent != 0.0 {
474 c.push_item(Item::Absolute(-config.hanging_indent, false));
475 }
476 let region_w = region.width.to_pt();
477 let book = res!(engine.fonts.book());
478 let mut warned_position = false;
479 for pair in children {
480 if let Some(tag) = &pair.tag {
481 c.push_item(Item::Tag(tag.clone()));
482 continue;
483 }
484 let styles = &pair.styles;
485 let kind = match pair.content.kind() {
486 Some(k) => k,
487 None => continue,
488 };
489 // A link to a page position has no place in the IR yet, so its content is left unlinked.
490 if !warned_position && matches!(res!(ftext::elem_field(styles, ElemKind::Link, "current")), Some(Value::Dict(_))) {
491 warned_position = true;
492 engine.warn(DiagnosticKind::Unsupported, pair.content.span(), "a link to a position is not supported yet and was left unlinked");
493 }
494 match kind {
495 ElemKind::Tag => {
496 if let Some(tag) = RealiseTag::from_content(&pair.content) {
497 c.push_item(Item::Tag(tag));
498 }
499 }
500 ElemKind::Space => c.push_text(" ", styles),
501 ElemKind::Text | ElemKind::Symbol => {
502 let text = match pair.content.get(crate::eval::content::FieldId(0)) {
503 Some(Value::Str(s)) => s.clone(),
504 _ => continue,
505 };
506 let props = res!(cache.get(styles));
507 let mut s = String::new();
508 if props.rtl != config.rtl {
509 s.push_str(if props.rtl { RTL_EMBEDDING } else { LTR_EMBEDDING });
510 }
511 match props.case {
512 Some(true) => s.push_str(&text.to_uppercase()),
513 Some(false) => s.push_str(&text.to_lowercase()),
514 None => s.push_str(&text),
515 }
516 if props.rtl != config.rtl {
517 s.push_str(POP_EMBEDDING);
518 }
519 c.push_text(&s, styles);
520 }
521 ElemKind::H => {
522 match res!(own(pair, "amount")) {
523 Some(Value::Fraction(f)) => {
524 if f.0 != 0.0 {
525 c.push_item(Item::Fractional(f.0, None));
526 }
527 }
528 Some(v) => {
529 let size = styles.font_size();
530 let amount = match v {
531 Value::Length(l) => l.resolve(size),
532 Value::Ratio(r) => r.0 * region_w,
533 Value::Relative(r) => r.rel.0 * region_w + r.abs.resolve(size),
534 _ => 0.0,
535 };
536 if amount != 0.0 {
537 c.push_item(Item::Absolute(amount, bool_of(res!(own(pair, "weak")), false)));
538 }
539 }
540 None => (),
541 }
542 }
543 ElemKind::Linebreak => {
544 let justify = bool_of(res!(own(pair, "justify")), false);
545 c.push_text(if justify { "\u{2028}" } else { "\n" }, styles);
546 }
547 ElemKind::SmartQuote => {
548 let double = bool_of(res!(own(pair, "double")), true);
549 if bool_of(res!(own(pair, "enabled")), true) {
550 let alternative = bool_of(res!(own(pair, "alternative")), false);
551 let custom = res!(own(pair, "quotes")).filter(|v| !v.is_auto());
552 let q = quotes_for(styles, alternative, custom.as_ref());
553 let before = c.full.chars().rev().find(|&ch| !is_default_ignorable(ch));
554 let mark = quoter.quote(before, &q, double);
555 c.push_text(&mark, styles);
556 } else {
557 c.push_text(if double { "\"" } else { "'" }, styles);
558 }
559 }
560 ElemKind::Equation => {
561 c.push_item(Item::Skip(LTR_ISOLATE));
562 let node = res!(crate::flow::math::layout_equation(engine, &pair.content, styles, region));
563 let mut frame = frame_of_node(node);
564 let props = res!(cache.get(styles));
565 frame.link = props.link.clone();
566 frame.shift = ftext::frame_shift(&book, &props);
567 c.push_item(Item::Frame(frame));
568 c.push_item(Item::Skip(POP_ISOLATE));
569 }
570 ElemKind::Box => {
571 match res!(own(pair, "width")) {
572 Some(Value::Fraction(f)) => c.push_item(Item::Fractional(f.0,
573 Some(Arc::new((pair.content.clone(), styles.clone()))))),
574 _ => {
575 let frame = res!(layout_inline_box(engine, &pair.content, styles, region, None, cache));
576 c.push_item(Item::Frame(frame));
577 }
578 }
579 }
580 other => {
581 engine.warn(DiagnosticKind::Lint, pair.content.span(), fmt!(
582 "{} may not occur inside of a paragraph and was ignored", other.name()));
583 }
584 }
585 }
586 Ok((c.full, c.segments))
587}
588
589/// How far the breaks of these children can be kept from one compile to the next. Every child must be one of
590/// the kinds below; the list is an allowlist, so a kind added to `collect` is left out until it is
591/// considered here.
592#[derive(Clone, Copy, Debug, PartialEq, Eq)]
593pub enum Keep {
594 No, // a child of a kind not considered
595 Width, // text-like children, prepared from their content, chain and the region's width alone
596 Region, // an inline box or equation as well, laid out through the engine against the whole region
597}
598
599/// Which [`Keep`] these children allow. An inline box or equation may also ask the introspector as it is
600/// laid out, which no fingerprint of the children holds, so the caller keeps such a paragraph only where
601/// its preparation asked nothing ([`crate::eval::intro::ReadLog::asks`]).
602pub fn keepable(children: &[Pair]) -> Keep {
603 let mut keep = Keep::Width;
604 for c in children {
605 if c.is_tag() {
606 continue;
607 }
608 match c.content.kind() {
609 None => (), // empty, skipped by `collect`
610 Some(ElemKind::Tag | ElemKind::Space | ElemKind::Text | ElemKind::Symbol | ElemKind::H
611 | ElemKind::Linebreak | ElemKind::SmartQuote) => (),
612 Some(ElemKind::Box | ElemKind::Equation) => keep = Keep::Region,
613 Some(_) => return Keep::No,
614 }
615 }
616 keep
617}
618
619/// A laid-out node as an inline frame, its baseline its height above the baseline.
620pub fn frame_of_node(node: Node) -> Frame {
621 let dims = match &node {
622 Node::HBox(b) | Node::VBox(b) => b.dims,
623 Node::Leaf(l) => l.dims,
624 _ => Dims::default(),
625 };
626 Frame::new(vec![node], dims.width.to_pt(), dims.height.to_pt(), dims.vextent().to_pt())
627}
628
629/// An inline `box` as a line holds it, Typst's `layout_and_modify` then `apply_shift`: laid out with any
630/// link in force taken off its body, then linked as a whole and moved by the text's baseline shift.
631fn layout_inline_box(
632 engine: &mut Engine,
633 elem: &Content,
634 styles: &StyleChain,
635 region: Region,
636 share: Option<f64>,
637 cache: &mut PropsCache,
638)
639 -> Outcome<Frame>
640{
641 let props = res!(cache.get(styles));
642 // The line links the box as a whole, so the box itself is laid out unlinked.
643 let inner = crate::flow::block::unlink(styles, &props.link);
644 let mut frame = res!(layout_box(engine, elem, &inner, region, share));
645 let book = res!(engine.fonts.book());
646 frame.link = props.link.clone();
647 frame.shift = ftext::frame_shift(&book, &props);
648 Ok(frame)
649}
650
651/// Lays out an inline `box` as the block flow does an unbreakable block, Typst's `layout_box`: its body in the
652/// box's width (its natural width when `auto`, the share of a fractional width when `share` is given), its
653/// height, `inset`, `outset`, `fill`, `stroke`, `radius` and `clip` applied, its baseline shifted by `baseline`.
654pub fn layout_box(
655 engine: &mut Engine,
656 elem: &Content,
657 styles: &StyleChain,
658 region: Region,
659 share: Option<f64>,
660)
661 -> Outcome<Frame>
662{
663 let f = res!(crate::flow::block::layout_box(engine, elem, styles, region, share));
664 let (w, h, base) = (f.w, f.h, f.baseline());
665 Ok(Frame::new(vec![f.into_node()], w, base, h))
666}
667
668// ┌───────────────────────────────────────────────────────────────────────────┐
669// │ PREPARATION │
670// └───────────────────────────────────────────────────────────────────────────┘
671
672/// Collects, shapes and indexes a paragraph's children.
673pub fn prepare(
674 engine: &mut Engine,
675 children: &[Pair],
676 config: Config,
677 region: Region,
678) -> Outcome<Prep> {
679 let book = res!(engine.fonts.book());
680 let mut cache = PropsCache::default();
681 let (text, segments) = res!(collect(engine, children, &config, region, &mut cache));
682
683 // Bidi levels, kept only when some text runs against the base direction.
684 let base_level: u8 = if config.rtl { 1 } else { 0 };
685 let needs = config.rtl || text.chars().any(|c| matches!(
686 oxedyne_fe2o3_text::unicode::prop::BidiClass::of(c),
687 oxedyne_fe2o3_text::unicode::prop::BidiClass::R | oxedyne_fe2o3_text::unicode::prop::BidiClass::AL
688 | oxedyne_fe2o3_text::unicode::prop::BidiClass::RLE | oxedyne_fe2o3_text::unicode::prop::BidiClass::RLO
689 | oxedyne_fe2o3_text::unicode::prop::BidiClass::RLI));
690 let levels: Vec<u8> = if needs {
691 let info = bidi::resolve(&text, if config.rtl { bidi::Direction::Rtl } else { bidi::Direction::Ltr });
692 let mut per_byte = vec![base_level; text.len()];
693 for (ci, (b, ch)) in text.char_indices().enumerate() {
694 let lv = info.levels.get(ci).copied().unwrap_or(base_level);
695 for k in b..b + ch.len_utf8() {
696 if let Some(slot) = per_byte.get_mut(k) {
697 *slot = lv;
698 }
699 }
700 }
701 per_byte
702 } else {
703 vec![base_level; text.len()]
704 };
705 let is_bidi = levels.iter().any(|l| (l % 2) != (base_level % 2));
706
707 let mut cursor = 0;
708 let mut items: Vec<((usize, usize), Item)> = Vec::with_capacity(segments.len());
709 for seg in segments {
710 let len = seg.textual_len();
711 let end = cursor + len;
712 match seg {
713 Segment::Text(_, styles) => {
714 let props = res!(cache.get(&styles));
715 crate::flow::text::ask_for_face(engine, &book, props.families.iter().map(|f| f.name.as_str()));
716 res!(shape_range(&mut items, &book, &text, &levels, cursor, end, &props));
717 }
718 Segment::Item(item) => items.push(((cursor, end), item)),
719 }
720 cursor = end;
721 }
722 let mut indices = Vec::with_capacity(text.len());
723 for (i, (r, _)) in items.iter().enumerate() {
724 for _ in r.0..r.1 {
725 indices.push(i);
726 }
727 }
728 if config.cjk_latin_spacing {
729 add_cjk_latin_spacing(&mut items);
730 }
731 Ok(Prep {
732 text,
733 config,
734 bidi: if is_bidi { Some(levels) } else { None },
735 items,
736 indices,
737 book,
738 })
739}
740
741fn is_generic_script(s: Script) -> bool {
742 matches!(s, Script::Unknown | Script::Common | Script::Inherited)
743}
744
745fn is_compatible(a: Script, b: Script) -> bool {
746 is_generic_script(a) || is_generic_script(b) || a == b
747}
748
749/// Shapes `start..end` in runs of one bidi level and one script.
750fn shape_range(
751 items: &mut Vec<((usize, usize), Item)>,
752 book: &FontBook,
753 text: &str,
754 levels: &[u8],
755 start: usize,
756 end: usize,
757 props: &Arc<TextProps>,
758)
759 -> Outcome<()>
760{
761 let explicit = props.script.is_some();
762 let process = |items: &mut Vec<((usize, usize), Item)>, a: usize, b: usize, level: u8| -> Outcome<()> {
763 let rtl = level % 2 == 1;
764 let sub = match text.get(a..b) {
765 Some(s) => s,
766 None => return Err(err!("A text run {}..{} is off a character boundary.", a, b; Bug)),
767 };
768 let shaped = res!(shape_run(book, a, sub, props, rtl));
769 items.push(((a, b), Item::Text(shaped)));
770 Ok(())
771 };
772 let mut prev_level: u8 = 0;
773 let mut prev_script = Script::Unknown;
774 let mut cursor = start;
775 for i in start..end {
776 if !text.is_char_boundary(i) {
777 continue;
778 }
779 let level = levels.get(i).copied().unwrap_or(0);
780 let cur = if explicit {
781 Script::Unknown
782 } else {
783 text.get(i..).and_then(|t| t.chars().next()).map_or(Script::Unknown, Script::of)
784 };
785 if level != prev_level || !is_compatible(cur, prev_script) {
786 if cursor < i {
787 res!(process(items, cursor, i, prev_level));
788 }
789 cursor = i;
790 prev_level = level;
791 prev_script = cur;
792 } else if is_generic_script(prev_script) {
793 prev_script = cur;
794 }
795 }
796 process(items, cursor, end, prev_level)
797}
798
799/// A quarter em between Han or kana and a western letter or number, shrinkable to an eighth.
800fn add_cjk_latin_spacing(items: &mut [((usize, usize), Item)]) {
801 // The glyphs in order, as (item, glyph) positions, with a break where a non-text item stands.
802 let mut seq: Vec<Option<(usize, usize, bool)>> = Vec::new(); // (item, glyph, has shift)
803 for (ii, (_, item)) in items.iter().enumerate() {
804 match item {
805 Item::Tag(_) => (),
806 Item::Text(t) => for gi in t.kept.0..t.kept.1 {
807 seq.push(Some((ii, gi, t.props.shift.is_some())));
808 },
809 _ => seq.push(None),
810 }
811 }
812 let glyph = |items: &[((usize, usize), Item)], ii: usize, gi: usize| -> Option<crate::flow::text::SGlyph> {
813 match &items[ii].1 {
814 Item::Text(t) => t.glyphs.get(gi).cloned(),
815 _ => None,
816 }
817 };
818 for k in 0..seq.len() {
819 let (ii, gi, shift) = match seq[k] {
820 Some(x) => x,
821 None => continue,
822 };
823 let g = match glyph(items, ii, gi) {
824 Some(g) => g,
825 None => continue,
826 };
827 if !g.is_cj_script() {
828 continue;
829 }
830 let next = seq.get(k + 1).copied().flatten();
831 let prev = if k > 0 { seq[k - 1] } else { None };
832 let mut add_right = false;
833 let mut add_left = false;
834 if let Some((ni, ng, ns)) = next {
835 if let Some(n) = glyph(items, ni, ng) {
836 if n.is_letter_or_number() && ns == shift {
837 add_right = true;
838 }
839 }
840 }
841 if let Some((pi, pg, ps)) = prev {
842 if let Some(p) = glyph(items, pi, pg) {
843 if p.is_letter_or_number() && ps == shift {
844 add_left = true;
845 }
846 }
847 }
848 if let Item::Text(t) = &mut items[ii].1 {
849 if let Some(gm) = Arc::make_mut(&mut t.glyphs).get_mut(gi) {
850 if add_right {
851 gm.x_advance += 0.25;
852 gm.shrink.1 += 0.125;
853 }
854 if add_left {
855 gm.x_advance += 0.25;
856 gm.x_offset += 0.25;
857 gm.shrink.0 += 0.125;
858 }
859 }
860 }
861 if add_left {
862 if let Some((pi, pg, _)) = prev {
863 if let Item::Text(t) = &mut items[pi].1 {
864 if let Some(pm) = Arc::make_mut(&mut t.glyphs).get_mut(pg) {
865 pm.justifiable = true;
866 }
867 }
868 }
869 }
870 }
871}
872
873// ┌───────────────────────────────────────────────────────────────────────────┐
874// │ LINES │
875// └───────────────────────────────────────────────────────────────────────────┘
876
877/// A dash at a line's end, for the cost of consecutive dashes.
878#[derive(Clone, Copy, Debug, PartialEq, Eq)]
879pub enum Dash {
880 Soft, // a hyphen added to break a word
881 Hard, // a hyphen in a compound word
882 Other, // an en or em dash
883}
884
885/// A candidate or chosen line: its items in visual order with their logical indices, its natural
886/// width, and whether it justifies.
887#[derive(Clone, Debug)]
888pub struct Line {
889 pub items: Vec<(usize, Item)>,
890 pub width: f64,
891 pub justify: bool,
892 pub dash: Option<Dash>,
893}
894
895impl Line {
896 pub fn empty() -> Self {
897 Self { items: Vec::new(), width: 0.0, justify: false, dash: None }
898 }
899
900 pub fn justifiables(&self) -> usize {
901 let mut n: usize = self.items.iter().filter_map(|(_, i)| i.text()).map(|t| t.justifiables()).sum();
902 if self.trailing_text().map_or(false, |t| t.cjk_justifiable_at_last()) {
903 n = n.saturating_sub(1);
904 }
905 n
906 }
907
908 pub fn stretchability(&self) -> f64 {
909 self.items.iter().filter_map(|(_, i)| i.text()).map(|t| t.stretchability()).sum()
910 }
911
912 pub fn shrinkability(&self) -> f64 {
913 self.items.iter().filter_map(|(_, i)| i.text()).map(|t| t.shrinkability()).sum()
914 }
915
916 pub fn has_negative_width_items(&self) -> bool {
917 self.items.iter().any(|(_, i)| match i {
918 Item::Absolute(a, _) => *a < 0.0,
919 Item::Frame(f) => f.width < 0.0,
920 _ => false,
921 })
922 }
923
924 pub fn fr(&self) -> f64 {
925 self.items.iter().map(|(_, i)| match i {
926 Item::Fractional(f, _) => *f,
927 _ => 0.0,
928 }).sum()
929 }
930
931 pub fn leading_text(&self) -> Option<&ShapedRun> {
932 self.items.iter().find(|(_, i)| !i.is_tag()).and_then(|(_, i)| i.text())
933 }
934
935 pub fn trailing_text(&self) -> Option<&ShapedRun> {
936 self.items.iter().rev().find(|(_, i)| !i.is_tag()).and_then(|(_, i)| i.text())
937 }
938
939 fn leading_text_mut(&mut self) -> Option<&mut ShapedRun> {
940 self.items.iter_mut().find(|(_, i)| !i.is_tag()).and_then(|(_, i)| i.text_mut())
941 }
942
943 fn trailing_text_mut(&mut self) -> Option<&mut ShapedRun> {
944 self.items.iter_mut().rev().find(|(_, i)| !i.is_tag()).and_then(|(_, i)| i.text_mut())
945 }
946
947 pub fn tail(&self) -> Tail {
948 let style = match self.dash {
949 Some(Dash::Hard) => self.trailing_text().map(ShapedRun::empty),
950 _ => None,
951 };
952 Tail { dash: self.dash, style }
953 }
954}
955
956/// What the next line needs of a line: its dash, and for a hard hyphen the style of the text it ends,
957/// to repeat the hyphen in. A breaker keeps one per candidate instead of the whole line.
958#[derive(Clone, Debug, Default)]
959pub struct Tail {
960 pub dash: Option<Dash>,
961 pub style: Option<ShapedRun>, // glyphless, carrying only the properties and direction
962}
963
964/// The line spanning `start..end`, ending at `bp`, after the line whose tail is `pred`.
965pub fn line(p: &Prep, start: usize, end: usize, bp: Breakpoint, pred: Option<&Tail>) -> Outcome<Line> {
966 let full = match p.text.get(start..end) {
967 Some(t) => t,
968 None => return Err(err!("A line {}..{} is off a character boundary.", start, end; Bug)),
969 };
970 let justify = full.ends_with(LINE_SEPARATOR) || (p.config.justify && bp != Breakpoint::Mandatory);
971 let dash = dash_of(bp, full);
972 let trim = bp.trim(start, full);
973 let mut l = Line { items: Vec::new(), width: 0.0, justify, dash };
974
975 // A hard hyphen repeated at the next line's start, where the language wants it.
976 if let Some(pred) = pred {
977 if pred.dash == Some(Dash::Hard) {
978 if let Some(base) = &pred.style {
979 if should_repeat_hyphen(&base.props.lang, full) {
980 if let Some(h) = base.hyphen(&p.book, trim.shaping, false) {
981 l.items.push((START_HYPHEN, Item::Text(h)));
982 }
983 }
984 }
985 }
986 }
987
988 res!(collect_items(&mut l.items, p, start, end, &trim));
989
990 if dash == Some(Dash::Soft) {
991 let base = l.trailing_text().cloned();
992 if let Some(base) = base {
993 if let Some(h) = base.hyphen(&p.book, trim.shaping, true) {
994 l.items.push((END_HYPHEN, Item::Text(h)));
995 }
996 }
997 }
998
999 trim_weak_spacing(&mut l.items);
1000 adjust_cj_at_line_boundaries(p, start, trim.layout, &mut l);
1001 adjust_glyph_stretch_at_line_end(p, &mut l);
1002 l.width = l.items.iter().map(|(_, i)| i.natural_width()).sum();
1003 Ok(l)
1004}
1005
1006fn collect_items(items: &mut Vec<(usize, Item)>, p: &Prep, start: usize, end: usize, trim: &Trim) -> Outcome<()> {
1007 let mut fallback: Option<(usize, Item)> = None;
1008 for (a, b, rtl) in reorder(p, start, end) {
1009 let from = items.len();
1010 res!(collect_range(p, a, b, trim, items, &mut fallback));
1011 if rtl {
1012 items[from..].reverse();
1013 }
1014 }
1015 if !items.iter().any(|(_, i)| matches!(i, Item::Text(_))) {
1016 if let Some(f) = fallback {
1017 items.push(f);
1018 }
1019 }
1020 Ok(())
1021}
1022
1023/// The line's ranges in visual order, each with whether it runs right to left.
1024fn reorder(p: &Prep, start: usize, end: usize) -> Vec<(usize, usize, bool)> {
1025 let levels = match &p.bidi {
1026 None => return vec![(start, end, p.config.rtl)],
1027 Some(l) => l,
1028 };
1029 if start >= end {
1030 return vec![(start, end, p.config.rtl)];
1031 }
1032 // Runs of one level, then rule L2: reverse every run at or above each level down to the lowest odd.
1033 let mut runs: Vec<(usize, usize, u8)> = Vec::new();
1034 let mut a = start;
1035 let mut cur = levels.get(start).copied().unwrap_or(0);
1036 for i in start..end {
1037 let lv = levels.get(i).copied().unwrap_or(0);
1038 if lv != cur {
1039 runs.push((a, i, cur));
1040 a = i;
1041 cur = lv;
1042 }
1043 }
1044 runs.push((a, end, cur));
1045 let hi = runs.iter().map(|r| r.2).max().unwrap_or(0);
1046 let lo = runs.iter().map(|r| r.2).filter(|l| l % 2 == 1).min().unwrap_or(hi + 1);
1047 let mut level = hi;
1048 while level >= lo && level > 0 {
1049 let mut i = 0;
1050 while i < runs.len() {
1051 if runs[i].2 >= level {
1052 let mut j = i;
1053 while j < runs.len() && runs[j].2 >= level {
1054 j += 1;
1055 }
1056 runs[i..j].reverse();
1057 i = j;
1058 } else {
1059 i += 1;
1060 }
1061 }
1062 level -= 1;
1063 }
1064 runs.into_iter().map(|(a, b, l)| (a, b, l % 2 == 1)).collect()
1065}
1066
1067fn collect_range(
1068 p: &Prep,
1069 start: usize,
1070 end: usize,
1071 trim: &Trim,
1072 items: &mut Vec<(usize, Item)>,
1073 fallback: &mut Option<(usize, Item)>,
1074)
1075 -> Outcome<()>
1076{
1077 for i in p.slice(start, end) {
1078 let (sub, item) = &p.items[i];
1079 let idx = i + 1;
1080 let shaped = match item {
1081 Item::Text(t) => t,
1082 other => {
1083 items.push((idx, other.clone()));
1084 continue;
1085 }
1086 };
1087 let a = start.max(sub.0);
1088 let b = end.min(sub.1).min(trim.shaping);
1089 let split = sub.0 < a || b < sub.1;
1090 if a >= b {
1091 *fallback = Some((idx, Item::Text(shaped.empty())));
1092 continue;
1093 }
1094 // Nothing is kept per attempt: the breaker tries several lines for every breakpoint, and a store
1095 // of each one's glyphs grew with the paragraph (2.6 GB in the browser for 20,000 words in one).
1096 // A cut run shares the item's glyphs when both its ends are safe to break, as Typst's does, so
1097 // an attempt neither copies nor reshapes; otherwise the book's bounded shape cache answers.
1098 let mut run = if split { res!(shaped.reshape(&p.book, a, b)) } else { shaped.clone() };
1099 if trim.layout < end {
1100 let lim = trim.layout;
1101 run.trim(|g| g.range.0 >= lim);
1102 }
1103 items.push((idx, Item::Text(run)));
1104 }
1105 Ok(())
1106}
1107
1108fn trim_weak_spacing(items: &mut Vec<(usize, Item)>) {
1109 let prefix = items.iter().take_while(|(_, i)| matches!(i, Item::Absolute(_, true))).count();
1110 if prefix > 0 {
1111 items.drain(..prefix);
1112 }
1113 while matches!(items.last(), Some((_, Item::Absolute(_, true)))) {
1114 items.pop();
1115 }
1116}
1117
1118fn adjust_cj_at_line_boundaries(p: &Prep, start: usize, end: usize, l: &mut Line) {
1119 let text = match p.text.get(start..end) {
1120 Some(t) => t,
1121 None => return,
1122 };
1123 let cjl = p.config.cjk_latin_spacing;
1124 if text.starts_with(BEGIN_PUNCT) || (cjl && text.chars().next().map_or(false, is_of_cj_script)) {
1125 if let Some(t) = l.leading_text_mut() {
1126 if let Some(g) = t.kept().first().cloned() {
1127 if g.is_cjk_right_aligned_punctuation() {
1128 if let Some(gm) = t.kept_mut().first_mut() {
1129 let s = gm.shrink.0;
1130 gm.shrink_left(s);
1131 }
1132 } else if cjl && g.is_cj_script() && g.x_offset > 0.0 {
1133 if let Some(gm) = t.kept_mut().first_mut() {
1134 let s = gm.x_offset;
1135 gm.x_advance -= s;
1136 gm.x_offset = 0.0;
1137 gm.shrink.0 = 0.0;
1138 }
1139 }
1140 }
1141 }
1142 }
1143 if text.ends_with(END_PUNCT) || (cjl && text.chars().next_back().map_or(false, is_of_cj_script)) {
1144 if let Some(t) = l.trailing_text_mut() {
1145 let style = ftext::cjk_punct_style(&t.props.lang, t.props.region.as_deref());
1146 if let Some(g) = t.kept().last().cloned() {
1147 if g.is_cjk_left_aligned_punctuation(style) {
1148 if let Some(gm) = t.kept_mut().last_mut() {
1149 let s = gm.shrink.1;
1150 gm.shrink_right(s);
1151 }
1152 } else if cjl && g.is_cj_script() && (g.x_advance - g.x_offset) > 1.0 {
1153 if let Some(gm) = t.kept_mut().last_mut() {
1154 let s = gm.x_advance - gm.x_offset - 1.0;
1155 gm.x_advance -= s;
1156 gm.shrink.1 = 0.0;
1157 }
1158 }
1159 }
1160 }
1161 }
1162}
1163
1164/// With glyph-level justification on, the last glyph of a line gives none, so no tracking trails it.
1165fn adjust_glyph_stretch_at_line_end(p: &Prep, l: &mut Line) {
1166 let _ = p;
1167 let limits = match l.trailing_text() {
1168 Some(t) => t.props.limits,
1169 None => return,
1170 };
1171 if limits.tracking_min == 0.0 && limits.tracking_max == 0.0 {
1172 return;
1173 }
1174 if let Some(t) = l.trailing_text_mut() {
1175 if let Some(g) = t.kept_mut().last_mut() {
1176 g.stretch = (0.0, 0.0);
1177 g.shrink = (0.0, 0.0);
1178 }
1179 }
1180}
1181
1182fn should_repeat_hyphen(lang: &str, following: &str) -> bool {
1183 match lang {
1184 "dsb" | "cs" | "hr" | "pl" | "pt" | "sk" => true,
1185 "es" => following.chars().next().map_or(false, |c| !c.is_uppercase()),
1186 _ => false,
1187 }
1188}
1189
1190/// How far a character hangs into the end margin, as a fraction of its advance.
1191pub fn overhang(c: char) -> f64 {
1192 match c {
1193 '\u{2013}' | '\u{2014}' => 0.2,
1194 '-' | '\u{00AD}' => 0.55,
1195 '.' | ',' => 0.8,
1196 ':' | ';' => 0.3,
1197 '\u{060C}' | '\u{06D4}' => 0.4,
1198 _ => 0.0,
1199 }
1200}
1201
1202/// A committed line: its box, and its extent above and below the baseline, in points.
1203#[derive(Clone, Debug)]
1204pub struct LineBox {
1205 pub node: Node,
1206 pub width: f64,
1207 pub top: f64,
1208 pub bottom: f64,
1209 pub text: String, // what the line reads, for diagnostics and the oracle comparison
1210}
1211
1212/// Commits a line to a box `width` points wide: hanging punctuation, justification, fractional spacing
1213/// and alignment, as Typst's `commit`.
1214pub fn commit(engine: &mut Engine, p: &Prep, l: &Line, width: f64, full: f64) -> Outcome<LineBox> {
1215 let hang = p.config.hanging_indent;
1216 let mut remaining = width - l.width - hang;
1217 let mut offset = 0.0f64;
1218 if !p.config.rtl {
1219 offset += hang;
1220 }
1221
1222 // Punctuation hangs into the margin: on the left only for right-to-left text, on the right for left
1223 // to right, and not for a line that is one glyph alone.
1224 if let Some(t) = l.leading_text() {
1225 if let Some(g) = t.kept().first() {
1226 if t.rtl && t.props.overhang && (l.items.len() > 1 || t.kept().len() > 1) {
1227 let amount = overhang(g.c) * g.x_advance * g.size;
1228 offset -= amount;
1229 remaining += amount;
1230 }
1231 }
1232 }
1233 if let Some(t) = l.trailing_text() {
1234 if let Some(g) = t.kept().last() {
1235 if !t.rtl && t.props.overhang && (l.items.len() > 1 || t.kept().len() > 1) {
1236 let amount = overhang(g.c) * g.x_advance * g.size;
1237 remaining += amount;
1238 }
1239 }
1240 }
1241
1242 let fr = l.fr();
1243 let mut ratio = 0.0f64;
1244 let mut extra = 0.0f64;
1245 let shrink = l.shrinkability();
1246 let stretch = l.stretchability();
1247 if remaining < 0.0 && shrink > 0.0 {
1248 ratio = (remaining / shrink).max(-1.0);
1249 remaining = (remaining + shrink).min(0.0);
1250 } else if l.justify && fr == 0.0 {
1251 if stretch > 0.0 {
1252 ratio = (remaining / stretch).min(1.0);
1253 remaining = (remaining - stretch).max(0.0);
1254 }
1255 let justifiables = l.justifiables();
1256 if justifiables > 0 && remaining > 0.0 {
1257 extra = remaining / justifiables as f64;
1258 remaining = 0.0;
1259 }
1260 }
1261
1262 // First the extent every item gives the line, then the nodes at their places, in logical order as
1263 // Typst orders a line's frames, so an element inside is met where it stands in the text.
1264 enum Placed {
1265 Text(ShapedRun, f64, f64), // the run, and its extent above and below the baseline
1266 Frame(Frame),
1267 Tag(RealiseTag),
1268 }
1269 let mut placed: Vec<(usize, f64, Placed, f64)> = Vec::new(); // (logical index, x, what, width)
1270 let mut top = 0.0f64;
1271 let mut bottom = 0.0f64;
1272 let mut cache = PropsCache::default();
1273 for (idx, item) in &l.items {
1274 match item {
1275 Item::Absolute(v, _) => offset += *v,
1276 Item::Fractional(v, elem) => {
1277 let amount = if fr > 0.0 && remaining.is_finite() { (v / fr * remaining).max(0.0) } else { 0.0 };
1278 match elem {
1279 Some(e) => {
1280 let (content, styles) = (&e.0, &e.1);
1281 let region = Region {
1282 width: Sp::from_pt(amount),
1283 height: Sp::from_pt(full),
1284 base: (Sp::from_pt(amount), Sp::from_pt(full)),
1285 expand_x: true,
1286 expand_y: false,
1287 };
1288 let f = res!(layout_inline_box(engine, content, styles, region, Some(amount), &mut cache));
1289 top = top.max(f.baseline);
1290 bottom = bottom.max(f.height - f.baseline);
1291 let w = f.width;
1292 placed.push((*idx, offset, Placed::Frame(f), w));
1293 offset += w;
1294 }
1295 None => offset += amount,
1296 }
1297 }
1298 Item::Text(t) => {
1299 let (tt, bb) = t.measure(&p.book);
1300 top = top.max(tt);
1301 bottom = bottom.max(bb);
1302 let w = justified_width(t, ratio, extra);
1303 placed.push((*idx, offset, Placed::Text(t.clone(), tt, bb), w));
1304 offset += w;
1305 }
1306 Item::Frame(f) => {
1307 top = top.max(f.baseline);
1308 bottom = bottom.max(f.height - f.baseline);
1309 placed.push((*idx, offset, Placed::Frame(f.clone()), f.width));
1310 offset += f.width;
1311 }
1312 Item::Tag(tag) => placed.push((*idx, offset, Placed::Tag(tag.clone()), 0.0)),
1313 Item::Skip(_) => (),
1314 }
1315 }
1316 if fr != 0.0 {
1317 remaining = 0.0;
1318 }
1319 let shift_x = p.config.align.position(remaining);
1320 placed.sort_by_key(|(idx, ..)| *idx);
1321
1322 // Every child sits on the line's baseline, TeX's rule: a leaf's height is its extent above the
1323 // baseline, and a frame is a box whose height is its baseline below its top.
1324 let mut nodes: Vec<Node> = Vec::new();
1325 let mut cursor = 0.0f64;
1326 for (_, x, what, w) in placed {
1327 let x = match &what {
1328 Placed::Frame(f) => x + shift_x + f.shift.0,
1329 _ => x + shift_x,
1330 };
1331 if (x - cursor).abs() > 0.0 {
1332 nodes.push(Node::Glue(Glue::fixed(Sp::from_pt(x - cursor))));
1333 }
1334 cursor = x;
1335 match what {
1336 Placed::Text(t, tt, bb) => {
1337 // A link covers the run and half the leading above and below it, as Typst's text frames do.
1338 if let (Some(link), false) = (&t.props.link, t.props.hidden) {
1339 let out = t.props.link_outset;
1340 nodes.push(link_area(link, w, tt + out, bb + out, 0.0));
1341 nodes.push(Node::Glue(Glue::fixed(Sp::from_pt(-w))));
1342 }
1343 let (ns, adv) = res!(t.build(&p.book, ratio, extra));
1344 nodes.extend(ns);
1345 cursor += adv;
1346 }
1347 Placed::Frame(f) => {
1348 if let Some(link) = &f.link {
1349 nodes.push(link_area(link, w, f.baseline, f.height - f.baseline, f.shift.1));
1350 nodes.push(Node::Glue(Glue::fixed(Sp::from_pt(-w))));
1351 }
1352 nodes.push(frame_node(&f));
1353 cursor += w;
1354 }
1355 // A located element's tags sit in the line where it stands, on its baseline: the driver records the
1356 // element for the introspector and the ledger, and a footnote's marker is found by its start tag.
1357 Placed::Tag(tag) => nodes.push(Node::Tag(tag)),
1358 }
1359 }
1360 // Rounded up, so a region taken from the line's measured width still holds the line.
1361 let dims = Dims::new(Sp::from_pt_up(width), Sp::from_pt(top), Sp::from_pt(bottom));
1362 Ok(LineBox { node: Node::HBox(BoxNode::new(nodes, dims)), width, top, bottom, text: line_text(l) })
1363}
1364
1365/// A link area: an inkless graphic `width` wide reaching `above` and `below` the baseline, lowered by
1366/// `down`, whose placement box the writers make a link.
1367fn link_area(target: &LinkTarget, width: f64, above: f64, below: f64, down: f64) -> Node {
1368 let mut g = Graphic::new(Vec::new(), Dims::new(Sp::from_pt(width), Sp::from_pt(above), Sp::from_pt(below)));
1369 g.link = Some(target.clone());
1370 Node::Leaf(Leaf::graphic(g).with_shift(Sp::from_pt(down)))
1371}
1372
1373/// A frame as a line holds it: a vertical box whose height is the frame's baseline, so it seats on the
1374/// line's baseline, its contents lowered by the frame's shift.
1375fn frame_node(f: &Frame) -> Node {
1376 let mut list = Vec::with_capacity(f.nodes.len() + 1);
1377 if f.shift.1 != 0.0 {
1378 list.push(Node::Glue(Glue::fixed(Sp::from_pt(f.shift.1))));
1379 }
1380 list.extend(f.nodes.iter().cloned());
1381 let dims = Dims::new(Sp::from_pt(f.width), Sp::from_pt(f.baseline), Sp::from_pt(f.height - f.baseline));
1382 Node::VBox(BoxNode::new(list, dims))
1383}
1384
1385/// What a line reads: its runs' kept text, an object replacement for each inline frame.
1386fn line_text(l: &Line) -> String {
1387 let mut text = String::new();
1388 for (_, item) in &l.items {
1389 match item {
1390 Item::Text(t) => {
1391 let k = t.kept();
1392 let a = k.iter().map(|g| g.range.0).min();
1393 let b = k.iter().map(|g| g.range.1).max();
1394 if let (Some(a), Some(b)) = (a, b) {
1395 text.push_str(t.text.get(a.saturating_sub(t.base)..b.saturating_sub(t.base)).unwrap_or(""));
1396 }
1397 }
1398 Item::Frame(_) => text.push('\u{FFFC}'),
1399 _ => (),
1400 }
1401 }
1402 text
1403}
1404
1405/// The width a run takes once justified.
1406fn justified_width(t: &ShapedRun, ratio: f64, extra: f64) -> f64 {
1407 let mut w = 0.0;
1408 for g in t.kept() {
1409 let left = if ratio < 0.0 { g.shrink.0 } else { g.stretch.0 };
1410 let right = if ratio < 0.0 { g.shrink.1 } else { g.stretch.1 };
1411 let mut adv = g.x_advance * g.size + (left + right) * ratio * g.size;
1412 if g.justifiable {
1413 adv += extra;
1414 }
1415 w += adv;
1416 }
1417 w
1418}
1419
1420/// Is `c` a space for justification? Re-exported for the breaker's estimates.
1421pub fn is_justifiable_space(c: char) -> bool { is_space(c) }
1422
1423/// The chain's `text.lang` in force, for a uniform-language check.
1424pub fn lang_of(styles: &StyleChain) -> Outcome<String> {
1425 Ok(match res!(text_field(styles, "lang")) {
1426 Some(Value::Str(s)) => s.to_lowercase(),
1427 _ => "en".to_string(),
1428 })
1429}
1430
1431/// The horizontal alignment the chain's `align` puts in force, fixed against the direction.
1432pub fn fixed_align(styles: &StyleChain, rtl: bool) -> Outcome<FixedAlign> {
1433 let a = res!(ftext::elem_field(styles, ElemKind::Align, "alignment"));
1434 let x = match a {
1435 Some(Value::Alignment(al)) => al.x,
1436 _ => None,
1437 };
1438 Ok(match x {
1439 None | Some(HAlign::Start) => FixedAlign::Start,
1440 Some(HAlign::End) => FixedAlign::End,
1441 Some(HAlign::Center) => FixedAlign::Center,
1442 Some(HAlign::Left) => if rtl { FixedAlign::End } else { FixedAlign::Start },
1443 Some(HAlign::Right) => if rtl { FixedAlign::Start } else { FixedAlign::End },
1444 })
1445}