strata_layout/typography/
line_breaker.rs1use super::shaper::ShapedGlyph;
7use strata_primitives::geom::LayoutUnit;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum LineBreakClass {
12 BK,
14 CR,
16 LF,
18 ZW,
20 WJ,
22 GL,
24 SP,
26 OP,
28 CL,
30 CP,
32 EX,
34 NS,
36 ID,
38 AL,
40 NU,
42 HY,
44 BA,
46 BB,
48 IN,
50 IS,
52 PR,
54 PO,
56 XX,
58}
59
60pub 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 '(' | '[' | '{' | '<' | '(' | '[' | '{' | '〈' | '《' | '「' | '『' | '【' | '〔'
73 | '“' | '‘' | '«' => LineBreakClass::OP,
74
75 ')' | ']' | '}' | '>' | ')' | ']' | '}' | '〉' | '》' | '」' | '』' | '】' | '〕'
77 | '”' | '’' | '»' | '。' | '、' | ',' | '.' => LineBreakClass::CL,
78
79 '!' | '?' | '!' | '?' => LineBreakClass::EX,
81
82 'ぁ' | 'ぃ' | 'ぅ' | 'ぇ' | 'ぉ' | 'っ' | 'ゃ' | 'ゅ' | 'ょ' | 'ゎ' | 'ァ' | 'ィ'
84 | 'ゥ' | 'ェ' | 'ォ' | 'ッ' | 'ャ' | 'ュ' | 'ョ' | 'ヮ' | 'ヶ' | 'ヵ' | 'ー' | '・'
85 | ':' | ';' => LineBreakClass::NS,
86
87 '-' => LineBreakClass::HY,
89 '—' | '–' | '\u{00AD}' => LineBreakClass::BA,
90
91 '…' | '‥' => LineBreakClass::IN,
93
94 '$' | '£' | '¥' | '€' | '¢' | '¥' => LineBreakClass::PR,
96 '%' | '‰' | '°' => LineBreakClass::PO,
97
98 ',' | '.' | ':' | ';' => LineBreakClass::IS,
100
101 '0'..='9' | '٠'..='٩' => LineBreakClass::NU,
103
104 '\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#[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#[inline]
127pub fn is_prohibited_end(c: char) -> bool {
128 matches!(
129 classify_line_break(c),
130 LineBreakClass::OP | LineBreakClass::PR
131 )
132}
133
134pub 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 if matches!(
141 p_class,
142 LineBreakClass::BK | LineBreakClass::CR | LineBreakClass::LF
143 ) {
144 return true;
145 }
146
147 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 if matches!(
156 c_class,
157 LineBreakClass::CL | LineBreakClass::CP | LineBreakClass::EX | LineBreakClass::NS
158 ) {
159 return false;
160 }
161 if matches!(p_class, LineBreakClass::OP | LineBreakClass::PR) {
163 return false;
164 }
165
166 if p_class == LineBreakClass::ZW {
168 return true;
169 }
170
171 if p_class == LineBreakClass::SP {
173 return true;
174 }
175
176 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 if matches!(p_class, LineBreakClass::CL | LineBreakClass::CP)
193 && (c_class == LineBreakClass::ID || c_class == LineBreakClass::AL)
194 {
195 return true;
196 }
197
198 if matches!(p_class, LineBreakClass::HY | LineBreakClass::BA) {
200 return true;
201 }
202
203 false
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
208pub enum WhiteSpaceMode {
209 #[default]
211 Normal,
212 NoWrap,
214 Pre,
216 PreWrap,
218 PreLine,
220}
221
222impl WhiteSpaceMode {
223 #[inline(always)]
225 pub fn collapses_spaces(self) -> bool {
226 matches!(
227 self,
228 WhiteSpaceMode::Normal | WhiteSpaceMode::NoWrap | WhiteSpaceMode::PreLine
229 )
230 }
231
232 #[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 #[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#[derive(Debug, Clone, PartialEq)]
253pub struct TextLine {
254 pub glyphs: Vec<ShapedGlyph>,
256 pub content_width: LayoutUnit,
258 pub trailing_space_width: LayoutUnit,
260 pub is_hard_break: bool,
262}
263
264#[derive(Debug, Clone, Default)]
266pub struct LineBreaker;
267
268impl LineBreaker {
269 pub fn new() -> Self {
270 Self
271 }
272
273 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 if glyph.glyph_id == 10 || glyph.glyph_id == 13 {
303 let (content_w, trailing_w) = Self::calculate_widths(¤t_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 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 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 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(¤t_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 let (content_w, trailing_w) = Self::calculate_widths(¤t_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 let (content_w, trailing_w) = Self::calculate_widths(¤t_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 if !current_glyphs.is_empty() {
394 let (content_w, trailing_w) = Self::calculate_widths(¤t_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 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}