k2f_layout 0.3.3

K2F deterministic layout compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use crate::LayoutContext;
use k2f_core::Pt;

use super::metrics::{line_height_for_style, measure_text_run_width};
use super::types::{merge_join_tracking, push_or_merge_run, TextLine, TextRun};
use super::wrap_fit::fit_prefix_boundary;
use super::wrap_tokenize::{split_run_for_wrapping, FragKind, Fragment};

#[derive(Debug, Clone)]
struct Piece {
    kind: FragKind, // Text or Whitespace
    run: TextRun,
    width: Pt,
    height: Pt,
}

#[derive(Debug, Clone, Copy)]
struct BreakPoint {
    /// How many pieces are kept on the current line (exclusive), *excluding* trailing whitespace.
    line_len_excluding_ws: usize,
    /// The next piece index to start the next line from (exclusive of the whitespace).
    next_start: usize,
}

pub(crate) fn wrap_runs(
    runs: &[TextRun],
    max_width: Pt,
    base_line_height: Pt,
    first_line_indent: Pt,
    ctx: &LayoutContext,
) -> Result<Vec<TextLine>, String> {
    let mut frags: Vec<Fragment> = Vec::new();
    for r in runs {
        frags.extend(split_run_for_wrapping(r));
    }

    let infinite_width = max_width.0 == i128::MAX;
    if !infinite_width && max_width.0 <= 0 {
        if let Some(sample) = visible_sample(runs) {
            return Err(format!(
                "UNSPLITTABLE_OVERFLOW: text {sample} does not fit because the line width is {} millipt. A grid cell, fixed width, or padding left no room",
                max_width.0
            ));
        }
    }

    let mut out_lines: Vec<TextLine> = Vec::new();

    let mut line: Vec<Piece> = Vec::new();
    let mut line_width = Pt::ZERO;
    let mut line_height = base_line_height;
    let mut last_break: Option<BreakPoint> = None;
    let mut is_first_line = true;

    let line_limit = |first: bool| {
        if first && first_line_indent.0 > 0 && !infinite_width {
            (max_width - first_line_indent).max(Pt::ZERO)
        } else {
            max_width
        }
    };

    let text_budget: usize = runs.iter().map(|r| r.text.len()).sum();
    let step_cap = text_budget.saturating_mul(8).saturating_add(32);
    let mut steps: usize = 0;
    let mut i: usize = 0;
    while i < frags.len() {
        steps += 1;
        if steps > step_cap {
            let sample = frags
                .get(i)
                .and_then(|f| f.run.as_ref())
                .map(|r| text_sample(&r.text))
                .unwrap_or_else(|| "\"\"".to_string());
            return Err(format!(
                "UNSPLITTABLE_OVERFLOW: text {sample} does not fit because wrapping made no progress (line width {} millipt)",
                max_width.0
            ));
        }
        let frag = frags[i].clone();
        match frag.kind {
            FragKind::Newline => {
                flush_line(
                    &mut out_lines,
                    &mut line,
                    &mut line_width,
                    &mut line_height,
                    base_line_height,
                );
                is_first_line = false;
                last_break = None;
                i += 1;
            }
            FragKind::Atom => {
                let run = frag.run.expect("run present for atom");
                let tex = run.math_tex.as_deref().unwrap_or("");
                let math = crate::math::layout_inline_tex(tex, run.style.font_size, ctx)?;
                let piece_width = math.width;
                let piece_height = if math.height > line_height_for_style(&run.style) {
                    math.height
                } else {
                    line_height_for_style(&run.style)
                };

                if infinite_width
                    || next_line_width(&line, line_width, piece_width, &run)
                        <= line_limit(is_first_line)
                {
                    push_piece(
                        &mut line,
                        &mut line_width,
                        &mut line_height,
                        Piece {
                            kind: frag.kind,
                            run,
                            width: piece_width,
                            height: piece_height,
                        },
                        base_line_height,
                        &mut last_break,
                    );
                    i += 1;
                    continue;
                }

                if !line.is_empty() {
                    if let Some(bp) = last_break {
                        break_at(
                            bp,
                            &mut out_lines,
                            &mut line,
                            &mut line_width,
                            &mut line_height,
                            base_line_height,
                        );
                        is_first_line = false;
                        last_break = None;
                        continue;
                    }
                    flush_line(
                        &mut out_lines,
                        &mut line,
                        &mut line_width,
                        &mut line_height,
                        base_line_height,
                    );
                    is_first_line = false;
                    last_break = None;
                    continue;
                }

                return Err(format!(
                    "UNSPLITTABLE_OVERFLOW: inline math '{tex}' is wider than the line"
                ));
            }
            FragKind::Whitespace | FragKind::Text => {
                let run = frag.run.expect("run present for text/whitespace");

                // Drop leading whitespace (stable, avoids lines starting with spaces).
                if frag.kind == FragKind::Whitespace && line.is_empty() {
                    i += 1;
                    continue;
                }

                let piece_width = measure_text_run_width(&run.text, &run.style, ctx)?;
                let piece_height = line_height_for_style(&run.style);

                // No wrapping when width is infinite; only hard newlines split lines.
                if infinite_width {
                    push_piece(
                        &mut line,
                        &mut line_width,
                        &mut line_height,
                        Piece {
                            kind: frag.kind,
                            run,
                            width: piece_width,
                            height: piece_height,
                        },
                        base_line_height,
                        &mut last_break,
                    );
                    i += 1;
                    continue;
                }

                // If it fits, just add it.
                if next_line_width(&line, line_width, piece_width, &run)
                    <= line_limit(is_first_line)
                {
                    push_piece(
                        &mut line,
                        &mut line_width,
                        &mut line_height,
                        Piece {
                            kind: frag.kind,
                            run,
                            width: piece_width,
                            height: piece_height,
                        },
                        base_line_height,
                        &mut last_break,
                    );
                    i += 1;
                    continue;
                }

                // Overflow handling.
                if !line.is_empty() {
                    if let Some(bp) = last_break {
                        break_at(
                            bp,
                            &mut out_lines,
                            &mut line,
                            &mut line_width,
                            &mut line_height,
                            base_line_height,
                        );
                        is_first_line = false;
                        last_break = None;
                        // retry this fragment on the next line
                        continue;
                    }

                    // No break point: force a new line before this fragment.
                    flush_line(
                        &mut out_lines,
                        &mut line,
                        &mut line_width,
                        &mut line_height,
                        base_line_height,
                    );
                    is_first_line = false;
                    last_break = None;
                    continue;
                }

                // Line is empty and fragment doesn't fit: force split (at least one char).
                if frag.kind == FragKind::Whitespace {
                    // If whitespace can't fit on an empty line, drop it.
                    i += 1;
                    continue;
                }

                let limit = line_limit(is_first_line);
                let split_at = fit_prefix_boundary(&run.text, &run.style, limit, ctx)?;
                let head_text = run.text[..split_at].to_string();
                let tail_text = run.text[split_at..].to_string();
                let head_w = measure_text_run_width(&head_text, &run.style, ctx)?;
                if head_w > limit {
                    return Err(format!(
                        "UNSPLITTABLE_OVERFLOW: text {} does not fit because it is wider than the line ({} > {} millipt)",
                        text_sample(&head_text),
                        head_w.0,
                        limit.0
                    ));
                }

                let head = TextRun {
                    start: run.start,
                    end: run.start + split_at,
                    style: run.style.clone(),
                    text: head_text,
                    math_tex: None,
                };
                let tail = TextRun {
                    start: run.start + split_at,
                    end: run.end,
                    style: run.style,
                    text: tail_text,
                    math_tex: None,
                };

                // Replace current fragment with head, and insert tail (if any) after it.
                frags[i] = Fragment {
                    kind: FragKind::Text,
                    run: Some(head),
                };
                if !tail.text.is_empty() {
                    frags.insert(
                        i + 1,
                        Fragment {
                            kind: FragKind::Text,
                            run: Some(tail),
                        },
                    );
                }
                // retry (head should now be addable)
            }
        }
    }

    // Flush final line (even if empty, to keep layout stable).
    flush_line(
        &mut out_lines,
        &mut line,
        &mut line_width,
        &mut line_height,
        base_line_height,
    );

    Ok(out_lines)
}

fn text_sample(text: &str) -> String {
    let sample: String = text.chars().take(40).collect();
    format!("{sample:?}")
}

fn visible_sample(runs: &[TextRun]) -> Option<String> {
    let mut sample = String::new();
    for run in runs {
        for ch in run.text.chars() {
            if ch.is_whitespace() {
                continue;
            }
            sample.push(ch);
            if sample.chars().count() >= 40 {
                return Some(format!("{sample:?}"));
            }
        }
    }
    if sample.is_empty() {
        None
    } else {
        Some(format!("{sample:?}"))
    }
}

fn next_line_width(line: &[Piece], line_width: Pt, piece_width: Pt, run: &TextRun) -> Pt {
    let join = line
        .last()
        .map(|p| merge_join_tracking(&p.run, run))
        .unwrap_or(Pt::ZERO);
    line_width + join + piece_width
}

fn pieces_advance(line: &[Piece]) -> Pt {
    let mut w = Pt::ZERO;
    for (i, p) in line.iter().enumerate() {
        if i > 0 {
            w = w + merge_join_tracking(&line[i - 1].run, &p.run);
        }
        w = w + p.width;
    }
    w
}

fn push_piece(
    line: &mut Vec<Piece>,
    line_width: &mut Pt,
    line_height: &mut Pt,
    piece: Piece,
    base_line_height: Pt,
    last_break: &mut Option<BreakPoint>,
) {
    *line_width = next_line_width(line, *line_width, piece.width, &piece.run);
    if piece.height > *line_height {
        *line_height = piece.height;
    }
    if *line_height < base_line_height {
        *line_height = base_line_height;
    }

    line.push(piece);

    // A whitespace piece creates a deterministic break opportunity *after* it.
    if matches!(line.last().map(|p| p.kind), Some(FragKind::Whitespace)) {
        let len = line.len();
        // Exclude the whitespace itself from the line if we break here.
        *last_break = Some(BreakPoint {
            line_len_excluding_ws: len.saturating_sub(1),
            next_start: len,
        });
    } else if line
        .last()
        .map(|p| p.kind == FragKind::Text && is_hyphen_break(&p.run.text))
        .unwrap_or(false)
    {
        let len = line.len();
        // Keep the hyphen/soft-hyphen on this line.
        *last_break = Some(BreakPoint {
            line_len_excluding_ws: len,
            next_start: len,
        });
    }
}

fn is_hyphen_break(text: &str) -> bool {
    text.ends_with('-') || text.ends_with('\u{00AD}')
}

fn break_at(
    bp: BreakPoint,
    out_lines: &mut Vec<TextLine>,
    line: &mut Vec<Piece>,
    line_width: &mut Pt,
    line_height: &mut Pt,
    base_line_height: Pt,
) {
    // remainder = pieces after whitespace
    let mut remainder = if bp.next_start <= line.len() {
        line.split_off(bp.next_start)
    } else {
        Vec::new()
    };
    // Drop whitespace segment itself by truncating the kept part.
    line.truncate(bp.line_len_excluding_ws);

    flush_line(out_lines, line, line_width, line_height, base_line_height);

    // Start next line with remainder, dropping leading whitespace for stability.
    while matches!(
        remainder.first().map(|p| p.kind),
        Some(FragKind::Whitespace)
    ) {
        remainder.remove(0);
    }

    *line = remainder;
    recompute_line_metrics(line, line_width, line_height, base_line_height);
}

fn flush_line(
    out_lines: &mut Vec<TextLine>,
    line: &mut Vec<Piece>,
    line_width: &mut Pt,
    line_height: &mut Pt,
    base_line_height: Pt,
) {
    // Trim trailing whitespace.
    while matches!(line.last().map(|p| p.kind), Some(FragKind::Whitespace)) {
        line.pop();
    }
    *line_width = pieces_advance(line);

    let mut runs: Vec<TextRun> = Vec::new();
    for p in line.iter() {
        push_or_merge_run(&mut runs, p.run.clone());
    }

    let width = *line_width;
    let height = if runs.is_empty() {
        base_line_height
    } else {
        (*line_height).max(base_line_height)
    };

    out_lines.push(TextLine {
        runs,
        width,
        height,
    });

    line.clear();
    *line_width = Pt::ZERO;
    *line_height = base_line_height;
}

fn recompute_line_metrics(line: &[Piece], width: &mut Pt, height: &mut Pt, base_line_height: Pt) {
    let mut h = base_line_height;
    for p in line {
        if p.height > h {
            h = p.height;
        }
    }
    *width = pieces_advance(line);
    *height = h.max(base_line_height);
}