Skip to main content

strata_layout/typography/
inline_context.rs

1//! Inline Formatting Context (IFC), Line Boxes, and Subpixel Vertical Alignment.
2//!
3//! Organizes shaped glyph runs into line boxes, resolves vertical alignments,
4//! and computes final subpixel layout bounds with full Blink LayoutNG parity.
5
6use super::bidi::BidiEngine;
7use super::font_metrics::{compute_half_leading, CssStrut, FontHeight, FontMetrics};
8use super::line_breaker::{LineBreaker, WhiteSpaceMode};
9use super::shaper::{ShapedGlyph, TextShaper};
10use crate::exclusions::{ExclusionSpace, LineOpportunity};
11use crate::geometry::Rect;
12use std::cell::RefCell;
13use strata_primitives::geom::LayoutUnit;
14use strata_style::types::{Color, FontStyle, FontWeight, TextDecoration};
15
16thread_local! {
17    static INLINE_LAYOUT_CACHE: std::cell::RefCell<std::collections::HashMap<u64, InlineLayoutResult>> =
18        std::cell::RefCell::new(std::collections::HashMap::new());
19    static FONT_METRICS_CACHE: std::cell::RefCell<std::collections::HashMap<(u32, u32, bool, u64), FontMetrics>> =
20        std::cell::RefCell::new(std::collections::HashMap::new());
21}
22
23/// Hashes an inline item stream and option set into a deterministic layout cache key.
24fn inline_layout_cache_key(items: &[InlineItem], options: &InlineLayoutOptions) -> u64 {
25    use std::hash::{Hash, Hasher};
26    let mut hasher = std::collections::hash_map::DefaultHasher::new();
27    // Measurement callbacks can be re-registered at runtime. Mixing the font
28    // generation into the key prevents cached geometry from an older
29    // measurement backend surviving a rebuild.
30    crate::text::font_generation().hash(&mut hasher);
31    options.font_size.to_bits().hash(&mut hasher);
32    options
33        .line_height
34        .map(|v| v.to_bits())
35        .unwrap_or(u32::MAX)
36        .hash(&mut hasher);
37    options
38        .max_width
39        .map(|v| v.to_bits())
40        .unwrap_or(u32::MAX)
41        .hash(&mut hasher);
42    (options.white_space as u8).hash(&mut hasher);
43    (options.vertical_align as u8).hash(&mut hasher);
44    options.is_monospace.hash(&mut hasher);
45    options.bfc_offset_y.to_bits().hash(&mut hasher);
46    items.len().hash(&mut hasher);
47    for item in items {
48        match item {
49            InlineItem::Text { text, style } => {
50                1u8.hash(&mut hasher);
51                text.hash(&mut hasher);
52                style.font_family.0.hash(&mut hasher);
53                style.font_size.to_bits().hash(&mut hasher);
54                (style.font_weight as u8).hash(&mut hasher);
55                (style.font_style as u8).hash(&mut hasher);
56                style.letter_spacing.to_bits().hash(&mut hasher);
57                style
58                    .line_height
59                    .map(|v| v.to_bits())
60                    .unwrap_or(u32::MAX)
61                    .hash(&mut hasher);
62                style.is_monospace.hash(&mut hasher);
63                (style.vertical_align as u8).hash(&mut hasher);
64                // Paint-only fields must participate in the key. A cached
65                // result carries cloned fragments with a full InlineTextStyle,
66                // so a hit with a different color would repaint the first
67                // run's styling for the life of the thread.
68                style.color.r.hash(&mut hasher);
69                style.color.g.hash(&mut hasher);
70                style.color.b.hash(&mut hasher);
71                style.color.a.hash(&mut hasher);
72                match style.background_color {
73                    Some(c) => {
74                        1u8.hash(&mut hasher);
75                        c.r.hash(&mut hasher);
76                        c.g.hash(&mut hasher);
77                        c.b.hash(&mut hasher);
78                        c.a.hash(&mut hasher);
79                    }
80                    None => 0u8.hash(&mut hasher),
81                }
82                (style.text_decoration as u8).hash(&mut hasher);
83                style.href.hash(&mut hasher);
84            }
85            InlineItem::Atomic {
86                node_index,
87                width,
88                height,
89                margin_left,
90                margin_right,
91                vertical_align,
92            } => {
93                2u8.hash(&mut hasher);
94                node_index.hash(&mut hasher);
95                width.to_bits().hash(&mut hasher);
96                height.to_bits().hash(&mut hasher);
97                margin_left.to_bits().hash(&mut hasher);
98                margin_right.to_bits().hash(&mut hasher);
99                (*vertical_align as u8).hash(&mut hasher);
100            }
101            InlineItem::HardBreak => 3u8.hash(&mut hasher),
102        }
103    }
104    hasher.finish()
105}
106
107/// Builds font metrics from the registered platform callback, falling back to the
108/// synthetic design-ratio metrics when no platform font backend is active.
109fn metrics_for_style(
110    font_family: strata_primitives::AtomId,
111    font_size: f32,
112    is_monospace: bool,
113) -> FontMetrics {
114    let cache_key = (
115        font_family.0,
116        font_size.to_bits(),
117        is_monospace,
118        crate::text::font_generation(),
119    );
120    if let Some(hit) = FONT_METRICS_CACHE.with(|cache| cache.borrow().get(&cache_key).copied()) {
121        return hit;
122    }
123    if let Some(callback) = crate::text::get_font_metrics() {
124        let (ascent, descent, line_gap) = callback(font_family, font_size, is_monospace);
125        if ascent > 0.0 && descent >= 0.0 {
126            let metrics = FontMetrics {
127                ascent: LayoutUnit::from_f32(ascent),
128                descent: LayoutUnit::from_f32(descent),
129                line_gap: LayoutUnit::from_f32(line_gap.max(0.0)),
130                x_height: LayoutUnit::from_f32(ascent * 0.56),
131                cap_height: LayoutUnit::from_f32(ascent * 0.78),
132                units_per_em: 1000,
133                font_size,
134            };
135            FONT_METRICS_CACHE.with(|cache| {
136                let mut map = cache.borrow_mut();
137                if map.len() >= 4096 {
138                    map.clear();
139                }
140                map.insert(cache_key, metrics);
141            });
142            return metrics;
143        }
144    }
145
146    let weight = strata_style::types::FontWeight::Normal;
147    let style = strata_style::types::FontStyle::Normal;
148    let effective_family = if is_monospace && font_family == strata_primitives::AtomId::NULL {
149        strata_primitives::AtomId::FONT_MONO
150    } else {
151        font_family
152    };
153
154    if let Some(font) =
155        crate::typography::opentype::lookup_font_for_style(effective_family, weight, style)
156    {
157        let metrics = font.font_metrics(font_size);
158        FONT_METRICS_CACHE.with(|cache| {
159            let mut map = cache.borrow_mut();
160            if map.len() >= 4096 {
161                map.clear();
162            }
163            map.insert(cache_key, metrics);
164        });
165        return metrics;
166    }
167
168    if is_monospace {
169        FontMetrics::default_mono(font_size)
170    } else {
171        FontMetrics::default_sans(font_size)
172    }
173}
174
175/// CSS vertical-align property values for inline formatting context.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
177pub enum VerticalAlignment {
178    /// Align the baseline of the element with the baseline of its parent box.
179    #[default]
180    Baseline,
181    /// Align the top of the element with the top of the entire line box.
182    Top,
183    /// Align the bottom of the element with the bottom of the entire line box.
184    Bottom,
185    /// Align the vertical midpoint of the element with baseline + half x-height.
186    Middle,
187    /// Subscript: Lower the baseline by ~20% of font size.
188    Sub,
189    /// Superscript: Raise the baseline by ~35% of font size.
190    Super,
191    /// Align the top of the element with the top of the parent element's font.
192    TextTop,
193    /// Align the bottom of the element with the bottom of the parent element's font.
194    TextBottom,
195}
196
197/// Typographic styling applied to an individual inline text run within an IFC.
198#[derive(Debug, Clone, PartialEq)]
199pub struct InlineTextStyle {
200    pub font_family: strata_primitives::AtomId,
201    pub font_size: f32,
202    pub font_weight: FontWeight,
203    pub font_style: FontStyle,
204    pub color: Color,
205    pub background_color: Option<Color>,
206    pub text_decoration: TextDecoration,
207    pub vertical_align: VerticalAlignment,
208    pub letter_spacing: f32,
209    pub line_height: Option<f32>,
210    pub is_monospace: bool,
211    pub href: Option<String>,
212}
213
214impl Default for InlineTextStyle {
215    fn default() -> Self {
216        Self {
217            font_family: strata_primitives::AtomId::FONT_SANS,
218            font_size: 16.0,
219            font_weight: FontWeight::Normal,
220            font_style: FontStyle::Normal,
221            color: Color::new(0, 0, 0, 255),
222            background_color: None,
223            text_decoration: TextDecoration::None,
224            vertical_align: VerticalAlignment::Baseline,
225            letter_spacing: 0.0,
226            line_height: None,
227            is_monospace: false,
228            href: None,
229        }
230    }
231}
232
233/// An individual item in an Inline Formatting Context stream.
234#[derive(Debug, Clone, PartialEq)]
235pub enum InlineItem {
236    /// Text content with specific typographic styling.
237    Text {
238        text: String,
239        style: InlineTextStyle,
240    },
241    /// An atomic inline element (e.g. <img>, inline <button>, <input>).
242    Atomic {
243        node_index: usize,
244        width: f32,
245        height: f32,
246        margin_left: f32,
247        margin_right: f32,
248        vertical_align: VerticalAlignment,
249    },
250    /// Forced hard line break (<br>).
251    HardBreak,
252}
253
254impl InlineItem {
255    pub fn text(text: impl Into<String>, style: InlineTextStyle) -> Self {
256        Self::Text {
257            text: text.into(),
258            style,
259        }
260    }
261
262    pub fn atomic(
263        node_index: usize,
264        width: f32,
265        height: f32,
266        margin_left: f32,
267        margin_right: f32,
268        vertical_align: VerticalAlignment,
269    ) -> Self {
270        Self::Atomic {
271            node_index,
272            width,
273            height,
274            margin_left,
275            margin_right,
276            vertical_align,
277        }
278    }
279
280    pub fn hard_break() -> Self {
281        Self::HardBreak
282    }
283}
284
285/// A visual fragment of an inline text run positioned on a specific line box.
286#[derive(Debug, Clone, PartialEq)]
287pub struct TextFragment {
288    /// Bounding rectangle in container coordinate space (x, y, width, height).
289    pub bounds: Rect,
290    /// Substring of the originating inline item positioned on this line.
291    pub text: String,
292    /// Baseline vertical offset from the container top.
293    pub baseline_y: f32,
294    /// Typographic style applied to this fragment.
295    pub style: InlineTextStyle,
296    /// Requested font family atom used for glyph advances and paint selection.
297    pub font_family: strata_primitives::AtomId,
298    /// Originating inline item index in the IFC stream.
299    pub item_index: usize,
300}
301
302/// A positioned atomic inline fragment on a line box.
303#[derive(Debug, Clone, PartialEq)]
304pub struct AtomicFragment {
305    /// Bounding rectangle in container coordinate space.
306    pub bounds: Rect,
307    /// Child node index in the parent's children array.
308    pub node_index: usize,
309}
310
311/// A positioned inline line box representing a single rendered text line.
312#[derive(Debug, Clone, PartialEq)]
313pub struct LineBox {
314    /// Bounding rectangle in container coordinate space (x, y, width, height).
315    pub bounds: Rect,
316    /// Distance from the top of the line box to the dominant baseline.
317    pub baseline: f32,
318    /// Ascent and descent bounds encompassing all inline items on this line.
319    pub metrics: FontHeight,
320    /// Positioned glyphs on this line.
321    pub glyphs: Vec<ShapedGlyph>,
322    /// Visual text fragments positioned on this line.
323    pub text_fragments: Vec<TextFragment>,
324    /// Positioned atomic inline boxes on this line.
325    pub atomic_fragments: Vec<AtomicFragment>,
326    /// Whether this line was terminated by a hard newline.
327    pub is_hard_break: bool,
328}
329
330/// Options configuring inline text layout.
331#[derive(Debug, Clone, Copy)]
332pub struct InlineLayoutOptions<'a> {
333    /// Font size in CSS pixels.
334    pub font_size: f32,
335    /// Explicit CSS line-height in pixels, or None for 'normal' (~1.2x).
336    pub line_height: Option<f32>,
337    /// Container max-width constraint for wrapping.
338    pub max_width: Option<f32>,
339    /// Whitespace handling mode.
340    pub white_space: WhiteSpaceMode,
341    /// Vertical alignment mode.
342    pub vertical_align: VerticalAlignment,
343    /// Whether font is monospace (disables ligatures and kerning).
344    pub is_monospace: bool,
345    /// Active exclusion space for float obstructions.
346    pub exclusion_space: Option<&'a ExclusionSpace>,
347    /// Container vertical origin offset within the BFC for float alignment.
348    pub bfc_offset_y: f32,
349}
350
351impl<'a> Default for InlineLayoutOptions<'a> {
352    fn default() -> Self {
353        Self {
354            font_size: 16.0,
355            line_height: None,
356            max_width: None,
357            white_space: WhiteSpaceMode::Normal,
358            vertical_align: VerticalAlignment::Baseline,
359            is_monospace: false,
360            exclusion_space: None,
361            bfc_offset_y: 0.0,
362        }
363    }
364}
365
366/// Complete measurement and geometry result of an inline layout pass.
367#[derive(Debug, Clone, PartialEq)]
368pub struct InlineLayoutResult {
369    /// The formatted line boxes.
370    pub lines: Vec<LineBox>,
371    /// Maximum bounding width across all line boxes.
372    pub total_width: f32,
373    /// Total vertical height of all stacked line boxes.
374    pub total_height: f32,
375    /// Line box count.
376    pub line_count: usize,
377}
378
379/// Returns true if a token cannot begin a new line per Unicode UAX #14 (Japanese Kinsoku Shori Gyoto Kinsoku).
380#[inline]
381pub fn is_prohibited_line_start(text: &str) -> bool {
382    let mut chars = text.chars();
383    match chars.next() {
384        Some(c) => super::line_breaker::is_prohibited_start(c),
385        None => false,
386    }
387}
388
389/// Returns true if a token cannot end a line per Unicode UAX #14 (Japanese Kinsoku Shori Gyomatsu Kinsoku).
390#[inline]
391pub fn is_prohibited_line_end(text: &str) -> bool {
392    let trimmed = text.trim_end_matches([' ', '\t']);
393    if trimmed.len() != text.len() {
394        return false;
395    }
396    match trimmed.chars().last() {
397        Some(c) => super::line_breaker::is_prohibited_end(c),
398        None => false,
399    }
400}
401
402/// Returns true if a soft line break is permitted between two adjacent inline tokens per UAX #14.
403#[inline]
404fn can_break_between(prev: &InlineToken, next: &InlineToken) -> bool {
405    if prev.is_hard_break || next.is_hard_break {
406        return true;
407    }
408    if is_prohibited_line_start(&next.text) || is_prohibited_line_end(&prev.text) {
409        return false;
410    }
411    if let (Some(p_ch), Some(n_ch)) = (prev.text.chars().last(), next.text.chars().next()) {
412        if super::line_breaker::can_break_between_chars(p_ch, n_ch) {
413            return true;
414        }
415    }
416    prev.can_break_after || next.atomic.is_some()
417}
418
419/// Internal intermediate token for breaking and measuring the inline stream.
420#[derive(Debug, Clone)]
421struct InlineToken {
422    item_index: usize,
423    text: String,
424    style: InlineTextStyle,
425    glyphs: Vec<ShapedGlyph>,
426    width: f32,
427    can_break_after: bool,
428    is_hard_break: bool,
429    is_whitespace_only: bool,
430    atomic: Option<AtomicInlineData>,
431}
432
433#[derive(Debug, Clone)]
434struct AtomicInlineData {
435    node_index: usize,
436    width: f32,
437    height: f32,
438    margin_left: f32,
439    margin_right: f32,
440    #[allow(dead_code)]
441    vertical_align: VerticalAlignment,
442}
443
444/// High-performance Inline Formatting Context engine.
445#[derive(Debug, Clone, Default)]
446pub struct InlineFormattingContext {
447    bidi: BidiEngine,
448    shaper: TextShaper,
449    #[allow(dead_code)]
450    line_breaker: LineBreaker,
451}
452
453impl InlineFormattingContext {
454    pub fn new() -> Self {
455        Self {
456            bidi: BidiEngine::new(),
457            shaper: TextShaper::new(),
458            line_breaker: LineBreaker::new(),
459        }
460    }
461
462    /// Helper to emit a shaped text token.
463    fn make_text_token(
464        &self,
465        item_index: usize,
466        text: String,
467        style: &InlineTextStyle,
468        font_metrics: &FontMetrics,
469        can_break_after: bool,
470    ) -> InlineToken {
471        let is_whitespace_only = text.chars().all(|c| c.is_whitespace() || c == '\u{00A0}');
472        let bidi_runs = self.bidi.resolve_runs(&text);
473        let mut shaped = Vec::new();
474
475        let opt_font = super::opentype::lookup_font_for_style(
476            style.font_family,
477            style.font_weight,
478            style.font_style,
479        );
480
481        for run in bidi_runs {
482            let run_slice = &text[run.start..run.end];
483            let mut run_glyphs = if let Some(ref font) = opt_font {
484                self.shaper
485                    .shape_with_font(run_slice, font, style.font_size)
486            } else {
487                self.shaper
488                    .shape(run_slice, font_metrics, style.is_monospace)
489            };
490            if run.is_rtl {
491                run_glyphs.reverse();
492            }
493            shaped.extend(run_glyphs);
494        }
495
496        let mut token_width = 0.0f32;
497        for g in &shaped {
498            token_width += g.x_advance.to_f32();
499        }
500
501        if crate::text::get_family_styled_text_measurer().is_some() {
502            let (meas_w, _) = crate::text::measure_text_bounds_styled_with_family(
503                &text,
504                style.font_size,
505                1.0,
506                None,
507                style.is_monospace,
508                style.font_family,
509                style.font_weight,
510                style.font_style,
511            );
512            if token_width > 0.0 && meas_w > 0.0 {
513                let scale = meas_w / token_width;
514                for g in &mut shaped {
515                    g.x_advance = LayoutUnit::from_f32(g.x_advance.to_f32() * scale);
516                }
517                token_width = meas_w;
518            } else if meas_w > 0.0 {
519                token_width = meas_w;
520            }
521        } else if crate::text::get_family_text_measurer().is_some() {
522            let (meas_w, _) = crate::text::measure_text_bounds_with_family(
523                &text,
524                style.font_size,
525                1.0,
526                None,
527                style.is_monospace,
528                style.font_family,
529            );
530            if token_width > 0.0 && meas_w > 0.0 {
531                let scale = meas_w / token_width;
532                for g in &mut shaped {
533                    g.x_advance = LayoutUnit::from_f32(g.x_advance.to_f32() * scale);
534                }
535                token_width = meas_w;
536            } else if meas_w > 0.0 {
537                token_width = meas_w;
538            }
539        } else if let Some(styled_measurer) = crate::text::get_styled_text_measurer() {
540            let (meas_w, _) = styled_measurer(
541                &text,
542                style.font_size,
543                1.0,
544                None,
545                style.is_monospace,
546                style.font_weight,
547                style.font_style,
548            );
549            if token_width > 0.0 && meas_w > 0.0 {
550                let scale = meas_w / token_width;
551                for g in &mut shaped {
552                    g.x_advance = LayoutUnit::from_f32(g.x_advance.to_f32() * scale);
553                }
554                token_width = meas_w;
555            } else if meas_w > 0.0 {
556                token_width = meas_w;
557            }
558        } else if crate::text::get_text_measurer().is_some() {
559            let (meas_w, _) = crate::text::measure_text_bounds_ext(
560                &text,
561                style.font_size,
562                1.0,
563                None,
564                style.is_monospace,
565            );
566            if token_width > 0.0 && meas_w > 0.0 {
567                let scale = meas_w / token_width;
568                for g in &mut shaped {
569                    g.x_advance = LayoutUnit::from_f32(g.x_advance.to_f32() * scale);
570                }
571                token_width = meas_w;
572            } else if meas_w > 0.0 {
573                token_width = meas_w;
574            }
575        }
576
577        InlineToken {
578            item_index,
579            text,
580            style: style.clone(),
581            glyphs: shaped,
582            width: token_width,
583            can_break_after,
584            is_hard_break: false,
585            is_whitespace_only,
586            atomic: None,
587        }
588    }
589
590    /// Lays out a heterogeneous stream of inline phrasing items (text runs, atomic boxes, hard breaks).
591    pub fn layout_inline_stream(
592        &self,
593        items: &[InlineItem],
594        options: &InlineLayoutOptions,
595    ) -> InlineLayoutResult {
596        let _prof = crate::prof::Scope::new(crate::prof::Slot::Inline);
597        let cacheable = options.exclusion_space.is_none();
598        let cache_key = if cacheable {
599            Some(inline_layout_cache_key(items, options))
600        } else {
601            None
602        };
603        if let Some(key) = cache_key {
604            let cached = INLINE_LAYOUT_CACHE.with(|cache| {
605                let cache: &RefCell<std::collections::HashMap<u64, InlineLayoutResult>> = cache;
606                cache.borrow().get(&key).cloned()
607            });
608            if let Some(result) = cached {
609                return result;
610            }
611        }
612
613        let result = self.layout_inline_stream_inner(items, options);
614        if let (Some(key), true) = (cache_key, cacheable) {
615            INLINE_LAYOUT_CACHE.with(|cache| {
616                let cache: &RefCell<std::collections::HashMap<u64, InlineLayoutResult>> = cache;
617                let mut map = cache.borrow_mut();
618                if map.len() >= 512 {
619                    map.clear();
620                }
621                map.insert(key, result.clone());
622            });
623        }
624        result
625    }
626
627    fn layout_inline_stream_inner(
628        &self,
629        items: &[InlineItem],
630        options: &InlineLayoutOptions,
631    ) -> InlineLayoutResult {
632        let strut_family = items
633            .iter()
634            .find_map(|item| match item {
635                InlineItem::Text { style, .. } => Some(style.font_family),
636                _ => None,
637            })
638            .unwrap_or(strata_primitives::AtomId::FONT_SANS);
639        let strut_metrics =
640            metrics_for_style(strut_family, options.font_size, options.is_monospace);
641        let strut = CssStrut::new(&strut_metrics, options.line_height);
642
643        if items.is_empty() {
644            let height = strut.line_height.to_f32();
645            return InlineLayoutResult {
646                lines: Vec::new(),
647                total_width: 0.0,
648                total_height: height,
649                line_count: 0,
650            };
651        }
652
653        // 1. Tokenize stream into break units
654        let mut tokens: Vec<InlineToken> = Vec::new();
655        for (item_idx, item) in items.iter().enumerate() {
656            match item {
657                InlineItem::HardBreak => {
658                    tokens.push(InlineToken {
659                        item_index: item_idx,
660                        text: String::new(),
661                        style: InlineTextStyle::default(),
662                        glyphs: Vec::new(),
663                        width: 0.0,
664                        can_break_after: true,
665                        is_hard_break: true,
666                        is_whitespace_only: false,
667                        atomic: None,
668                    });
669                }
670                InlineItem::Atomic {
671                    node_index,
672                    width,
673                    height,
674                    margin_left,
675                    margin_right,
676                    vertical_align,
677                } => {
678                    tokens.push(InlineToken {
679                        item_index: item_idx,
680                        text: String::new(),
681                        style: InlineTextStyle::default(),
682                        glyphs: Vec::new(),
683                        width: margin_left + width + margin_right,
684                        can_break_after: true,
685                        is_hard_break: false,
686                        is_whitespace_only: false,
687                        atomic: Some(AtomicInlineData {
688                            node_index: *node_index,
689                            width: *width,
690                            height: *height,
691                            margin_left: *margin_left,
692                            margin_right: *margin_right,
693                            vertical_align: *vertical_align,
694                        }),
695                    });
696                }
697                InlineItem::Text { text, style } => {
698                    if text.is_empty() {
699                        continue;
700                    }
701
702                    let font_metrics =
703                        metrics_for_style(style.font_family, style.font_size, style.is_monospace);
704
705                    let mut current_word = String::new();
706                    for ch in text.chars() {
707                        if ch == '\n' {
708                            if !current_word.is_empty() {
709                                tokens.push(self.make_text_token(
710                                    item_idx,
711                                    std::mem::take(&mut current_word),
712                                    style,
713                                    &font_metrics,
714                                    true,
715                                ));
716                            }
717                            tokens.push(InlineToken {
718                                item_index: item_idx,
719                                text: String::new(),
720                                style: style.clone(),
721                                glyphs: Vec::new(),
722                                width: 0.0,
723                                can_break_after: true,
724                                is_hard_break: true,
725                                is_whitespace_only: false,
726                                atomic: None,
727                            });
728                        } else if ch == ' ' || ch == '\t' {
729                            if !current_word.is_empty() {
730                                current_word.push(ch);
731                                tokens.push(self.make_text_token(
732                                    item_idx,
733                                    std::mem::take(&mut current_word),
734                                    style,
735                                    &font_metrics,
736                                    true,
737                                ));
738                            } else {
739                                if !options.white_space.collapses_spaces()
740                                    || tokens.is_empty()
741                                    || !tokens.last().is_some_and(|t| t.text.ends_with(' '))
742                                {
743                                    current_word.push(ch);
744                                    tokens.push(self.make_text_token(
745                                        item_idx,
746                                        std::mem::take(&mut current_word),
747                                        style,
748                                        &font_metrics,
749                                        true,
750                                    ));
751                                }
752                            }
753                        } else if ch == '-' || ch == '\u{2010}' || ch == '\u{00AD}' {
754                            current_word.push(ch);
755                            tokens.push(self.make_text_token(
756                                item_idx,
757                                std::mem::take(&mut current_word),
758                                style,
759                                &font_metrics,
760                                true,
761                            ));
762                        } else if ch == '\u{200B}' {
763                            if !current_word.is_empty() {
764                                tokens.push(self.make_text_token(
765                                    item_idx,
766                                    std::mem::take(&mut current_word),
767                                    style,
768                                    &font_metrics,
769                                    true,
770                                ));
771                            }
772                        } else if ('\u{4E00}'..='\u{9FFF}').contains(&ch)
773                            || ('\u{3400}'..='\u{4DBF}').contains(&ch)
774                            || ('\u{3040}'..='\u{30FF}').contains(&ch)
775                            || ('\u{AC00}'..='\u{D7AF}').contains(&ch)
776                            || ('\u{3000}'..='\u{303F}').contains(&ch)
777                            || ('\u{FF01}'..='\u{FF60}').contains(&ch)
778                        {
779                            if !current_word.is_empty() {
780                                tokens.push(self.make_text_token(
781                                    item_idx,
782                                    std::mem::take(&mut current_word),
783                                    style,
784                                    &font_metrics,
785                                    true,
786                                ));
787                            }
788                            let can_break_after = !super::line_breaker::is_prohibited_end(ch);
789                            let mut cjk_str = String::new();
790                            cjk_str.push(ch);
791                            tokens.push(self.make_text_token(
792                                item_idx,
793                                cjk_str,
794                                style,
795                                &font_metrics,
796                                can_break_after,
797                            ));
798                        } else {
799                            current_word.push(ch);
800                        }
801                    }
802
803                    if !current_word.is_empty() {
804                        tokens.push(self.make_text_token(
805                            item_idx,
806                            current_word,
807                            style,
808                            &font_metrics,
809                            false,
810                        ));
811                    }
812                }
813            }
814        }
815
816        if tokens.is_empty() {
817            let height = strut.line_height.to_f32();
818            return InlineLayoutResult {
819                lines: Vec::new(),
820                total_width: 0.0,
821                total_height: height,
822                line_count: 0,
823            };
824        }
825
826        // 2. Line breaking and assembly pass with dynamic exclusion opportunities
827        let container_w = options.max_width.unwrap_or(f32::MAX);
828        let allows_soft_wrap =
829            options.white_space.allows_soft_wrap() && options.max_width.is_some();
830
831        let mut line_boxes: Vec<LineBox> = Vec::new();
832        let mut current_y = 0.0f32;
833        let mut max_total_width = 0.0f32;
834
835        let mut token_idx = 0;
836        let num_tokens = tokens.len();
837
838        while token_idx < num_tokens {
839            let line_start_idx = token_idx;
840            let mut line_tokens: Vec<InlineToken> = Vec::new();
841            let mut line_width = 0.0f32;
842            let mut is_hard_break = false;
843
844            // Estimate line height for exclusion query
845            let est_line_height = strut.line_height.to_f32();
846            let bfc_y = options.bfc_offset_y + current_y;
847
848            let opp = if let Some(es) = options.exclusion_space {
849                es.line_opportunity(bfc_y, est_line_height, container_w)
850            } else {
851                LineOpportunity {
852                    start_x: 0.0,
853                    available_width: container_w,
854                    left_float_edge: 0.0,
855                    right_float_edge: container_w,
856                }
857            };
858
859            // If available width is too narrow (< 20px) and floats exist, drop down past the float
860            if opp.available_width < 20.0 && container_w > 50.0 {
861                if let Some(es) = options.exclusion_space {
862                    if let Some(next_bottom) = es.next_float_bottom_after(bfc_y) {
863                        current_y = next_bottom - options.bfc_offset_y;
864                        continue;
865                    }
866                }
867            }
868
869            while token_idx < num_tokens {
870                let tok = &tokens[token_idx];
871
872                if tok.is_hard_break {
873                    is_hard_break = true;
874                    token_idx += 1;
875                    break;
876                }
877
878                // Skip leading whitespace on newly wrapped line
879                if line_tokens.is_empty()
880                    && tok.is_whitespace_only
881                    && options.white_space.collapses_spaces()
882                {
883                    token_idx += 1;
884                    continue;
885                }
886
887                // Group contiguous tokens without a valid break point between them (e.g. "version.[30]")
888                let mut cluster_end = token_idx + 1;
889                while cluster_end < num_tokens
890                    && !tokens[cluster_end].is_hard_break
891                    && !can_break_between(&tokens[cluster_end - 1], &tokens[cluster_end])
892                {
893                    cluster_end += 1;
894                }
895                let cluster_width: f32 =
896                    tokens[token_idx..cluster_end].iter().map(|t| t.width).sum();
897
898                if allows_soft_wrap
899                    && !line_tokens.is_empty()
900                    && (line_width + cluster_width > opp.available_width + 0.5)
901                    && line_tokens
902                        .last()
903                        .is_none_or(|prev| can_break_between(prev, tok))
904                {
905                    break;
906                }
907
908                // If line is empty and unbreakable cluster exceeds available_width:
909                // Check if dropping past float gives more width
910                if line_tokens.is_empty()
911                    && allows_soft_wrap
912                    && cluster_width > opp.available_width + 0.5
913                    && opp.available_width < container_w
914                {
915                    if let Some(es) = options.exclusion_space {
916                        if let Some(next_bottom) = es.next_float_bottom_after(bfc_y) {
917                            current_y = next_bottom - options.bfc_offset_y;
918                            break;
919                        }
920                    }
921                }
922
923                for tok in &tokens[token_idx..cluster_end] {
924                    line_width += tok.width;
925                    line_tokens.push(tok.clone());
926                }
927                token_idx = cluster_end;
928            }
929
930            // If we broke because of float drop-down on empty line, retry
931            if line_tokens.is_empty() && !is_hard_break {
932                if token_idx == line_start_idx {
933                    // Force consume at least one token to avoid infinite loop
934                    line_tokens.push(tokens[token_idx].clone());
935                    token_idx += 1;
936                } else {
937                    continue;
938                }
939            }
940
941            // Assemble LineBox for this line
942            let has_text_tokens = line_tokens
943                .iter()
944                .any(|tok| tok.atomic.is_none() && !tok.is_whitespace_only);
945            let (mut line_max_ascent, mut line_max_descent) = if has_text_tokens {
946                (
947                    strut.metrics.ascent.to_f32(),
948                    strut.metrics.descent.to_f32(),
949                )
950            } else {
951                (0.0f32, 0.0f32)
952            };
953
954            for tok in &line_tokens {
955                if let Some(ref at) = tok.atomic {
956                    line_max_ascent = line_max_ascent.max(at.height);
957                } else {
958                    let tok_metrics = metrics_for_style(
959                        tok.style.font_family,
960                        tok.style.font_size,
961                        tok.style.is_monospace,
962                    );
963                    let lh = tok
964                        .style
965                        .line_height
966                        .unwrap_or_else(|| tok_metrics.default_line_height().to_f32());
967                    let (la, lb) = compute_half_leading(
968                        LayoutUnit::from_f32(lh),
969                        tok_metrics.ascent,
970                        tok_metrics.descent,
971                    );
972                    let a = (tok_metrics.ascent + la).to_f32();
973                    let d = (tok_metrics.descent + lb).to_f32();
974                    line_max_ascent = line_max_ascent.max(a);
975                    line_max_descent = line_max_descent.max(d);
976                }
977            }
978
979            let actual_line_height = line_max_ascent + line_max_descent;
980            let base_vertical_shift = match options.vertical_align {
981                VerticalAlignment::Baseline => 0.0,
982                VerticalAlignment::Top => {
983                    -((strut.line_height - strut_metrics.natural_height()).to_f32() / 2.0)
984                }
985                VerticalAlignment::Bottom => {
986                    (strut.line_height - strut_metrics.natural_height()).to_f32() / 2.0
987                }
988                VerticalAlignment::Middle => {
989                    (strut_metrics.x_height.to_f32() / 2.0) - (options.font_size * 0.25)
990                }
991                VerticalAlignment::Sub => options.font_size * 0.20,
992                VerticalAlignment::Super => -(options.font_size * 0.35),
993                VerticalAlignment::TextTop => 0.0,
994                VerticalAlignment::TextBottom => 0.0,
995            };
996            let line_baseline = line_max_ascent + base_vertical_shift;
997
998            let mut text_fragments = Vec::new();
999            let mut atomic_fragments = Vec::new();
1000            let mut line_glyphs = Vec::new();
1001            let mut cur_x = opp.start_x;
1002
1003            let mut idx = 0;
1004            while idx < line_tokens.len() {
1005                let tok = &line_tokens[idx];
1006                if let Some(ref at) = tok.atomic {
1007                    let ax = cur_x + at.margin_left;
1008                    let ay = current_y + (line_baseline - at.height);
1009                    atomic_fragments.push(AtomicFragment {
1010                        bounds: Rect::from_xywh(ax, ay, at.width, at.height),
1011                        node_index: at.node_index,
1012                    });
1013                    cur_x += at.margin_left + at.width + at.margin_right;
1014                    idx += 1;
1015                } else {
1016                    let target_item = tok.item_index;
1017                    let target_style = tok.style.clone();
1018                    let mut merged_text = String::new();
1019                    let mut merged_width = 0.0f32;
1020                    let start_x = cur_x;
1021
1022                    while idx < line_tokens.len() {
1023                        let t = &line_tokens[idx];
1024                        if t.atomic.is_some()
1025                            || t.item_index != target_item
1026                            || t.style != target_style
1027                        {
1028                            break;
1029                        }
1030                        merged_text.push_str(&t.text);
1031                        merged_width += t.width;
1032                        line_glyphs.extend_from_slice(&t.glyphs);
1033                        cur_x += t.width;
1034                        idx += 1;
1035                    }
1036
1037                    // Pango paints the merged fragment as one continuously shaped
1038                    // string, whose advance is slightly wider than the sum of the
1039                    // individually measured token widths. Measure the merged run so
1040                    // the fragment width and the cursor advance match paint.
1041                    let frag_width = if crate::text::get_family_styled_text_measurer().is_some() {
1042                        let (measured_w, _) = crate::text::measure_text_bounds_styled_with_family(
1043                            &merged_text,
1044                            target_style.font_size,
1045                            1.0,
1046                            None,
1047                            target_style.is_monospace,
1048                            target_style.font_family,
1049                            target_style.font_weight,
1050                            target_style.font_style,
1051                        );
1052                        if measured_w > 0.0 {
1053                            measured_w
1054                        } else {
1055                            merged_width
1056                        }
1057                    } else {
1058                        merged_width
1059                    };
1060                    // Replace the accumulated token-sum advance with the continuous
1061                    // width so the next fragment starts at the painted position.
1062                    cur_x += frag_width - merged_width;
1063
1064                    let tok_metrics = metrics_for_style(
1065                        target_style.font_family,
1066                        target_style.font_size,
1067                        target_style.is_monospace,
1068                    );
1069
1070                    let vertical_shift = match target_style.vertical_align {
1071                        VerticalAlignment::Baseline => 0.0,
1072                        VerticalAlignment::Top => -(line_max_ascent - tok_metrics.ascent.to_f32()),
1073                        VerticalAlignment::Bottom => {
1074                            line_max_descent - tok_metrics.descent.to_f32()
1075                        }
1076                        VerticalAlignment::Middle => {
1077                            (tok_metrics.x_height.to_f32() / 2.0) - (target_style.font_size * 0.25)
1078                        }
1079                        VerticalAlignment::Sub => target_style.font_size * 0.20,
1080                        VerticalAlignment::Super => -(target_style.font_size * 0.35),
1081                        VerticalAlignment::TextTop => 0.0,
1082                        VerticalAlignment::TextBottom => 0.0,
1083                    };
1084
1085                    let frag_baseline = current_y + line_baseline + vertical_shift;
1086                    let frag_y = frag_baseline - tok_metrics.ascent.to_f32();
1087                    let frag_h = (tok_metrics.ascent + tok_metrics.descent).to_f32();
1088
1089                    text_fragments.push(TextFragment {
1090                        bounds: Rect::from_xywh(start_x, frag_y, frag_width, frag_h),
1091                        text: merged_text,
1092                        baseline_y: frag_baseline,
1093                        font_family: target_style.font_family,
1094                        style: target_style,
1095                        item_index: target_item,
1096                    });
1097                }
1098            }
1099
1100            let line_box_width = cur_x - opp.start_x;
1101            if cur_x > max_total_width {
1102                max_total_width = cur_x;
1103            }
1104
1105            line_boxes.push(LineBox {
1106                bounds: Rect::from_xywh(opp.start_x, current_y, line_box_width, actual_line_height),
1107                baseline: line_baseline,
1108                metrics: FontHeight::new(
1109                    LayoutUnit::from_f32(line_max_ascent),
1110                    LayoutUnit::from_f32(line_max_descent),
1111                ),
1112                glyphs: line_glyphs,
1113                text_fragments,
1114                atomic_fragments,
1115                is_hard_break,
1116            });
1117
1118            current_y += actual_line_height;
1119        }
1120
1121        let total_lines = line_boxes.len();
1122        let total_height = if total_lines == 0 {
1123            strut.line_height.to_f32()
1124        } else {
1125            current_y
1126        };
1127
1128        InlineLayoutResult {
1129            lines: line_boxes,
1130            total_width: max_total_width,
1131            total_height,
1132            line_count: total_lines,
1133        }
1134    }
1135
1136    /// Formats input text into positioned line boxes, honoring metrics, BiDi, and line breaks.
1137    pub fn layout_text(&self, text: &str, options: &InlineLayoutOptions) -> InlineLayoutResult {
1138        if options.exclusion_space.is_none() && text.len() >= 8192 && text.contains("\n\n") {
1139            let paragraphs: Vec<&str> = text.split("\n\n").collect();
1140            if paragraphs.len() >= 2 {
1141                return self.layout_text_parallel(&paragraphs, options);
1142            }
1143        }
1144        let style = InlineTextStyle {
1145            font_size: options.font_size,
1146            vertical_align: options.vertical_align,
1147            line_height: options.line_height,
1148            is_monospace: options.is_monospace,
1149            ..Default::default()
1150        };
1151        let item = InlineItem::Text {
1152            text: text.to_string(),
1153            style,
1154        };
1155        self.layout_inline_stream(&[item], options)
1156    }
1157
1158    fn layout_text_parallel(
1159        &self,
1160        paragraphs: &[&str],
1161        options: &InlineLayoutOptions,
1162    ) -> InlineLayoutResult {
1163        let strut_family = strata_primitives::AtomId::FONT_SANS;
1164        let strut_metrics =
1165            metrics_for_style(strut_family, options.font_size, options.is_monospace);
1166        let strut = CssStrut::new(&strut_metrics, options.line_height);
1167        let empty_line_h = strut.line_height.to_f32();
1168
1169        // Process paragraphs in parallel using std::thread::scope
1170        let results: Vec<InlineLayoutResult> = std::thread::scope(|s| {
1171            let mut handles = Vec::with_capacity(paragraphs.len());
1172            for &para in paragraphs {
1173                let opts = *options;
1174                let h = s.spawn(move || {
1175                    let ifc = InlineFormattingContext::new();
1176                    let style = InlineTextStyle {
1177                        font_size: opts.font_size,
1178                        vertical_align: opts.vertical_align,
1179                        line_height: opts.line_height,
1180                        is_monospace: opts.is_monospace,
1181                        ..Default::default()
1182                    };
1183                    let item = InlineItem::Text {
1184                        text: para.to_string(),
1185                        style,
1186                    };
1187                    ifc.layout_inline_stream(&[item], &opts)
1188                });
1189                handles.push(h);
1190            }
1191            handles.into_iter().map(|h| h.join().unwrap()).collect()
1192        });
1193
1194        // Merge results sequentially preserving correct Y coordinates and line boxes
1195        let mut merged_lines = Vec::new();
1196        let mut current_y = 0.0f32;
1197        let mut max_width = 0.0f32;
1198
1199        for (i, mut res) in results.into_iter().enumerate() {
1200            max_width = max_width.max(res.total_width);
1201            for line in &mut res.lines {
1202                line.bounds.y += current_y;
1203                for frag in &mut line.text_fragments {
1204                    frag.bounds.y += current_y;
1205                    frag.baseline_y += current_y;
1206                }
1207                for frag in &mut line.atomic_fragments {
1208                    frag.bounds.y += current_y;
1209                }
1210            }
1211            merged_lines.extend(res.lines);
1212            current_y += res.total_height;
1213
1214            if i + 1 < paragraphs.len() {
1215                merged_lines.push(LineBox {
1216                    bounds: Rect::from_xywh(0.0, current_y, 0.0, empty_line_h),
1217                    baseline: strut_metrics.ascent.to_f32(),
1218                    metrics: FontHeight::new(strut_metrics.ascent, strut_metrics.descent),
1219                    glyphs: Vec::new(),
1220                    text_fragments: Vec::new(),
1221                    atomic_fragments: Vec::new(),
1222                    is_hard_break: true,
1223                });
1224                current_y += empty_line_h;
1225            }
1226        }
1227
1228        let total_lines = merged_lines.len();
1229        InlineLayoutResult {
1230            lines: merged_lines,
1231            total_width: max_width,
1232            total_height: current_y,
1233            line_count: total_lines,
1234        }
1235    }
1236}