Skip to main content

strata_layout/typography/
line_breaker.rs

1//! Unicode Line Breaking Algorithm (UAX #14) and CSS white-space handling.
2//!
3//! Provides opportunistic break detection, Japanese Kinsoku Shori (prohibited start/end characters),
4//! CJK ideographic wrapping, zero-width space handling, and line boundary segmentation.
5
6use super::shaper::ShapedGlyph;
7use strata_primitives::geom::LayoutUnit;
8
9/// Unicode UAX #14 Line Breaking Class.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum LineBreakClass {
12    /// Mandatory Break (\n, \r, \u{000C}).
13    BK,
14    /// Carriage Return.
15    CR,
16    /// Line Feed.
17    LF,
18    /// Zero Width Space (\u{200B}).
19    ZW,
20    /// Word Joiner (\u{2060}, \u{FEFF}).
21    WJ,
22    /// Non-breaking Glue (\u{00A0}, \u{202F}).
23    GL,
24    /// Space (' ', '\t').
25    SP,
26    /// Open Punctuation (prohibited at line end: '(', '[', '{', '(', '「', '『', '【', '《').
27    OP,
28    /// Close Punctuation (prohibited at line start: ')', ']', '}', ')', '」', '』', '】', '》', '。', '、').
29    CL,
30    /// Close Parenthesis (prohibited at line start: ')', ']', ')', ']').
31    CP,
32    /// Exclamation / Interrogation (prohibited at line start: '!', '?', '!', '?').
33    EX,
34    /// Non-starter (prohibited at line start: small kana ぁ, ぃ, っ, ゃ, prolonged sound ー).
35    NS,
36    /// Ideographic / CJK character (allows break before and after other ideographs).
37    ID,
38    /// Ordinary Alphabetic character (Latin, Cyrillic, Greek, Arabic, Hebrew).
39    AL,
40    /// Numeric digit (0..=9).
41    NU,
42    /// Hyphen ('-').
43    HY,
44    /// Break After (em-dash '—', en-dash '–', soft hyphen \u{00AD}).
45    BA,
46    /// Break Before.
47    BB,
48    /// Inseparable (ellipsis '…', '‥').
49    IN,
50    /// Infix Numeric Separator (',', '.', ':', ';').
51    IS,
52    /// Prefix Numeric ('$', '£', '¥', '€', '¢').
53    PR,
54    /// Postfix Numeric ('%', '‰', '°').
55    PO,
56    /// Unknown / Other.
57    XX,
58}
59
60/// Classifies a Unicode character according to Unicode Standard Annex #14.
61pub fn classify_line_break(c: char) -> LineBreakClass {
62    match c {
63        '\n' => LineBreakClass::LF,
64        '\r' => LineBreakClass::CR,
65        '\u{000C}' => LineBreakClass::BK,
66        '\u{200B}' => LineBreakClass::ZW,
67        '\u{2060}' | '\u{FEFF}' => LineBreakClass::WJ,
68        '\u{00A0}' | '\u{202F}' => LineBreakClass::GL,
69        ' ' | '\t' => LineBreakClass::SP,
70
71        // Open Punctuation (Gyomatsu Kinsoku - prohibited at end of line)
72        '(' | '[' | '{' | '<' | '(' | '[' | '{' | '〈' | '《' | '「' | '『' | '【' | '〔'
73        | '“' | '‘' | '«' => LineBreakClass::OP,
74
75        // Close Punctuation (Gyoto Kinsoku - prohibited at start of line)
76        ')' | ']' | '}' | '>' | ')' | ']' | '}' | '〉' | '》' | '」' | '』' | '】' | '〕'
77        | '”' | '’' | '»' | '。' | '、' | ',' | '.' => LineBreakClass::CL,
78
79        // Exclamations / Questions (Gyoto Kinsoku)
80        '!' | '?' | '!' | '?' => LineBreakClass::EX,
81
82        // Non-starter characters (Japanese Gyoto Kinsoku: small kana and prolonged sound marks)
83        'ぁ' | 'ぃ' | 'ぅ' | 'ぇ' | 'ぉ' | 'っ' | 'ゃ' | 'ゅ' | 'ょ' | 'ゎ' | 'ァ' | 'ィ'
84        | 'ゥ' | 'ェ' | 'ォ' | 'ッ' | 'ャ' | 'ュ' | 'ョ' | 'ヮ' | 'ヶ' | 'ヵ' | 'ー' | '・'
85        | ':' | ';' => LineBreakClass::NS,
86
87        // Hyphens and break-after dashes
88        '-' => LineBreakClass::HY,
89        '—' | '–' | '\u{00AD}' => LineBreakClass::BA,
90
91        // Inseparable ellipsis
92        '…' | '‥' => LineBreakClass::IN,
93
94        // Prefix and Postfix numeric
95        '$' | '£' | '¥' | '€' | '¢' | '¥' => LineBreakClass::PR,
96        '%' | '‰' | '°' => LineBreakClass::PO,
97
98        // Infix numeric separators
99        ',' | '.' | ':' | ';' => LineBreakClass::IS,
100
101        // Numeric digits
102        '0'..='9' | '٠'..='٩' => LineBreakClass::NU,
103
104        // CJK Ideographs (Hiragana, Katakana, Kanji, Hanja, Hangul)
105        '\u{4E00}'..='\u{9FFF}'
106        | '\u{3400}'..='\u{4DBF}'
107        | '\u{20000}'..='\u{2A6DF}'
108        | '\u{3040}'..='\u{309F}'
109        | '\u{30A0}'..='\u{30FF}'
110        | '\u{AC00}'..='\u{D7AF}' => LineBreakClass::ID,
111
112        _ => LineBreakClass::AL,
113    }
114}
115
116/// Returns true if character is prohibited at the start of a line (Japanese Gyoto Kinsoku).
117#[inline]
118pub fn is_prohibited_start(c: char) -> bool {
119    matches!(
120        classify_line_break(c),
121        LineBreakClass::CL | LineBreakClass::CP | LineBreakClass::EX | LineBreakClass::NS
122    )
123}
124
125/// Returns true if character is prohibited at the end of a line (Japanese Gyomatsu Kinsoku).
126#[inline]
127pub fn is_prohibited_end(c: char) -> bool {
128    matches!(
129        classify_line_break(c),
130        LineBreakClass::OP | LineBreakClass::PR
131    )
132}
133
134/// Determines whether a soft line break is permitted between two adjacent characters per UAX #14.
135pub fn can_break_between_chars(prev: char, curr: char) -> bool {
136    let p_class = classify_line_break(prev);
137    let c_class = classify_line_break(curr);
138
139    // 1. Mandatory breaks
140    if matches!(
141        p_class,
142        LineBreakClass::BK | LineBreakClass::CR | LineBreakClass::LF
143    ) {
144        return true;
145    }
146
147    // 2. Prohibited breaks (WJ, GL, Kinsoku Shori)
148    if p_class == LineBreakClass::WJ || c_class == LineBreakClass::WJ {
149        return false;
150    }
151    if p_class == LineBreakClass::GL || c_class == LineBreakClass::GL {
152        return false;
153    }
154    // Never break before close punctuation, exclamations, or non-starters (Gyoto Kinsoku)
155    if matches!(
156        c_class,
157        LineBreakClass::CL | LineBreakClass::CP | LineBreakClass::EX | LineBreakClass::NS
158    ) {
159        return false;
160    }
161    // Never break after open punctuation or currency prefix (Gyomatsu Kinsoku)
162    if matches!(p_class, LineBreakClass::OP | LineBreakClass::PR) {
163        return false;
164    }
165
166    // 3. Zero Width Space allows break after
167    if p_class == LineBreakClass::ZW {
168        return true;
169    }
170
171    // 4. Space allows break after
172    if p_class == LineBreakClass::SP {
173        return true;
174    }
175
176    // 5. CJK Ideographic breaks (ID x ID, ID x AL, AL x ID)
177    if p_class == LineBreakClass::ID && c_class == LineBreakClass::ID {
178        return true;
179    }
180    if p_class == LineBreakClass::ID
181        && (c_class == LineBreakClass::AL || c_class == LineBreakClass::NU)
182    {
183        return true;
184    }
185    if (p_class == LineBreakClass::AL || p_class == LineBreakClass::NU)
186        && c_class == LineBreakClass::ID
187    {
188        return true;
189    }
190
191    // 6. Close punctuation followed by an ideograph or word allows break
192    if matches!(p_class, LineBreakClass::CL | LineBreakClass::CP)
193        && (c_class == LineBreakClass::ID || c_class == LineBreakClass::AL)
194    {
195        return true;
196    }
197
198    // 7. Break after hyphen or dash
199    if matches!(p_class, LineBreakClass::HY | LineBreakClass::BA) {
200        return true;
201    }
202
203    false
204}
205
206/// CSS white-space property mode controlling whitespace collapsing and wrapping.
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
208pub enum WhiteSpaceMode {
209    /// Collapses consecutive whitespace; wraps on line breaks and when line exceeds width.
210    #[default]
211    Normal,
212    /// Collapses consecutive whitespace; suppresses all soft line wrapping.
213    NoWrap,
214    /// Preserves all whitespace and newlines; suppresses soft line wrapping.
215    Pre,
216    /// Preserves all whitespace and newlines; wraps lines when exceeding container width.
217    PreWrap,
218    /// Collapses consecutive whitespace; preserves explicit newlines; wraps on line bounds.
219    PreLine,
220}
221
222impl WhiteSpaceMode {
223    /// Whether consecutive whitespace characters are collapsed into a single space.
224    #[inline(always)]
225    pub fn collapses_spaces(self) -> bool {
226        matches!(
227            self,
228            WhiteSpaceMode::Normal | WhiteSpaceMode::NoWrap | WhiteSpaceMode::PreLine
229        )
230    }
231
232    /// Whether soft wrapping is allowed when line exceeds container width.
233    #[inline(always)]
234    pub fn allows_soft_wrap(self) -> bool {
235        matches!(
236            self,
237            WhiteSpaceMode::Normal | WhiteSpaceMode::PreWrap | WhiteSpaceMode::PreLine
238        )
239    }
240
241    /// Whether explicit newline characters (\n) force a line break.
242    #[inline(always)]
243    pub fn preserves_newlines(self) -> bool {
244        matches!(
245            self,
246            WhiteSpaceMode::Pre | WhiteSpaceMode::PreWrap | WhiteSpaceMode::PreLine
247        )
248    }
249}
250
251/// A segmented line of shaped glyphs resulting from the line breaking pass.
252#[derive(Debug, Clone, PartialEq)]
253pub struct TextLine {
254    /// The shaped glyphs placed on this line.
255    pub glyphs: Vec<ShapedGlyph>,
256    /// Total horizontal advance width of the line excluding trailing whitespace.
257    pub content_width: LayoutUnit,
258    /// Advance width of trailing whitespace.
259    pub trailing_space_width: LayoutUnit,
260    /// Whether this line ended with an explicit mandatory break (\n).
261    pub is_hard_break: bool,
262}
263
264/// Unicode UAX #14 Line Breaker.
265#[derive(Debug, Clone, Default)]
266pub struct LineBreaker;
267
268impl LineBreaker {
269    pub fn new() -> Self {
270        Self
271    }
272
273    /// Breaks a stream of shaped glyphs into visual lines fitting within `max_width`.
274    pub fn break_lines(
275        &self,
276        glyphs: &[ShapedGlyph],
277        max_width: Option<LayoutUnit>,
278        mode: WhiteSpaceMode,
279    ) -> Vec<TextLine> {
280        if glyphs.is_empty() {
281            return Vec::new();
282        }
283
284        let max_w = max_width.unwrap_or(LayoutUnit(i32::MAX));
285        let allows_soft_wrap = mode.allows_soft_wrap() && max_width.is_some();
286        let collapses_spaces = mode.collapses_spaces();
287
288        let mut lines = Vec::new();
289        let mut current_glyphs = Vec::new();
290        let mut current_width = LayoutUnit::ZERO;
291
292        let mut last_break_idx = None;
293        let mut prev_was_space = false;
294        let mut prev_char: Option<char> = None;
295        let mut idx = 0;
296
297        while idx < glyphs.len() {
298            let glyph = glyphs[idx];
299            let curr_char = char::from_u32(glyph.glyph_id).unwrap_or(' ');
300
301            // 1. Check for hard newline character (\n is glyph_id 10)
302            if glyph.glyph_id == 10 || glyph.glyph_id == 13 {
303                let (content_w, trailing_w) = Self::calculate_widths(&current_glyphs);
304                lines.push(TextLine {
305                    glyphs: std::mem::take(&mut current_glyphs),
306                    content_width: content_w,
307                    trailing_space_width: trailing_w,
308                    is_hard_break: true,
309                });
310                current_width = LayoutUnit::ZERO;
311                last_break_idx = None;
312                prev_was_space = false;
313                prev_char = None;
314                idx += 1;
315                continue;
316            }
317
318            // 2. Whitespace collapsing
319            if collapses_spaces && glyph.is_space {
320                if prev_was_space || current_glyphs.is_empty() {
321                    idx += 1;
322                    continue;
323                }
324                prev_was_space = true;
325            } else {
326                prev_was_space = false;
327            }
328
329            // 3. Record UAX #14 break opportunities between characters
330            if let Some(p_ch) = prev_char {
331                if can_break_between_chars(p_ch, curr_char) {
332                    last_break_idx = Some(current_glyphs.len());
333                }
334            }
335
336            // 4. Check for line overflow and break opportunity
337            let advance = glyph.x_advance;
338            let fits = current_width + advance <= max_w;
339
340            if !fits && allows_soft_wrap && !current_glyphs.is_empty() {
341                if let Some(break_pos) = last_break_idx {
342                    if break_pos > 0 && break_pos < current_glyphs.len() {
343                        let remainder: Vec<ShapedGlyph> =
344                            current_glyphs.drain(break_pos..).collect();
345                        let (content_w, trailing_w) = Self::calculate_widths(&current_glyphs);
346
347                        lines.push(TextLine {
348                            glyphs: std::mem::take(&mut current_glyphs),
349                            content_width: content_w,
350                            trailing_space_width: trailing_w,
351                            is_hard_break: false,
352                        });
353
354                        current_glyphs = remainder;
355                        current_width = current_glyphs
356                            .iter()
357                            .map(|g| g.x_advance)
358                            .fold(LayoutUnit::ZERO, |a, b| a + b);
359                        last_break_idx = None;
360                    } else {
361                        // Forced break on overflow
362                        let (content_w, trailing_w) = Self::calculate_widths(&current_glyphs);
363                        lines.push(TextLine {
364                            glyphs: std::mem::take(&mut current_glyphs),
365                            content_width: content_w,
366                            trailing_space_width: trailing_w,
367                            is_hard_break: false,
368                        });
369                        current_width = LayoutUnit::ZERO;
370                        last_break_idx = None;
371                    }
372                } else {
373                    // Forced emergency break on overflow
374                    let (content_w, trailing_w) = Self::calculate_widths(&current_glyphs);
375                    lines.push(TextLine {
376                        glyphs: std::mem::take(&mut current_glyphs),
377                        content_width: content_w,
378                        trailing_space_width: trailing_w,
379                        is_hard_break: false,
380                    });
381                    current_width = LayoutUnit::ZERO;
382                    last_break_idx = None;
383                }
384            }
385
386            current_width = current_width + advance;
387            current_glyphs.push(glyph);
388            prev_char = Some(curr_char);
389            idx += 1;
390        }
391
392        // Flush remaining line
393        if !current_glyphs.is_empty() {
394            let (content_w, trailing_w) = Self::calculate_widths(&current_glyphs);
395            lines.push(TextLine {
396                glyphs: current_glyphs,
397                content_width: content_w,
398                trailing_space_width: trailing_w,
399                is_hard_break: false,
400            });
401        }
402
403        lines
404    }
405
406    /// Computes content width and trailing space width for a set of glyphs.
407    fn calculate_widths(glyphs: &[ShapedGlyph]) -> (LayoutUnit, LayoutUnit) {
408        if glyphs.is_empty() {
409            return (LayoutUnit::ZERO, LayoutUnit::ZERO);
410        }
411
412        let mut trailing_w = LayoutUnit::ZERO;
413
414        for g in glyphs.iter().rev() {
415            if g.is_space {
416                trailing_w = trailing_w + g.x_advance;
417            } else {
418                break;
419            }
420        }
421
422        let total_w = glyphs
423            .iter()
424            .map(|g| g.x_advance)
425            .fold(LayoutUnit::ZERO, |a, b| a + b);
426        let content_w = total_w - trailing_w;
427
428        (content_w, trailing_w)
429    }
430}