1
//! An implementation of the Knuth-Plass line-breaking algorithm
2
//! for simple rectangular layouts.
3

            
4
#[cfg(feature = "text_layout_hyphenation")]
5
use hyphenation::{Hyphenator, Standard};
6

            
7
#[cfg(not(feature = "text_layout_hyphenation"))]
8
use crate::text3::cache::Standard;
9
use crate::text3::cache::{
10
    get_base_direction_from_logical, get_item_measure, is_no_break_space, is_word_separator,
11
    is_zero_width_space, AvailableSpace, BidiDirection, JustifyContent, LayoutError, LoadedFonts,
12
    LogicalItem, OverflowInfo, ParsedFontTrait, Point, PositionedItem, ShapedItem, TextAlign,
13
    UnifiedConstraints, UnifiedLayout,
14
};
15

            
16
const INFINITY_BADNESS: f32 = 10000.0;
17
const SPACE_STRETCH_RATIO: f32 = 0.5;
18
const SPACE_SHRINK_RATIO: f32 = 0.33;
19
const HYPHENATION_PENALTY: f32 = 50.0;
20
const BADNESS_MULTIPLIER: f32 = 100.0;
21

            
22
/// Represents the elements of a paragraph for the line-breaking algorithm.
23
#[derive(Debug, Clone)]
24
enum LayoutNode {
25
    /// A non-stretchable, non-shrinkable item (a glyph cluster or an object).
26
    Box(ShapedItem, f32), // Item and its width
27
    /// A flexible space.
28
    Glue {
29
        item: ShapedItem,
30
        /// Natural width of the space.
31
        width: f32,
32
        /// Maximum amount the space can grow beyond its natural width.
33
        stretch: f32,
34
        /// Maximum amount the space can shrink below its natural width.
35
        shrink: f32,
36
    },
37
    /// A point where a line break is allowed, with an associated cost.
38
    Penalty {
39
        /// Optional item associated with the penalty (e.g., a hyphen glyph).
40
        item: Option<ShapedItem>,
41
        width: f32,
42
        penalty: f32,
43
    },
44
}
45

            
46
/// Stores the result of the dynamic programming algorithm for a given point.
47
#[derive(Debug, Clone, Copy)]
48
struct Breakpoint {
49
    /// The total demerit score to reach this point.
50
    demerit: f32,
51
    /// The index of the previous breakpoint in the optimal path.
52
    previous: usize,
53
    /// The line number this breakpoint ends.
54
    line: usize,
55
}
56

            
57
/// Main entry point for the Knuth-Plass layout algorithm.
58
///
59
/// This implements optimal line-breaking as described in "Breaking Paragraphs into Lines"
60
/// (Knuth & Plass, 1981). Unlike greedy algorithms, it considers the entire paragraph
61
/// to find globally optimal break points.
62
///
63
/// # Use Cases
64
///
65
/// - `text-wrap: balance` - CSS property for balanced line lengths
66
/// - High-quality typesetting where line consistency matters
67
/// - Multi-line headings that should appear visually balanced
68
///
69
/// # Limitations
70
///
71
/// - Only supports horizontal text (vertical writing modes use greedy algorithm)
72
/// - Higher computational cost than greedy breaking
73
/// - May produce different results than browsers for edge cases
74
/// - overflow-wrap: anywhere/break-word emergency breaks stay greedy-only (word-break /
75
///   hyphens-driven opportunities ARE honoured here)
76
// overflow-wrap emergency breaks; the greedy break_one_line path handles this
77
84
pub(crate) fn kp_layout<T: ParsedFontTrait>(
78
84
    items: &[ShapedItem],
79
84
    logical_items: &[LogicalItem],
80
84
    constraints: &UnifiedConstraints,
81
84
    hyphenator: Option<&Standard>,
82
84
    fonts: &LoadedFonts<T>,
83
84
) -> UnifiedLayout {
84
84
    if items.is_empty() {
85
7
        return UnifiedLayout {
86
7
            items: Vec::new(),
87
7
            overflow: OverflowInfo::default(),
88
7
        };
89
77
    }
90

            
91
    // Convert ShapedItems into a sequence of Boxes, Glue, and Penalties.
92
    // The paragraph base direction gates hyphenation (see 508895 below);
93
    // the constraints carry word-break/line-break/overflow-wrap so the KP
94
    // path honours the same soft-wrap controls as the greedy path.
95
77
    let base_direction = get_base_direction_from_logical(logical_items);
96
77
    let nodes = convert_items_to_nodes(items, hyphenator, fonts, constraints, base_direction);
97

            
98
    // Dynamic Programming to find optimal breakpoints
99
77
    let breaks = find_optimal_breakpoints(&nodes, constraints);
100

            
101
    // Use breakpoints to build and position the final lines
102
77
    let final_layout: UnifiedLayout =
103
77
        position_lines_from_breaks(&nodes, &breaks, logical_items, constraints);
104

            
105
77
    final_layout
106
84
}
107

            
108
/// Converts a slice of `ShapedItems` into the Box/Glue/Penalty model.
109
// +spec:line-breaking:16e64c - soft wrap opportunity controls (word-break, overflow-wrap,
110
// line-break) threaded via UnifiedConstraints
111
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
112
                                 // (one branch per case)
113
120
fn convert_items_to_nodes<T: ParsedFontTrait>(
114
120
    items: &[ShapedItem],
115
120
    hyphenator: Option<&Standard>,
116
120
    fonts: &LoadedFonts<T>,
117
120
    constraints: &UnifiedConstraints,
118
120
    base_direction: BidiDirection,
119
120
) -> Vec<LayoutNode> {
120
120
    let mut nodes = Vec::new();
121
120
    let is_vertical = false; // Knuth-Plass is horizontal-only for now
122
120
    let mut item_iter = items.iter().peekable();
123

            
124
1417
    while let Some(item) = item_iter.next() {
125
        // +spec:line-breaking:f12241 - shaping across intra-word breaks: shaped clusters preserve
126
        // joining forms
127
454
        match item {
128
1297
            item if is_zero_width_space(item) => {
129
407
                nodes.push(LayoutNode::Penalty {
130
407
                    item: None,
131
407
                    width: 0.0,
132
407
                    penalty: 0.0,
133
407
                });
134
407
            }
135
890
            item if is_word_separator(item) => {
136
384
                let width = get_item_measure(item, is_vertical);
137
384
                nodes.push(LayoutNode::Glue {
138
384
                    item: item.clone(),
139
384
                    width,
140
384
                    stretch: width * SPACE_STRETCH_RATIO,
141
384
                    shrink: width * SPACE_SHRINK_RATIO,
142
384
                });
143
                // NBSP & friends (UAX#14 class GL/WJ) add word-spacing Glue but are NOT
144
                // soft-wrap opportunities, so suppress the break Penalty for them —
145
                // otherwise "1\u{00A0}km" could wrap between the number and unit.
146
384
                if !is_no_break_space(item) {
147
382
                    nodes.push(LayoutNode::Penalty {
148
382
                        item: None,
149
382
                        width: 0.0,
150
382
                        penalty: 0.0,
151
382
                    });
152
382
                }
153
            }
154
454
            ShapedItem::Cluster(cluster)
155
454
                if cluster.text().ends_with('\u{002D}') || cluster.text().ends_with('\u{2010}') =>
156
15
            {
157
15
                let width = get_item_measure(item, is_vertical);
158
15
                nodes.push(LayoutNode::Box(item.clone(), width));
159
15
                // +spec:line-breaking:2d3674 - U+002D/U+2010 are soft wrap opportunities, not
160
15
                // hyphenation opportunities (no extra glyph inserted) Zero-width
161
15
                // penalty: allows a line break after the visible hyphen character
162
15
                // without inserting an additional hyphen glyph.
163
15
                nodes.push(LayoutNode::Penalty {
164
15
                    item: None,
165
15
                    width: 0.0,
166
15
                    penalty: 0.0,
167
15
                });
168
15
            }
169
439
            ShapedItem::Cluster(cluster) => {
170
                // 1. Collect all adjacent clusters to form a full "word".
171
439
                let mut current_word_clusters = vec![cluster.clone()];
172
1210
                while let Some(peeked_item) = item_iter.peek() {
173
1150
                    if let ShapedItem::Cluster(next_cluster) = peeked_item {
174
                        // Stop collecting *before* any soft-wrap boundary so the outer
175
                        // loop can emit the correct node for it. Word separators are
176
                        // shaped as ordinary Clusters (text " "), so without these guards
177
                        // the greedy collection would absorb every space into one giant
178
                        // "word" and the paragraph could never break — it would collapse
179
                        // onto a single line. Boundaries handled by the outer loop:
180
                        //   * word separator     -> Glue + Penalty (soft wrap)
181
                        //   * zero-width space    -> Penalty (soft wrap)
182
                        //   * cluster ending '-'  -> Box + zero-width Penalty
183
                        //     (+spec:line-breaking:2d3674 — U+002D/U+2010 are UAX#14 class BA break
184
                        //     opportunities AFTER the hyphen; a hyphen occurs mid-word, e.g.
185
                        //     "well-being").
186
1141
                        if is_word_separator(peeked_item)
187
781
                            || is_zero_width_space(peeked_item)
188
780
                            || next_cluster.text().ends_with('\u{002D}')
189
772
                            || next_cluster.text().ends_with('\u{2010}')
190
                        {
191
370
                            break;
192
771
                        }
193
771
                        current_word_clusters.push(next_cluster.clone());
194
771
                        item_iter.next(); // Consume the peeked item
195
                    } else {
196
                        // Stop if we hit a non-cluster item (object, tab, break, etc.)
197
9
                        break;
198
                    }
199
                }
200

            
201
                // +spec:line-breaking:28a40b - Hyphenation is a rendering-only effect (no change to
202
                // underlying content) +spec:line-breaking:f23fe8 - UA may use
203
                // language-tailored heuristics (delegated to hyphenation crate)
204
                // 2. Try to find all hyphenation opportunities for this word.
205
                // +spec:display-property:508895 - hyphenation of direction-mismatched words is
206
                // suppressed (CSS 2.2 §9.10 note: hyphenating an LTR word inside an
207
                // RTL paragraph - or vice versa - would render the hyphen visually
208
                // MID-line rather than at the line edge, so UAs usually
209
                // suppress it. The word's direction comes from its first
210
                // cluster; the paragraph's from the logical items.)
211
439
                let word_direction = current_word_clusters
212
439
                    .first()
213
439
                    .map_or(base_direction, |c| c.direction);
214
439
                let hyphenation_allowed = word_direction == base_direction;
215
439
                let hyphenation_breaks = hyphenator.filter(|_| hyphenation_allowed).and_then(|h| {
216
                    crate::text3::cache::find_all_hyphenation_breaks(
217
                        &current_word_clusters,
218
                        h,
219
                        is_vertical,
220
                        fonts,
221
                    )
222
                });
223

            
224
439
                if let Some(breaks) = hyphenation_breaks {
225
                    // 3. Convert word + hyphenation breaks into a sequence of Boxes and Penalties.
226
                    let mut current_item_cursor = 0;
227

            
228
                    for b in &breaks {
229
                        // Add the items that form the next syllable (the part between the last
230
                        // break and this one)
231
                        let num_items_in_syllable = b.line_part.len() - current_item_cursor;
232
                        for item in b.line_part.iter().skip(current_item_cursor) {
233
                            nodes.push(LayoutNode::Box(
234
                                item.clone(),
235
                                get_item_measure(item, is_vertical),
236
                            ));
237
                        }
238
                        current_item_cursor += num_items_in_syllable;
239

            
240
                        let hyphen_measure = get_item_measure(&b.hyphen_item, is_vertical);
241
                        nodes.push(LayoutNode::Penalty {
242
                            item: Some(b.hyphen_item.clone()),
243
                            width: hyphen_measure,
244
                            penalty: HYPHENATION_PENALTY, // Standard penalty for hyphenation
245
                        });
246
                    }
247

            
248
                    // Add the final remainder of the word.
249
                    if let Some(last_break) = breaks.last() {
250
                        for remainder_item in &last_break.remainder_part {
251
                            nodes.push(LayoutNode::Box(
252
                                remainder_item.clone(),
253
                                get_item_measure(remainder_item, is_vertical),
254
                            ));
255
                        }
256
                    } else {
257
                        // This case happens if find_all_hyphenation_breaks returned an empty vec.
258
                        // Fallback to just adding the original word.
259
                        for c in current_word_clusters {
260
                            nodes.push(LayoutNode::Box(ShapedItem::Cluster(c.clone()), c.advance));
261
                        }
262
                    }
263
                } else {
264
                    // No hyphenation possible, add the whole word as boxes -
265
                    // with the SAME soft-wrap opportunities between clusters
266
                    // the greedy path grants (word-break: break-all breaks
267
                    // between any two clusters, `normal` between CJK ones,
268
                    // keep-all suppresses those; the shared predicate is the
269
                    // single source of truth). Without this, `text-wrap:
270
                    // balance` (the KP path) silently ignored word-break and
271
                    // CJK runs never gained intra-word breaks.
272
439
                    let n_word = current_word_clusters.len();
273
1210
                    for (ci, c) in current_word_clusters.iter().enumerate() {
274
1210
                        nodes.push(LayoutNode::Box(ShapedItem::Cluster(c.clone()), c.advance));
275
1210
                        let is_last = ci + 1 == n_word;
276
1210
                        if !is_last
277
771
                            && crate::text3::cache::is_break_opportunity_with_word_break(
278
771
                                &ShapedItem::Cluster(c.clone()),
279
771
                                constraints.word_break,
280
771
                                constraints.hyphenation,
281
                            )
282
5
                        {
283
5
                            nodes.push(LayoutNode::Penalty {
284
5
                                item: None,
285
5
                                width: 0.0,
286
5
                                penalty: 0.0,
287
5
                            });
288
1205
                        }
289
                    }
290
                }
291
            }
292
            // Per CSS Text 3 §5.1: "there is a soft wrap opportunity before and
293
            // after each replaced element or other atomic inline"
294
19
            ShapedItem::Object { .. } | ShapedItem::CombinedBlock { .. } => {
295
19
                // Soft wrap opportunity before the atomic inline
296
19
                nodes.push(LayoutNode::Penalty {
297
19
                    item: None,
298
19
                    width: 0.0,
299
19
                    penalty: 0.0,
300
19
                });
301
19
                nodes.push(LayoutNode::Box(
302
19
                    item.clone(),
303
19
                    get_item_measure(item, is_vertical),
304
19
                ));
305
19
                // Soft wrap opportunity after the atomic inline
306
19
                nodes.push(LayoutNode::Penalty {
307
19
                    item: None,
308
19
                    width: 0.0,
309
19
                    penalty: 0.0,
310
19
                });
311
19
            }
312
19
            ShapedItem::Tab { bounds, .. } => {
313
19
                nodes.push(LayoutNode::Glue {
314
19
                    item: item.clone(),
315
19
                    width: bounds.width,
316
19
                    stretch: bounds.width * SPACE_STRETCH_RATIO, /* Treat like a space for
317
19
                                                                  * flexibility */
318
19
                    shrink: bounds.width * SPACE_SHRINK_RATIO,
319
19
                });
320
19
            }
321
14
            ShapedItem::Break { .. } => {
322
14
                nodes.push(LayoutNode::Penalty {
323
14
                    item: None,
324
14
                    width: 0.0,
325
14
                    penalty: -INFINITY_BADNESS,
326
14
                });
327
14
            }
328
        }
329
    }
330

            
331
    // Anchor the end of the paragraph. Standard Knuth-Plass appends a finishing
332
    // forced break so the final line is broken at the paragraph end. Without it,
333
    // a paragraph that ends in an ordinary word (its final nodes are Box, not a
334
    // Penalty) never sets breakpoints[n] in the DP, so the backtrack collapses
335
    // the entire paragraph onto a single line. A forced break at the end makes
336
    // n a legal breakpoint regardless of the last node's type; the forced-break
337
    // scoring in find_optimal_breakpoints already exempts a short last line from
338
    // any badness, so no finishing glue is required. The penalty carries no item,
339
    // so it contributes nothing to the positioned output.
340
120
    if !nodes.is_empty()
341
7
        && !matches!(
342
119
            nodes.last(),
343
53
            Some(LayoutNode::Penalty { penalty, .. }) if *penalty <= -INFINITY_BADNESS
344
        )
345
112
    {
346
112
        nodes.push(LayoutNode::Penalty {
347
112
            item: None,
348
112
            width: 0.0,
349
112
            penalty: -INFINITY_BADNESS,
350
112
        });
351
112
    }
352

            
353
120
    nodes
354
120
}
355

            
356
/// Uses dynamic programming to find the optimal set of line breaks.
357
#[allow(clippy::match_same_arms)]
358
// enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that can't
359
// merge)
360
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
361
#[allow(clippy::cognitive_complexity)] // cohesive Knuth-Plass DP: one branch per break class
362
133
fn find_optimal_breakpoints(nodes: &[LayoutNode], constraints: &UnifiedConstraints) -> Vec<usize> {
363
    // For MinContent (intrinsic min-content sizing), CSS wants the width of the
364
    // widest unbreakable unit (word). Break at EVERY legal opportunity so each
365
    // word lands on its own line; the widest resulting line then equals the
366
    // widest word. The optimizing DP below cannot express this: with an
367
    // effectively infinite width it puts the whole paragraph on one line, making
368
    // min-content == max-content. Every Penalty node is a legal break point.
369
133
    if matches!(constraints.available_width, AvailableSpace::MinContent) {
370
16
        let mut breaks = Vec::new();
371
86
        for (i, node) in nodes.iter().enumerate() {
372
86
            if matches!(node, LayoutNode::Penalty { .. }) {
373
36
                breaks.push(i + 1);
374
50
            }
375
        }
376
        // Ensure the final segment (which may end in Box nodes) forms a line.
377
16
        if breaks.last() != Some(&nodes.len()) {
378
1
            breaks.push(nodes.len());
379
15
        }
380
16
        return breaks;
381
117
    }
382

            
383
    // For Knuth-Plass, we need a definite line width.
384
    //
385
    // For MaxContent, use a very large value (no line breaks unless forced).
386
    // The actual min-content width is determined by the widest resulting line.
387

            
388
117
    let line_width = match constraints.available_width {
389
101
        AvailableSpace::Definite(w) => w,
390
16
        AvailableSpace::MaxContent => f32::MAX / 2.0,
391
        // MinContent is handled by the early return above; keep a large width as
392
        // a defensive fallback so this arm never breaks after every character.
393
        AvailableSpace::MinContent => f32::MAX / 2.0,
394
    };
395

            
396
    // (and lines after forced breaks when each-line is set). The hanging keyword would
397
    // invert this, indenting all lines EXCEPT the first.
398
117
    let text_indent = constraints.text_indent;
399
117
    let first_line_width = if constraints.text_indent_hanging {
400
6
        line_width
401
    } else {
402
111
        line_width - text_indent
403
    };
404
117
    let non_first_line_width = if constraints.text_indent_hanging {
405
6
        line_width - text_indent
406
    } else {
407
111
        line_width
408
    };
409

            
410
    // Prefix sums for O(1) range queries (eliminates O(n³) inner loop).
411
    //
412
    // Knuth-Plass counts a Penalty's width ONLY when the line breaks AT that
413
    // penalty (the hyphen is rendered at the split, nowhere else - CSS Text 3
414
    // §5.3). Interior hyphenation opportunities therefore contribute ZERO to
415
    // a candidate line's width: keep penalties out of `prefix_width` and add
416
    // the break-node's own width explicitly in the DP loop. The old sums
417
    // inflated every candidate by one hyphen width per unused opportunity,
418
    // and the positioner then rendered a "-" at every opportunity mid-line.
419
117
    let n = nodes.len();
420
117
    let mut prefix_width = vec![0.0f32; n + 1];
421
117
    let mut prefix_stretch = vec![0.0f32; n + 1];
422
117
    let mut prefix_shrink = vec![0.0f32; n + 1];
423
2737
    for (k, node) in nodes.iter().enumerate() {
424
2737
        let (w, st, sh) = match node {
425
1340
            LayoutNode::Box(_, w) => (*w, 0.0, 0.0),
426
            LayoutNode::Glue {
427
421
                width,
428
421
                stretch,
429
421
                shrink,
430
                ..
431
421
            } => (*width, *stretch, *shrink),
432
976
            LayoutNode::Penalty { .. } => (0.0, 0.0, 0.0),
433
        };
434
2737
        prefix_width[k + 1] = prefix_width[k] + w;
435
2737
        prefix_stretch[k + 1] = prefix_stretch[k] + st;
436
2737
        prefix_shrink[k + 1] = prefix_shrink[k] + sh;
437
    }
438

            
439
117
    let mut breakpoints = vec![
440
117
        Breakpoint {
441
117
            // TRUE infinity for "not yet reached", NOT the finite INFINITY_BADNESS
442
117
            // (10_000). Demerits accumulate across lines, so once the optimal path's
443
117
            // cumulative demerit passed 10_000 no later candidate could beat a finite
444
117
            // sentinel, and the whole paragraph collapsed onto one overfull line.
445
117
            demerit: f32::INFINITY,
446
117
            previous: 0,
447
117
            line: 0
448
117
        };
449
117
        n + 1
450
    ];
451
117
    breakpoints[0] = Breakpoint {
452
117
        demerit: 0.0,
453
117
        previous: 0,
454
117
        line: 0,
455
117
    };
456

            
457
2737
    for i in 0..n {
458
        // Optimization:
459
        //
460
        // A legal line break can only occur at a Penalty node. If the current node
461
        // is a Box or Glue, we can skip it as a potential breakpoint.
462

            
463
2737
        if !matches!(nodes.get(i), Some(LayoutNode::Penalty { .. })) {
464
1761
            continue;
465
976
        }
466

            
467
        // Width the hyphen (or other penalty item) adds IF the line breaks here.
468
976
        let break_penalty_width = match nodes.get(i) {
469
976
            Some(LayoutNode::Penalty { width, .. }) => *width,
470
            _ => 0.0,
471
        };
472

            
473
309503
        for j in (0..=i).rev() {
474
            // Calculate the properties of a potential line from node `j` to `i`.
475
            // O(1) range sum via prefix sums: sum of nodes[j..=i], plus the
476
            // width of the penalty broken at (see the prefix-sum note above).
477
309503
            let current_width = prefix_width[i + 1] - prefix_width[j] + break_penalty_width;
478
309503
            let stretch = prefix_stretch[i + 1] - prefix_stretch[j];
479
309503
            let shrink = prefix_shrink[i + 1] - prefix_shrink[j];
480

            
481
309503
            let effective_line_width = if breakpoints[j].line == 0 {
482
183988
                first_line_width
483
125515
            } else if constraints.text_indent_hanging {
484
18
                non_first_line_width
485
            } else {
486
125497
                line_width
487
            };
488

            
489
            // Calculate adjustment ratio. If the line is wider than the available width
490
            // but has no glue to shrink, it is an invalid candidate.
491
309503
            let ratio = if current_width < effective_line_width {
492
85339
                if stretch > 0.0 {
493
4046
                    (effective_line_width - current_width) / stretch
494
                } else {
495
81293
                    INFINITY_BADNESS // Cannot stretch
496
                }
497
224164
            } else if current_width > effective_line_width {
498
223891
                if shrink > 0.0 {
499
223745
                    (effective_line_width - current_width) / shrink
500
                } else {
501
                    // Overfull with nothing to shrink: this line physically cannot
502
                    // fit, so it is INFEASIBLE — not merely "loose". Marking it with a
503
                    // large negative ratio makes the `ratio < -1.0` guard below reject
504
                    // it, exactly like an over-shrunk line. Using +INFINITY_BADNESS
505
                    // here (a positive ratio) was a bug: it let an overflowing line
506
                    // survive the feasibility guard and then be rewarded by the forced
507
                    // end-of-paragraph break, so the DP preferred one overflowing line
508
                    // over a legal break (e.g. after a mid-word hyphen). Overlong
509
                    // unbreakable content is intentionally left to the greedy path.
510
146
                    -INFINITY_BADNESS
511
                }
512
            } else {
513
273
                0.0 // Perfect fit
514
            };
515

            
516
            // Lines that must shrink too much (or that overflow with no shrink) are
517
            // invalid and cannot start an optimal path.
518
309503
            if ratio < -1.0 {
519
223882
                continue;
520
85621
            }
521

            
522
            // Calculate badness
523
85621
            let mut badness = BADNESS_MULTIPLIER * ratio.abs().powi(3);
524

            
525
            // Add penalty for the break point
526
85621
            if let Some(LayoutNode::Penalty { penalty, .. }) = nodes.get(i) {
527
85621
                if *penalty >= 0.0 {
528
84656
                    badness += penalty;
529
84656
                } else if *penalty <= -INFINITY_BADNESS {
530
965
                    badness = -INFINITY_BADNESS; // Forced break
531
965
                }
532
            }
533

            
534
            // TODO: Add demerits for consecutive lines with very different
535
            // ratios (fitness classes).
536
            //
537
            // For now, demerit is simply the cumulative badness.
538
85621
            let demerit = badness + breakpoints[j].demerit;
539

            
540
85621
            if demerit < breakpoints[i + 1].demerit {
541
1487
                breakpoints[i + 1] = Breakpoint {
542
1487
                    demerit,
543
1487
                    previous: j,
544
1487
                    line: breakpoints[j].line + 1,
545
1487
                };
546
84134
            }
547
        }
548
    }
549

            
550
    // Backtrack from the end to find the break points
551
117
    let mut breaks = Vec::new();
552
117
    let mut current = nodes.len();
553
441
    while current > 0 {
554
324
        breaks.push(current);
555
324
        let prev_idx = breakpoints[current].previous;
556
324
        current = prev_idx;
557
324
    }
558
117
    breaks.reverse();
559
117
    breaks
560
133
}
561

            
562
/// Takes the optimal break points and performs the final positioning.
563
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
564
#[allow(clippy::cast_precision_loss)] // bounded graphics/coord/counter/fixed-point cast
565
#[allow(clippy::match_same_arms)]
566
// enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that can't
567
// merge)
568
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
569
                                 // (one branch per case)
570
127
fn position_lines_from_breaks(
571
127
    nodes: &[LayoutNode],
572
127
    breaks: &[usize],
573
127
    logical_items: &[LogicalItem],
574
127
    constraints: &UnifiedConstraints,
575
127
) -> UnifiedLayout {
576
127
    let mut positioned_items = Vec::new();
577
127
    let mut start_node = 0;
578
127
    let mut cross_axis_pen = 0.0;
579
127
    let base_direction = get_base_direction_from_logical(logical_items);
580
349
    for (line_index, &end_node) in breaks.iter().enumerate() {
581
349
        let line_nodes = &nodes[start_node..end_node];
582
349
        let is_last_line = line_index == breaks.len() - 1;
583

            
584
        // A Penalty's item (the synthesized hyphen) renders ONLY when the
585
        // line actually breaks at that penalty - i.e. for the LAST node of
586
        // the span. Cloning every penalty's item drew a "-" at each interior
587
        // hyphenation opportunity (CSS Text 3 §5.3: hyphenation visually
588
        // indicates the split, at the split).
589
349
        let last_idx = line_nodes.len().saturating_sub(1);
590
349
        let mut line_items: Vec<ShapedItem> = line_nodes
591
349
            .iter()
592
349
            .enumerate()
593
597
            .filter_map(|(k, node)| match node {
594
1339
                LayoutNode::Box(item, _) => Some(item.clone()),
595
429
                LayoutNode::Glue { item, .. } => Some(item.clone()),
596
597
                LayoutNode::Penalty { item, .. } if k == last_idx => item.clone(),
597
250
                LayoutNode::Penalty { .. } => None,
598
2365
            })
599
349
            .collect();
600

            
601
        // +spec CSS Text 3 §4.1.2: a line's trailing (line-terminating) spaces
602
        // "hang" — they are removed before measuring the line and are not counted
603
        // as justification opportunities. The break index sits just past the
604
        // Penalty following the trailing Glue, so that space is the last item
605
        // here. Drop trailing word separators so line_width, the justification
606
        // space count, and positioning all exclude them (matching the greedy
607
        // break_one_line path, which trims trailing spaces).
608
553
        while line_items.last().is_some_and(is_word_separator) {
609
204
            line_items.pop();
610
204
        }
611

            
612
        // Note: Calculate spacing, do not mutate items
613
349
        let mut extra_per_space = 0.0;
614
1564
        let line_width: f32 = line_items.iter().map(|i| get_item_measure(i, false)).sum();
615

            
616
        // the last line and lines ending with a forced break
617
2364
        let ends_with_forced_break = line_nodes.iter().any(|n| {
618
131
            matches!(
619
596
                n, LayoutNode::Penalty { penalty, .. } if *penalty <= -INFINITY_BADNESS
620
            )
621
2364
        });
622
349
        let effective_align = super::cache::resolve_effective_alignment(
623
349
            constraints.text_align,
624
349
            constraints.text_align_last,
625
349
            is_last_line || ends_with_forced_break,
626
        );
627

            
628
        // +spec:display-contents:858337 - text-align justification: last line start-aligned,
629
        // justify-all forces last line justify +spec:display-property:50e074 - justify
630
        // stretches spaces/words in inline boxes, not inline-table/inline-block
631
        // +spec:display-property:ce8d54 - text-justify selects justification method, inherited from
632
        // block containers to root inline box Justify ONLY when the RESOLVED alignment says
633
        // so. `resolve_effective_alignment` already encodes the last-line and
634
        // forced-break rules (§6.1/§6.3: Justify degrades to Start there,
635
        // JustifyAll does not), so no extra last-line disjunct belongs here.
636
        // The old gate justified every non-last line whenever text-justify
637
        // was not `none` - which is its DEFAULT (`auto` -> InterWord) - so
638
        // `text-align: left/center/right` paragraphs came out justified, and
639
        // lines before a forced break were justified against §6.3. The
640
        // greedy path documents the same trap (see cache.rs
641
        // "Without this check, ALL text gets justified").
642
349
        let should_justify = constraints.text_justify != JustifyContent::None
643
34
            && matches!(effective_align, TextAlign::Justify | TextAlign::JustifyAll);
644

            
645
        // Get the available width as f32 for calculations
646
        // For MinContent/MaxContent, we use the actual computed line_width
647
        // since there's no "available" space to justify into.
648
349
        let available_width_f32 = match constraints.available_width {
649
299
            AvailableSpace::Definite(w) => w,
650
18
            AvailableSpace::MaxContent => line_width,
651
32
            AvailableSpace::MinContent => line_width,
652
        };
653

            
654
349
        if should_justify {
655
30
            let space_to_add = available_width_f32 - line_width;
656
30
            if space_to_add > 0.0 {
657
2
                let space_count = line_items
658
2
                    .iter()
659
9
                    .filter(|item| is_word_separator(item))
660
2
                    .count();
661
2
                if space_count > 0 {
662
1
                    extra_per_space = space_to_add / space_count as f32;
663
1
                }
664
28
            }
665
319
        }
666

            
667
        // Alignment & Positioning
668
349
        let total_width: f32 = line_items
669
349
            .iter()
670
1564
            .map(|item| get_item_measure(item, false))
671
349
            .sum();
672

            
673
        // For MaxContent, don't apply alignment (treat as left-aligned)
674
349
        let is_indefinite = matches!(
675
349
            constraints.available_width,
676
            AvailableSpace::MaxContent | AvailableSpace::MinContent
677
        );
678
349
        let remaining_space = if is_indefinite {
679
50
            0.0
680
        } else {
681
299
            available_width_f32
682
299
                - (total_width
683
299
                    + extra_per_space
684
299
                        * line_items
685
299
                            .iter()
686
1512
                            .filter(|item| is_word_separator(item))
687
299
                            .count() as f32)
688
        };
689

            
690
        // +spec:writing-modes:155a06 - resolve start/end edges of line box per bidi direction
691
349
        let physical_align = match (effective_align, base_direction) {
692
4
            (TextAlign::Start, BidiDirection::Ltr) => TextAlign::Left,
693
1
            (TextAlign::Start, BidiDirection::Rtl) => TextAlign::Right,
694
5
            (TextAlign::End, BidiDirection::Ltr) => TextAlign::Right,
695
1
            (TextAlign::End, BidiDirection::Rtl) => TextAlign::Left,
696
338
            (other, _) => other,
697
        };
698

            
699
        // +spec:display-contents:5a1b30 - overflowing lines are start-aligned (overflow off end
700
        // edge)
701
349
        let mut main_axis_pen = if remaining_space < 0.0 {
702
36
            0.0
703
        } else {
704
313
            match physical_align {
705
14
                TextAlign::Center => remaining_space / 2.0,
706
6
                TextAlign::Right => remaining_space,
707
293
                _ => 0.0,
708
            }
709
        };
710

            
711
        // +spec:display-contents:21b27a - text-indent applies to initial letter's originating line
712
        // as usual +spec:line-breaking:bc389d - text-indent with each-line/hanging keywords
713
349
        if constraints.text_indent != 0.0 {
714
            // TODO: with text-indent-each-line, also detect lines after forced breaks in the KP
715
            // path
716
33
            let is_indent_target = line_index == 0;
717
33
            let should_indent = if constraints.text_indent_hanging {
718
10
                !is_indent_target
719
            } else {
720
23
                is_indent_target
721
            };
722
33
            if should_indent {
723
22
                main_axis_pen += constraints.text_indent;
724
22
            }
725
316
        }
726

            
727
1913
        for item in line_items {
728
1564
            let item_advance = get_item_measure(&item, false);
729

            
730
1564
            let draw_pos = match &item {
731
1528
                ShapedItem::Cluster(c) if !c.glyphs.is_empty() => {
732
                    let glyph = &c.glyphs[0];
733
                    Point {
734
                        x: main_axis_pen + glyph.offset.x,
735
                        y: cross_axis_pen - glyph.offset.y, // Use - for GPOS offset
736
                    }
737
                }
738
1564
                _ => Point {
739
1564
                    x: main_axis_pen,
740
1564
                    y: cross_axis_pen,
741
1564
                },
742
            };
743

            
744
1564
            positioned_items.push(PositionedItem {
745
1564
                item: item.clone(),
746
1564
                position: draw_pos,
747
1564
                line_index,
748
1564
            });
749

            
750
1564
            main_axis_pen += item_advance;
751

            
752
            // Apply extra spacing to the pen
753
1564
            if is_word_separator(&item) {
754
207
                main_axis_pen += extra_per_space;
755
1357
            }
756
        }
757

            
758
        // +spec:box-model:96f5a7 - line box height uses line-height only; inline
759
        // margins/borders/padding do not enter calculation
760
349
        cross_axis_pen += constraints.resolved_line_height();
761
349
        start_node = end_node;
762
    }
763

            
764
127
    let mut layout = UnifiedLayout {
765
127
        items: positioned_items,
766
127
        overflow: OverflowInfo::default(),
767
127
    };
768
    // Record the unclipped content bounds. `overflow_items` stays empty by
769
    // design: every item is positioned (visual overflow is clipped at paint
770
    // time), so nothing is dropped here. TODO(superplan): populate
771
    // `overflow_items` only if a path actually discards content that doesn't fit.
772
127
    let bounds = layout.bounds();
773
127
    layout.overflow.unclipped_bounds = bounds;
774
127
    layout
775
127
}
776

            
777
#[cfg(test)]
778
mod kp_fix_tests {
779
    use std::sync::Arc;
780

            
781
    use azul_core::selection::{ContentIndex, GraphemeClusterId};
782
    use azul_css::props::basic::FontRef;
783

            
784
    use super::*;
785
    use crate::text3::cache::{ShapedCluster, StyleProperties, UnifiedConstraints};
786

            
787
36
    fn cl(text: &str, advance: f32) -> ShapedItem {
788
36
        ShapedItem::Cluster(ShapedCluster {
789
36
            flags: crate::text3::cache::ClusterFlags::classify(text),
790
36
            source_text: Arc::from(text),
791
36
            source_byte_len: text.len() as u16,
792
36
            source_cluster_id: GraphemeClusterId {
793
36
                source_run: 0,
794
36
                start_byte_in_run: 0,
795
36
            },
796
36
            source_content_index: ContentIndex {
797
36
                run_index: 0,
798
36
                item_index: 0,
799
36
            },
800
36
            source_node_id: None,
801
36
            glyphs: smallvec::SmallVec::new(),
802
36
            advance,
803
36
            direction: BidiDirection::Ltr,
804
36
            style: Arc::new(StyleProperties::default()),
805
36
            marker_position_outside: None,
806
36
            is_first_fragment: true,
807
36
            is_last_fragment: true,
808
36
        })
809
36
    }
810

            
811
4
    fn nodes_for(text: &str) -> Vec<LayoutNode> {
812
        // Build per-grapheme clusters like the real shaper. 12px letters, 6px '-', 5px space.
813
4
        let items: Vec<ShapedItem> = text
814
4
            .chars()
815
36
            .map(|c| {
816
36
                let s = c.to_string();
817
36
                let adv = match c {
818
3
                    ' ' => 5.0,
819
1
                    '-' => 6.0,
820
32
                    _ => 12.0,
821
                };
822
36
                cl(&s, adv)
823
36
            })
824
4
            .collect();
825
4
        let fonts: LoadedFonts<FontRef> = LoadedFonts::new();
826
4
        convert_items_to_nodes(
827
4
            &items,
828
4
            None,
829
4
            &fonts,
830
4
            &UnifiedConstraints::default(),
831
4
            BidiDirection::Ltr,
832
        )
833
4
    }
834

            
835
    #[test]
836
1
    fn bug1_terminal_break_wraps_word_ending_paragraph() {
837
        // "aaaa aaaa" (ends in a Box, no trailing space) must wrap at width 60.
838
1
        let nodes = nodes_for("aaaa aaaa");
839
1
        assert!(
840
1
            matches!(nodes.last(), Some(LayoutNode::Penalty { penalty, .. }) if *penalty <= -INFINITY_BADNESS),
841
            "a terminal forced break must be appended"
842
        );
843
1
        let c = UnifiedConstraints {
844
1
            available_width: AvailableSpace::Definite(60.0),
845
1
            ..Default::default()
846
1
        };
847
1
        let breaks = find_optimal_breakpoints(&nodes, &c);
848
1
        assert!(
849
1
            breaks.len() >= 2,
850
            "must break into >=2 lines, got {breaks:?}"
851
        );
852
1
        assert_eq!(*breaks.last().unwrap(), nodes.len(), "final break at n");
853
1
    }
854

            
855
    #[test]
856
1
    fn bug2_hyphen_is_break_opportunity() {
857
        // "aaaa-aaaa": a zero-width penalty must follow the '-' Box.
858
1
        let nodes = nodes_for("aaaa-aaaa");
859
        // find the '-' box and assert the next node is a zero-width penalty
860
1
        let mut found = false;
861
11
        for (i, n) in nodes.iter().enumerate() {
862
9
            if let LayoutNode::Box(ShapedItem::Cluster(cc), _) = n {
863
9
                if cc.text() == "-" {
864
1
                    match nodes.get(i + 1) {
865
1
                        Some(LayoutNode::Penalty { penalty, width, .. }) => {
866
1
                            assert!(
867
1
                                *width == 0.0 && *penalty > -INFINITY_BADNESS,
868
                                "hyphen must be followed by a zero-width soft penalty"
869
                            );
870
1
                            found = true;
871
                        }
872
                        other => panic!("expected penalty after hyphen, got {other:?}"),
873
                    }
874
8
                }
875
2
            }
876
        }
877
1
        assert!(found, "hyphen box must exist");
878
        // and it must actually enable a wrap at width 60
879
1
        let c = UnifiedConstraints {
880
1
            available_width: AvailableSpace::Definite(60.0),
881
1
            ..Default::default()
882
1
        };
883
1
        let breaks = find_optimal_breakpoints(&nodes, &c);
884
1
        assert!(
885
1
            breaks.len() >= 2,
886
            "hyphenated token must wrap, got {breaks:?}"
887
        );
888
1
    }
889

            
890
    #[test]
891
1
    fn bug4_min_content_breaks_every_word() {
892
        // "aaaa aaaa" min-content: two words => two content lines (widest = one word).
893
1
        let nodes = nodes_for("aaaa aaaa");
894
1
        let c = UnifiedConstraints {
895
1
            available_width: AvailableSpace::MinContent,
896
1
            ..Default::default()
897
1
        };
898
1
        let breaks = find_optimal_breakpoints(&nodes, &c);
899
        // there must be a break after the first word's trailing space penalty,
900
        // i.e. more than one break -> not a single spanning line.
901
1
        assert!(
902
1
            breaks.len() >= 2,
903
            "min-content must break per word, got {breaks:?}"
904
        );
905
1
    }
906

            
907
    #[test]
908
1
    fn bug3_trailing_space_trimmed_from_line() {
909
        // "aaaa aaaa" @60 wraps to [.., 6, 11]; line 0 = "aaaa" + trailing space.
910
1
        let nodes = nodes_for("aaaa aaaa");
911
1
        let c = UnifiedConstraints {
912
1
            available_width: AvailableSpace::Definite(60.0),
913
1
            ..Default::default()
914
1
        };
915
1
        let breaks = find_optimal_breakpoints(&nodes, &c);
916
1
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
917
        // The line-terminating space must not be positioned on line 0.
918
1
        let line0_spaces = layout
919
1
            .items
920
1
            .iter()
921
8
            .filter(|it| it.line_index == 0 && is_word_separator(&it.item))
922
1
            .count();
923
1
        assert_eq!(
924
            line0_spaces, 0,
925
            "trailing space must be trimmed from line 0"
926
        );
927
        // Rightmost cluster edge on line 0 == 4*12 = 48px (not 53 incl. the space).
928
1
        let max_x = layout
929
1
            .items
930
1
            .iter()
931
8
            .filter(|it| it.line_index == 0)
932
4
            .filter_map(|it| it.item.as_cluster().map(|cc| it.position.x + cc.advance))
933
1
            .fold(0.0f32, f32::max);
934
1
        assert!(
935
1
            (max_x - 48.0).abs() < 0.01,
936
            "line 0 right edge {max_x} should be 48px"
937
        );
938
1
    }
939
}
940

            
941
#[cfg(test)]
942
#[allow(clippy::float_cmp)] // exact geometry: every advance below is an exact f32
943
#[allow(clippy::cast_precision_loss)] // small line counters
944
mod autotest_generated {
945
    use std::sync::Arc;
946

            
947
    use azul_core::selection::{ContentIndex, GraphemeClusterId};
948
    use azul_css::props::basic::FontRef;
949

            
950
    use super::*;
951
    use crate::text3::cache::{
952
        BreakType, ClearType, InlineBreak, InlineContent, LineHeight, Rect, ShapedCluster,
953
        StyleProperties,
954
    };
955

            
956
    // ---------------------------------------------------------------------
957
    // Builders. Every item is a single-grapheme cluster with an explicit
958
    // advance, mirroring what the shaper produces: 12px letters, 5px space,
959
    // 6px hyphen. No glyphs -> get_item_measure() == advance exactly, so all
960
    // expected coordinates below are exact integers.
961
    // ---------------------------------------------------------------------
962

            
963
    fn cl(text: &str, advance: f32) -> ShapedItem {
964
        ShapedItem::Cluster(ShapedCluster {
965
            flags: crate::text3::cache::ClusterFlags::classify(text),
966
            source_text: Arc::from(text),
967
            source_byte_len: text.len() as u16,
968
            source_cluster_id: GraphemeClusterId {
969
                source_run: 0,
970
                start_byte_in_run: 0,
971
            },
972
            source_content_index: ContentIndex {
973
                run_index: 0,
974
                item_index: 0,
975
            },
976
            source_node_id: None,
977
            glyphs: smallvec::SmallVec::new(),
978
            advance,
979
            direction: BidiDirection::Ltr,
980
            style: Arc::new(StyleProperties::default()),
981
            marker_position_outside: None,
982
            is_first_fragment: true,
983
            is_last_fragment: true,
984
        })
985
    }
986

            
987
    fn advance_of(c: char) -> f32 {
988
        match c {
989
            ' ' => 5.0,
990
            '-' => 6.0,
991
            _ => 12.0,
992
        }
993
    }
994

            
995
    /// One cluster per `char`, like the real shaper hands to `kp_layout`.
996
    fn items_of(text: &str) -> Vec<ShapedItem> {
997
        text.chars()
998
            .map(|c| cl(&c.to_string(), advance_of(c)))
999
            .collect()
    }
    fn no_fonts() -> LoadedFonts<FontRef> {
        LoadedFonts::new()
    }
    /// `convert_items_to_nodes` with hyphenation disabled (the hyphenator is a
    /// feature-gated type and needs a real dictionary; `None` is the path the
    /// engine takes whenever `hyphens: none`).
    fn nodes_of(items: &[ShapedItem]) -> Vec<LayoutNode> {
        convert_items_to_nodes(
            items,
            None,
            &no_fonts(),
            &UnifiedConstraints::default(),
            BidiDirection::Ltr,
        )
    }
    fn nodes_for(text: &str) -> Vec<LayoutNode> {
        nodes_of(&items_of(text))
    }
    fn definite(width: f32) -> UnifiedConstraints {
        UnifiedConstraints {
            available_width: AvailableSpace::Definite(width),
            ..Default::default()
        }
    }
    fn object(width: f32) -> ShapedItem {
        ShapedItem::Object {
            source: ContentIndex {
                run_index: 0,
                item_index: 0,
            },
            bounds: Rect {
                x: 0.0,
                y: 0.0,
                width,
                height: 10.0,
            },
            baseline_offset: 0.0,
            content: InlineContent::Tab {
                style: Arc::new(StyleProperties::default()),
            },
        }
    }
    fn tab(width: f32) -> ShapedItem {
        ShapedItem::Tab {
            source: ContentIndex {
                run_index: 0,
                item_index: 0,
            },
            bounds: Rect {
                x: 0.0,
                y: 0.0,
                width,
                height: 10.0,
            },
        }
    }
    fn hard_break() -> ShapedItem {
        ShapedItem::Break {
            source: ContentIndex {
                run_index: 0,
                item_index: 0,
            },
            break_info: InlineBreak {
                break_type: BreakType::Hard,
                clear: ClearType::None,
                content_index: 0,
            },
        }
    }
    fn rtl_logical() -> Vec<LogicalItem> {
        vec![LogicalItem::Text {
            source: ContentIndex {
                run_index: 0,
                item_index: 0,
            },
            text: Arc::from("\u{05E9}\u{05DC}\u{05D5}\u{05DD}"), // "שלום"
            style: Arc::new(StyleProperties::default()),
            marker_position_outside: None,
            source_node_id: None,
        }]
    }
    // ---------------------------------------------------------------------
    // Inspectors
    // ---------------------------------------------------------------------
    fn is_forced(node: &LayoutNode) -> bool {
        matches!(node, LayoutNode::Penalty { penalty, .. } if *penalty <= -INFINITY_BADNESS)
    }
    fn penalty_count(nodes: &[LayoutNode]) -> usize {
        nodes
            .iter()
            .filter(|n| matches!(n, LayoutNode::Penalty { .. }))
            .count()
    }
    fn line_text(layout: &UnifiedLayout, line: usize) -> String {
        layout
            .items
            .iter()
            .filter(|it| it.line_index == line)
            .filter_map(|it| it.item.as_cluster().map(|c| c.text()))
            .collect()
    }
    fn line_count(layout: &UnifiedLayout) -> usize {
        layout
            .items
            .iter()
            .map(|it| it.line_index + 1)
            .max()
            .unwrap_or(0)
    }
    fn line_left(layout: &UnifiedLayout, line: usize) -> f32 {
        layout
            .items
            .iter()
            .filter(|it| it.line_index == line)
            .map(|it| it.position.x)
            .fold(f32::INFINITY, f32::min)
    }
    fn line_right(layout: &UnifiedLayout, line: usize) -> f32 {
        layout
            .items
            .iter()
            .filter(|it| it.line_index == line)
            .map(|it| it.position.x + get_item_measure(&it.item, false))
            .fold(f32::NEG_INFINITY, f32::max)
    }
    /// Structural contract of `find_optimal_breakpoints`: the returned indices
    /// are strictly increasing, in range, and the paragraph ends at `n`.
    fn assert_breaks_well_formed(nodes: &[LayoutNode], breaks: &[usize], what: &str) {
        for w in breaks.windows(2) {
            assert!(
                w[0] < w[1],
                "{what}: breaks must be strictly increasing, got {breaks:?}"
            );
        }
        for &b in breaks {
            assert!(
                b <= nodes.len(),
                "{what}: break {b} out of range (n = {})",
                nodes.len()
            );
        }
        if !breaks.is_empty() {
            assert_eq!(
                *breaks.last().unwrap(),
                nodes.len(),
                "{what}: the paragraph must end at the last node"
            );
        }
    }
    // =====================================================================
    // convert_items_to_nodes: structure of the Box/Glue/Penalty stream
    // =====================================================================
    #[test]
    fn convert_empty_items_yields_no_nodes() {
        // The terminal-forced-break append is guarded on !nodes.is_empty(),
        // so an empty paragraph must stay empty (not gain a lone penalty).
        assert!(nodes_of(&[]).is_empty());
    }
    #[test]
    fn convert_appends_exactly_one_terminal_forced_break() {
        let nodes = nodes_for("ab cd");
        assert!(
            is_forced(nodes.last().unwrap()),
            "paragraph must be anchored"
        );
        assert_eq!(
            nodes.iter().filter(|n| is_forced(n)).count(),
            1,
            "exactly one forced break for a paragraph with no explicit breaks"
        );
    }
    #[test]
    fn convert_does_not_duplicate_terminal_break_after_an_explicit_break() {
        let items = vec![cl("a", 12.0), hard_break()];
        let nodes = nodes_of(&items);
        assert_eq!(
            nodes.len(),
            2,
            "Box + the Break's own forced Penalty, no more"
        );
        assert!(is_forced(&nodes[1]));
        assert_eq!(nodes.iter().filter(|n| is_forced(n)).count(), 1);
    }
    #[test]
    fn convert_space_glue_uses_the_documented_stretch_shrink_ratios() {
        let nodes = nodes_for("a b");
        let glue = nodes
            .iter()
            .find(|n| matches!(n, LayoutNode::Glue { .. }))
            .expect("a space must become Glue");
        match glue {
            LayoutNode::Glue {
                width,
                stretch,
                shrink,
                ..
            } => {
                assert_eq!(*width, 5.0);
                assert_eq!(*stretch, 5.0 * SPACE_STRETCH_RATIO);
                assert_eq!(*shrink, 5.0 * SPACE_SHRINK_RATIO);
                assert!(*shrink < *width, "a space may never shrink past zero width");
            }
            _ => unreachable!(),
        }
    }
    #[test]
    fn convert_zero_width_space_becomes_an_itemless_penalty() {
        // U+200B is a wrap opportunity with no glyph: it must produce a
        // zero-width, zero-cost Penalty and contribute no Box.
        let items = vec![cl("a", 12.0), cl("\u{200B}", 0.0), cl("b", 12.0)];
        let nodes = nodes_of(&items);
        let zwsp = match &nodes[1] {
            LayoutNode::Penalty {
                item,
                width,
                penalty,
            } => (item.is_none(), *width, *penalty),
            other => panic!("expected a Penalty for U+200B, got {other:?}"),
        };
        assert_eq!(zwsp, (true, 0.0, 0.0));
        // ...and it really is a break opportunity at a narrow width.
        let breaks = find_optimal_breakpoints(&nodes, &definite(12.0));
        assert_breaks_well_formed(&nodes, &breaks, "zwsp");
    }
    #[test]
    fn convert_both_hyphen_codepoints_are_soft_wrap_opportunities() {
        // U+002D HYPHEN-MINUS and U+2010 HYPHEN are UAX#14 class BA: a break is
        // allowed AFTER them, and no extra hyphen glyph is inserted.
        for hyphen in ['\u{002D}', '\u{2010}'] {
            let items = vec![cl("a", 12.0), cl(&hyphen.to_string(), 6.0), cl("b", 12.0)];
            let nodes = nodes_of(&items);
            match (&nodes[1], &nodes[2]) {
                (
                    LayoutNode::Box(ShapedItem::Cluster(c), w),
                    LayoutNode::Penalty {
                        item,
                        width,
                        penalty,
                    },
                ) => {
                    assert_eq!(c.text(), hyphen.to_string());
                    assert_eq!(*w, 6.0);
                    assert!(item.is_none(), "no extra hyphen glyph may be inserted");
                    assert_eq!(*width, 0.0);
                    assert!(
                        *penalty > -INFINITY_BADNESS,
                        "the hyphen break is optional, not forced"
                    );
                }
                other => panic!("expected Box('{hyphen}') + zero-width Penalty, got {other:?}"),
            }
        }
    }
    #[test]
    fn convert_atomic_inline_is_wrapped_in_wrap_opportunities() {
        // CSS Text 3 §5.1: a soft wrap opportunity exists before AND after each
        // replaced element / atomic inline.
        let nodes = nodes_of(&[object(40.0)]);
        assert!(matches!(nodes[0], LayoutNode::Penalty { .. }));
        assert!(matches!(nodes[1], LayoutNode::Box(_, w) if w == 40.0));
        assert!(matches!(nodes[2], LayoutNode::Penalty { .. }));
    }
    #[test]
    fn convert_tab_is_glue_and_not_a_wrap_opportunity() {
        // A tab is stretchable like a space but is NOT followed by a Penalty,
        // so no line may break at it.
        let nodes = nodes_of(&[cl("a", 12.0), tab(30.0), cl("b", 12.0)]);
        match &nodes[1] {
            LayoutNode::Glue {
                width,
                stretch,
                shrink,
                ..
            } => {
                assert_eq!(*width, 30.0);
                assert_eq!(*stretch, 30.0 * SPACE_STRETCH_RATIO);
                assert_eq!(*shrink, 30.0 * SPACE_SHRINK_RATIO);
            }
            other => panic!("a tab must become Glue, got {other:?}"),
        }
        assert_eq!(
            penalty_count(&nodes),
            1,
            "only the terminal forced break; a tab offers no wrap opportunity"
        );
    }
    #[test]
    fn nbsp_must_not_be_a_soft_wrap_opportunity() {
        // UAX#14 class GL. cache.rs suppresses NBSP /
        // NNBSP / WJ / ZWNBSP as break opportunities in the greedy path
        // (`is_break_opportunity_with_word_break`, "otherwise 10\u{00A0}km
        // wrongly wraps"), but convert_items_to_nodes keys off
        // `is_word_separator`, which reports NBSP as a separator -- so the
        // Knuth-Plass path emits Glue + Penalty and "10\u{00A0}km" CAN wrap at
        // the no-break space. See the report accompanying this test batch.
        for nbsp in ['\u{00A0}', '\u{202F}'] {
            let items = vec![cl("1", 12.0), cl(&nbsp.to_string(), 5.0), cl("k", 12.0)];
            let nodes = nodes_of(&items);
            let optional_breaks = nodes
                .iter()
                .filter(|n| matches!(n, LayoutNode::Penalty { .. }) && !is_forced(n))
                .count();
            assert_eq!(
                optional_breaks, 0,
                "U+{:04X} is a no-break space: it must not offer a wrap opportunity, got {nodes:?}",
                nbsp as u32
            );
        }
    }
    #[test]
    fn cjk_run_gains_inter_character_wrap_opportunities() {
        // U+3000 stays a non-separator (CSS Text §7.1), but word-break is
        // threaded through kp_layout now: under `normal`, CJK clusters offer
        // a soft-wrap opportunity after each ideograph, exactly like the
        // greedy path (line-breaking:16e64c). Two inter-cluster penalties +
        // the terminal forced break.
        let items = vec![
            cl("\u{4E00}", 16.0),
            cl("\u{3000}", 16.0),
            cl("\u{4E8C}", 16.0),
        ];
        let nodes = nodes_of(&items);
        assert_eq!(
            penalty_count(&nodes),
            3,
            "two CJK inter-character opportunities plus the terminal break"
        );
        let breaks = find_optimal_breakpoints(&nodes, &definite(20.0));
        assert_breaks_well_formed(&nodes, &breaks, "cjk");
        // And the run actually wraps at 20px now.
        assert!(breaks.len() >= 2, "the CJK run must wrap: {breaks:?}");
    }
    #[test]
    fn convert_survives_hostile_unicode_without_panicking() {
        // Combining marks, an emoji ZWJ sequence, RTL text, a lone surrogate is
        // impossible in Rust, so use the next-worst thing: unpaired combining
        // marks, an unassigned plane-15 codepoint, and a zero-advance cluster.
        let items = vec![
            cl("e\u{0301}", 12.0),
            cl("\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}", 48.0),
            cl("\u{05D0}", 12.0),
            cl("\u{FFFD}", 12.0),
            cl("\u{F0000}", 0.0),
            cl("", 0.0),
        ];
        let nodes = nodes_of(&items);
        // Nothing is a separator or a hyphen, so every cluster stays a Box.
        assert_eq!(
            nodes
                .iter()
                .filter(|n| matches!(n, LayoutNode::Box(..)))
                .count(),
            items.len()
        );
        let layout = kp_layout(&items, &[], &definite(30.0), None, &no_fonts());
        assert_eq!(
            layout.items.len(),
            items.len(),
            "no cluster may be dropped by the layout"
        );
    }
    // =====================================================================
    // find_optimal_breakpoints: numeric limits & structural invariants
    // =====================================================================
    #[test]
    fn breakpoints_of_an_empty_paragraph_are_empty() {
        assert!(find_optimal_breakpoints(&[], &definite(100.0)).is_empty());
        assert!(find_optimal_breakpoints(&[], &UnifiedConstraints::default()).is_empty());
    }
    #[test]
    fn breakpoints_of_an_empty_paragraph_under_min_content_stay_in_range() {
        // The MinContent fast path appends nodes.len() unconditionally, so an
        // empty node list yields [0]. That must still be a safe input to the
        // positioner (kp_layout short-circuits before this, but the DP is
        // callable on its own).
        let breaks = find_optimal_breakpoints(
            &[],
            &UnifiedConstraints {
                available_width: AvailableSpace::MinContent,
                ..Default::default()
            },
        );
        assert_breaks_well_formed(&[], &breaks, "empty min-content");
        let layout = position_lines_from_breaks(
            &[],
            &breaks,
            &[],
            &UnifiedConstraints {
                available_width: AvailableSpace::MinContent,
                ..Default::default()
            },
        );
        assert!(layout.items.is_empty());
    }
    #[test]
    fn breaks_stay_well_formed_across_pathological_widths() {
        let nodes = nodes_for("aa bb cccc");
        let widths = [
            AvailableSpace::Definite(0.0),
            AvailableSpace::Definite(1.0),
            AvailableSpace::Definite(-100.0),
            AvailableSpace::Definite(f32::MIN),
            AvailableSpace::Definite(f32::MAX),
            AvailableSpace::Definite(f32::INFINITY),
            AvailableSpace::Definite(f32::NEG_INFINITY),
            AvailableSpace::Definite(f32::NAN),
            AvailableSpace::Definite(f32::EPSILON),
            AvailableSpace::MinContent,
            AvailableSpace::MaxContent,
        ];
        for w in widths {
            let c = UnifiedConstraints {
                available_width: w,
                ..Default::default()
            };
            let breaks = find_optimal_breakpoints(&nodes, &c);
            assert_breaks_well_formed(&nodes, &breaks, &format!("{w:?}"));
            // The positioner must survive whatever the DP produced.
            let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
            assert!(
                layout.items.len() <= nodes.len(),
                "{w:?}: cannot position more items than there are nodes"
            );
        }
    }
    #[test]
    fn breaks_land_only_after_penalty_nodes_in_a_feasible_paragraph() {
        // Knuth-Plass may only break at a Penalty: `breaks[k]` is the index one
        // past the last node of a line, so nodes[breaks[k] - 1] must be one.
        let nodes = nodes_for("aa bb cccc");
        let breaks = find_optimal_breakpoints(&nodes, &definite(60.0));
        assert!(breaks.len() >= 2, "must wrap at 60px, got {breaks:?}");
        for &b in &breaks {
            assert!(
                matches!(nodes[b - 1], LayoutNode::Penalty { .. }),
                "break at {b} follows {:?}, which is not a legal break point",
                nodes[b - 1]
            );
        }
    }
    #[test]
    fn nan_advances_do_not_panic_or_hang() {
        let items = vec![
            cl("a", f32::NAN),
            cl(" ", f32::NAN),
            cl("b", f32::NAN),
            cl("c", 12.0),
        ];
        let nodes = nodes_of(&items);
        let c = definite(50.0);
        let breaks = find_optimal_breakpoints(&nodes, &c);
        assert_breaks_well_formed(&nodes, &breaks, "NaN advances");
        // Positioning NaN geometry may yield NaN coordinates, but must not panic
        // and must not lose content.
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        assert_eq!(
            layout
                .items
                .iter()
                .filter(|it| it.item.as_cluster().is_some_and(|cc| cc.text() != " "))
                .count(),
            3
        );
    }
    #[test]
    fn infinite_advance_collapses_to_one_overfull_line_without_panicking() {
        let items = vec![cl("a", f32::INFINITY)];
        let nodes = nodes_of(&items);
        let c = definite(100.0);
        let breaks = find_optimal_breakpoints(&nodes, &c);
        assert_breaks_well_formed(&nodes, &breaks, "infinite advance");
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        assert_eq!(layout.items.len(), 1);
        // Overflowing lines are start-aligned, so the pen never moves off zero.
        assert_eq!(layout.items[0].position.x, 0.0);
    }
    #[test]
    fn extreme_text_indent_does_not_panic() {
        let nodes = nodes_for("aa bb cccc");
        for indent in [f32::MAX, f32::MIN, -1000.0, f32::NAN, f32::INFINITY] {
            for hanging in [false, true] {
                let c = UnifiedConstraints {
                    available_width: AvailableSpace::Definite(100.0),
                    text_indent: indent,
                    text_indent_hanging: hanging,
                    ..Default::default()
                };
                let breaks = find_optimal_breakpoints(&nodes, &c);
                assert_breaks_well_formed(&nodes, &breaks, &format!("indent {indent}"));
                let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
                assert!(layout.items.len() <= nodes.len());
            }
        }
    }
    #[test]
    fn zero_width_container_keeps_all_content() {
        // width: 0px is a genuinely zero-width container, not "unresolved":
        // every line overflows, but nothing may be dropped.
        let nodes = nodes_for("aa bb");
        let c = definite(0.0);
        let breaks = find_optimal_breakpoints(&nodes, &c);
        assert_breaks_well_formed(&nodes, &breaks, "zero width");
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        let letters = layout
            .items
            .iter()
            .filter(|it| it.item.as_cluster().is_some_and(|cc| cc.text() != " "))
            .count();
        assert_eq!(letters, 4, "all four letters must still be positioned");
    }
    #[test]
    fn min_content_breaks_at_every_penalty() {
        let nodes = nodes_for("aa bb cccc");
        let c = UnifiedConstraints {
            available_width: AvailableSpace::MinContent,
            ..Default::default()
        };
        let breaks = find_optimal_breakpoints(&nodes, &c);
        assert_breaks_well_formed(&nodes, &breaks, "min-content");
        // One break per Penalty node (the terminal penalty's break IS nodes.len()).
        assert_eq!(breaks.len(), penalty_count(&nodes));
        for &b in &breaks {
            assert!(matches!(nodes[b - 1], LayoutNode::Penalty { .. }));
        }
    }
    #[test]
    fn max_content_puts_an_unforced_paragraph_on_a_single_line() {
        let nodes = nodes_for("aa bb cccc");
        let c = UnifiedConstraints {
            available_width: AvailableSpace::MaxContent,
            ..Default::default()
        };
        let breaks = find_optimal_breakpoints(&nodes, &c);
        assert_eq!(
            breaks,
            vec![nodes.len()],
            "max-content must not wrap without a forced break"
        );
    }
    #[test]
    fn forced_break_item_starts_a_new_line_even_under_max_content() {
        let items = vec![cl("a", 12.0), hard_break(), cl("b", 12.0)];
        let c = UnifiedConstraints {
            available_width: AvailableSpace::MaxContent,
            ..Default::default()
        };
        let layout = kp_layout(&items, &[], &c, None, &no_fonts());
        assert_eq!(line_count(&layout), 2, "a Break must force a second line");
        assert_eq!(line_text(&layout, 0), "a");
        assert_eq!(line_text(&layout, 1), "b");
    }
    #[test]
    fn dp_terminates_on_a_paragraph_that_is_all_break_opportunities() {
        // 400 zero-width spaces: every node is a Penalty, i.e. the DP's worst
        // case (O(n^2) candidate pairs). It must terminate and produce a
        // well-formed, in-range break list.
        let items: Vec<ShapedItem> = (0..400).map(|_| cl("\u{200B}", 0.0)).collect();
        let nodes = nodes_of(&items);
        assert_eq!(penalty_count(&nodes), nodes.len());
        let breaks = find_optimal_breakpoints(&nodes, &definite(100.0));
        assert_breaks_well_formed(&nodes, &breaks, "all-penalty");
    }
    #[test]
    fn large_paragraph_keeps_every_glyph() {
        let text = "aaa ".repeat(300);
        let items = items_of(&text);
        let layout = kp_layout(&items, &[], &definite(100.0), None, &no_fonts());
        let letters = layout
            .items
            .iter()
            .filter(|it| it.item.as_cluster().is_some_and(|c| c.text() == "a"))
            .count();
        assert_eq!(letters, 900, "no glyph may be lost while wrapping");
        // line_index is emitted in reading order.
        assert!(layout
            .items
            .windows(2)
            .all(|w| w[0].line_index <= w[1].line_index));
    }
    #[test]
    fn a_multi_line_paragraph_must_not_collapse_onto_one_overfull_line() {
        // `breakpoints[].demerit` is seeded with
        // INFINITY_BADNESS, a *finite* 10_000 -- but demerits ACCUMULATE across
        // lines (`demerit = badness + breakpoints[j].demerit`). Once the optimal
        // path's cumulative demerit passes 10_000, no candidate can ever satisfy
        // `demerit < breakpoints[i + 1].demerit` again, so no further breakpoint
        // is recorded and the backtrack falls through the default
        // `previous: 0` -- putting the entire paragraph on one overfull line.
        //
        // Here each 2-word line has ratio 3.6 -> badness ~4_666, so the third
        // line (cumulative ~13_997) is already unrepresentable. Any paragraph of
        // loose lines hits this; even perfectly-fitting lines hit it once they
        // are numerous enough. Fix: seed `demerit` with f32::INFINITY instead of
        // reusing the badness constant as the sentinel.
        let text = "aaa ".repeat(8); // 8 words, 36px each + 5px spaces
        let items = items_of(&text);
        let layout = kp_layout(&items, &[], &definite(100.0), None, &no_fonts());
        let lines = line_count(&layout);
        assert!(
            lines >= 4,
            "at most 2 of these 41px words fit per 100px line, so 8 words need >= 4 lines; got \
             {lines}"
        );
        for line in 0..lines {
            assert!(
                line_right(&layout, line) <= 100.5,
                "line {line} runs to {}px in a 100px container",
                line_right(&layout, line)
            );
        }
    }
    // =====================================================================
    // position_lines_from_breaks: geometry, alignment, justification
    // =====================================================================
    #[test]
    fn position_with_no_breaks_yields_an_empty_layout() {
        let nodes = nodes_for("ab");
        let layout = position_lines_from_breaks(&nodes, &[], &[], &definite(100.0));
        assert!(layout.items.is_empty());
        assert_eq!(layout.overflow.unclipped_bounds.width, 0.0);
    }
    #[test]
    fn position_tolerates_a_repeated_break_index() {
        // A degenerate empty line (start == end) must not panic or shift content.
        let nodes = nodes_for("aa bb cccc");
        let n = nodes.len();
        let layout = position_lines_from_breaks(&nodes, &[8, 8, n], &[], &definite(100.0));
        assert_eq!(line_text(&layout, 0), "aa bb");
        assert_eq!(line_text(&layout, 1), "", "the empty line holds nothing");
        assert_eq!(line_text(&layout, 2), "cccc");
    }
    #[test]
    fn lines_advance_by_exactly_the_resolved_line_height() {
        let nodes = nodes_for("aa bb cccc");
        let c = UnifiedConstraints {
            available_width: AvailableSpace::Definite(60.0),
            line_height: LineHeight::Px(20.0),
            ..Default::default()
        };
        let breaks = find_optimal_breakpoints(&nodes, &c);
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        assert_eq!(c.resolved_line_height(), 20.0);
        for it in &layout.items {
            assert_eq!(
                it.position.y,
                20.0 * it.line_index as f32,
                "line {} must sit at {}px",
                it.line_index,
                20.0 * it.line_index as f32
            );
        }
    }
    #[test]
    fn left_aligned_pen_starts_at_zero_and_never_moves_backwards() {
        let nodes = nodes_for("aa bb cccc");
        let c = definite(60.0);
        let breaks = find_optimal_breakpoints(&nodes, &c);
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        for line in 0..line_count(&layout) {
            let xs: Vec<f32> = layout
                .items
                .iter()
                .filter(|it| it.line_index == line)
                .map(|it| it.position.x)
                .collect();
            assert_eq!(xs[0], 0.0, "line {line} must start at the left edge");
            assert!(
                xs.windows(2).all(|w| w[0] <= w[1]),
                "the pen must advance monotonically on line {line}: {xs:?}"
            );
        }
    }
    #[test]
    fn center_and_right_alignment_use_the_exact_remaining_space() {
        // "aaaa" = 48px in a 100px box -> 52px of slack.
        let nodes = nodes_for("aaaa");
        for (align, expected_left) in [
            (TextAlign::Left, 0.0f32),
            (TextAlign::Center, 26.0),
            (TextAlign::Right, 52.0),
            (TextAlign::Start, 0.0),
            (TextAlign::End, 52.0),
        ] {
            let c = UnifiedConstraints {
                available_width: AvailableSpace::Definite(100.0),
                text_align: align,
                ..Default::default()
            };
            let breaks = find_optimal_breakpoints(&nodes, &c);
            let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
            assert_eq!(
                line_left(&layout, 0),
                expected_left,
                "{align:?} must place the line at {expected_left}px"
            );
            assert_eq!(line_right(&layout, 0), expected_left + 48.0);
        }
    }
    #[test]
    fn an_overflowing_line_is_start_aligned_even_when_right_aligned() {
        // +spec: overflowing lines overflow the END edge, so the pen stays at 0
        // instead of going negative.
        let nodes = nodes_for("aaaaaaaa"); // 96px
        for align in [TextAlign::Right, TextAlign::Center, TextAlign::End] {
            let c = UnifiedConstraints {
                available_width: AvailableSpace::Definite(50.0),
                text_align: align,
                ..Default::default()
            };
            let breaks = find_optimal_breakpoints(&nodes, &c);
            let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
            assert_eq!(
                line_left(&layout, 0),
                0.0,
                "{align:?}: an overfull line must not be pushed to a negative x"
            );
            assert_eq!(line_text(&layout, 0), "aaaaaaaa", "no glyph may be dropped");
        }
    }
    #[test]
    fn rtl_base_direction_flips_logical_start_and_end() {
        // 3 clusters = 36px in a 100px box -> 64px of slack.
        let nodes = nodes_for("abc");
        let c_start = UnifiedConstraints {
            available_width: AvailableSpace::Definite(100.0),
            text_align: TextAlign::Start,
            ..Default::default()
        };
        let c_end = UnifiedConstraints {
            text_align: TextAlign::End,
            ..c_start.clone()
        };
        let breaks = find_optimal_breakpoints(&nodes, &c_start);
        // LTR paragraph: start = left, end = right.
        assert_eq!(
            line_left(
                &position_lines_from_breaks(&nodes, &breaks, &[], &c_start),
                0
            ),
            0.0
        );
        assert_eq!(
            line_left(&position_lines_from_breaks(&nodes, &breaks, &[], &c_end), 0),
            64.0
        );
        // RTL paragraph (Hebrew logical items): start = right, end = left.
        let rtl = rtl_logical();
        assert_eq!(get_base_direction_from_logical(&rtl), BidiDirection::Rtl);
        assert_eq!(
            line_left(
                &position_lines_from_breaks(&nodes, &breaks, &rtl, &c_start),
                0
            ),
            64.0
        );
        assert_eq!(
            line_left(
                &position_lines_from_breaks(&nodes, &breaks, &rtl, &c_end),
                0
            ),
            0.0
        );
    }
    #[test]
    fn justification_stretches_inner_lines_and_leaves_the_last_line_alone() {
        // "aa bb cccc" @60px wraps to ["aa bb ", "cccc"]. Line 0 is 53px wide
        // after trimming its hanging space, so its single interior space must
        // absorb all 7px of slack; the last line must stay at its natural width.
        let nodes = nodes_for("aa bb cccc");
        let c = UnifiedConstraints {
            available_width: AvailableSpace::Definite(60.0),
            text_align: TextAlign::Justify,
            text_justify: JustifyContent::InterWord,
            ..Default::default()
        };
        let breaks = find_optimal_breakpoints(&nodes, &c);
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        assert_eq!(line_count(&layout), 2, "breaks: {breaks:?}");
        assert_eq!(line_text(&layout, 0), "aa bb");
        assert_eq!(line_text(&layout, 1), "cccc");
        assert_eq!(line_right(&layout, 0), 60.0, "inner line must be justified");
        assert_eq!(
            line_right(&layout, 1),
            48.0,
            "text-align: justify must not stretch the last line"
        );
    }
    #[test]
    fn word_break_break_all_grants_intra_word_breaks_in_the_kp_path() {
        use crate::text3::cache::WordBreak;
        // "aaaa" = four 12px clusters, no spaces. At 30px it can only wrap if
        // word-break: break-all inserts opportunities between clusters.
        let nodes_normal = {
            let items: Vec<ShapedItem> =
                "aaaa".chars().map(|ch| cl(&ch.to_string(), 12.0)).collect();
            let fonts: LoadedFonts<FontRef> = LoadedFonts::new();
            let c = UnifiedConstraints::default();
            convert_items_to_nodes(&items, None, &fonts, &c, BidiDirection::Ltr)
        };
        let n_pen_normal = nodes_normal
            .iter()
            .filter(|n| matches!(n, LayoutNode::Penalty { .. }))
            .count();
        let nodes_break_all = {
            let items: Vec<ShapedItem> =
                "aaaa".chars().map(|ch| cl(&ch.to_string(), 12.0)).collect();
            let fonts: LoadedFonts<FontRef> = LoadedFonts::new();
            let c = UnifiedConstraints {
                word_break: WordBreak::BreakAll,
                ..Default::default()
            };
            convert_items_to_nodes(&items, None, &fonts, &c, BidiDirection::Ltr)
        };
        let n_pen_break_all = nodes_break_all
            .iter()
            .filter(|n| matches!(n, LayoutNode::Penalty { .. }))
            .count();
        assert!(
            n_pen_break_all > n_pen_normal,
            "break-all must add intra-word opportunities: normal={n_pen_normal}, \
             break-all={n_pen_break_all}"
        );
        // Three inter-cluster boundaries + the terminal forced break.
        assert_eq!(n_pen_break_all, n_pen_normal + 3);
    }
    #[test]
    fn hyphenation_is_suppressed_for_direction_mismatched_words() {
        // An LTR word inside an RTL paragraph must not be hyphenated (CSS 2.2
        // §9.10 note): the hyphen would land visually mid-line. Pin at the
        // node level: with a mismatched base direction, no penalty carries a
        // hyphen item even with a hyphenator present.
        #[cfg(not(feature = "text_layout_hyphenation"))]
        return; // dictionary feature not embedded in this build
        #[cfg(feature = "text_layout_hyphenation")]
        {
            use hyphenation::Load;
            let Ok(hyph) = Standard::from_embedded(hyphenation::Language::EnglishUS) else {
                return;
            };
            // Glyph-less test clusters PANIC inside find_all_hyphenation_breaks
            // (it indexes cluster.glyphs), so this test is doubly binding: with a
            // mismatched direction the hyphenator must never be CONSULTED - if
            // the gate regressed, the panic itself would fail the test before
            // the assertion does.
            let items: Vec<ShapedItem> = "hyphenation"
                .chars()
                .map(|ch| cl(&ch.to_string(), 12.0))
                .collect();
            let fonts: LoadedFonts<FontRef> = LoadedFonts::new();
            let c = UnifiedConstraints::default();
            let mismatched =
                convert_items_to_nodes(&items, Some(&hyph), &fonts, &c, BidiDirection::Rtl);
            let hyphen_penalties = mismatched
                .iter()
                .filter(|n| matches!(n, LayoutNode::Penalty { item: Some(_), .. }))
                .count();
            assert_eq!(
                hyphen_penalties, 0,
                "an LTR word in an RTL paragraph must not receive hyphen penalties"
            );
        }
    }
    #[test]
    fn left_aligned_paragraphs_are_never_justified() {
        // text-justify DEFAULTS to a non-none method (auto -> inter-word), so
        // the justification gate must key on the RESOLVED alignment, not on
        // text-justify alone. The old gate justified every non-last line of a
        // left-aligned paragraph.
        let nodes = nodes_for("aa bb cccc");
        let c = UnifiedConstraints {
            available_width: AvailableSpace::Definite(60.0),
            text_align: TextAlign::Left,
            text_justify: JustifyContent::InterWord,
            ..Default::default()
        };
        let breaks = find_optimal_breakpoints(&nodes, &c);
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        assert_eq!(line_count(&layout), 2, "breaks: {breaks:?}");
        assert_eq!(
            line_right(&layout, 0),
            53.0,
            "a left-aligned inner line keeps its natural width (was stretched to 60)"
        );
    }
    #[test]
    fn interior_hyphenation_opportunities_render_no_hyphen_and_add_no_width() {
        use super::LayoutNode;
        // Hand-built paragraph: "aa[-]bb cc" where [-] is a hyphenation
        // PENALTY (item = a 6px "-" cluster) that the break DOES NOT use at
        // width 80 (everything fits on one line). Knuth-Plass must neither
        // render that hyphen nor count its width.
        let aa = cl("aa", 24.0);
        let bb = cl("bb", 24.0);
        let sp = cl(" ", 5.0);
        let ccx = cl("cc", 24.0);
        let hyphen = cl("-", 6.0);
        let nodes = vec![
            LayoutNode::Box(aa, 24.0),
            LayoutNode::Penalty {
                penalty: 50.0,
                width: 6.0,
                item: Some(hyphen),
            },
            LayoutNode::Box(bb, 24.0),
            LayoutNode::Glue {
                item: sp,
                width: 5.0,
                stretch: 2.5,
                shrink: 1.6,
            },
            LayoutNode::Box(ccx, 24.0),
            LayoutNode::Penalty {
                penalty: -INFINITY_BADNESS,
                width: 0.0,
                item: None,
            },
        ];
        let c = UnifiedConstraints {
            available_width: AvailableSpace::Definite(120.0),
            ..Default::default()
        };
        let breaks = find_optimal_breakpoints(&nodes, &c);
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        assert_eq!(line_count(&layout), 1, "everything fits: breaks {breaks:?}");
        let text = line_text(&layout, 0);
        assert!(
            !text.contains('-'),
            "an UNUSED hyphenation opportunity must not render its hyphen: {text:?}"
        );
        assert_eq!(
            line_right(&layout, 0),
            24.0 + 24.0 + 5.0 + 24.0,
            "the unused penalty's 6px must not count into the line width"
        );
    }
    #[test]
    fn justification_of_a_space_less_line_does_not_divide_by_zero() {
        // The only space is the line-terminating one, which is trimmed before
        // the space count is taken: extra_per_space must stay 0, never NaN/inf.
        let nodes = nodes_for("aaaa aaaa");
        let c = UnifiedConstraints {
            available_width: AvailableSpace::Definite(60.0),
            text_align: TextAlign::Justify,
            text_justify: JustifyContent::InterWord,
            ..Default::default()
        };
        let breaks = find_optimal_breakpoints(&nodes, &c);
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        assert!(!layout.items.is_empty());
        for it in &layout.items {
            assert!(
                it.position.x.is_finite() && it.position.y.is_finite(),
                "no coordinate may be NaN or infinite: {:?}",
                it.position
            );
        }
        assert_eq!(
            line_right(&layout, 0),
            48.0,
            "nothing to stretch, no stretch"
        );
    }
    #[test]
    fn text_indent_offsets_only_the_first_line() {
        let nodes = nodes_for("aa bb cccc");
        let c = UnifiedConstraints {
            available_width: AvailableSpace::Definite(80.0),
            text_indent: 10.0,
            ..Default::default()
        };
        let breaks = find_optimal_breakpoints(&nodes, &c);
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        assert_eq!(line_count(&layout), 2, "breaks: {breaks:?}");
        assert_eq!(line_left(&layout, 0), 10.0, "first line is indented");
        assert_eq!(line_left(&layout, 1), 0.0, "later lines are not");
    }
    #[test]
    fn hanging_text_indent_offsets_every_line_but_the_first() {
        let nodes = nodes_for("aa bb cccc");
        let c = UnifiedConstraints {
            available_width: AvailableSpace::Definite(80.0),
            text_indent: 10.0,
            text_indent_hanging: true,
            ..Default::default()
        };
        let breaks = find_optimal_breakpoints(&nodes, &c);
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        assert_eq!(line_count(&layout), 2, "breaks: {breaks:?}");
        assert_eq!(line_left(&layout, 0), 0.0, "hanging: first line is flush");
        assert_eq!(line_left(&layout, 1), 10.0, "hanging: later lines indent");
    }
    #[test]
    fn every_line_trims_its_hanging_space() {
        // CSS Text 3 §4.1.2: line-terminating spaces hang; they are not measured
        // and are not justification opportunities.
        let nodes = nodes_for("aaaa aaaa aaaa");
        let c = definite(60.0);
        let breaks = find_optimal_breakpoints(&nodes, &c);
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        assert!(line_count(&layout) >= 2, "breaks: {breaks:?}");
        for line in 0..line_count(&layout) {
            let text = line_text(&layout, line);
            assert!(
                !text.ends_with(' '),
                "line {line} kept its hanging space: {text:?}"
            );
            assert!(!text.is_empty());
        }
    }
    #[test]
    fn unclipped_bounds_enclose_every_positioned_item() {
        let nodes = nodes_for("aa bb cccc");
        let c = UnifiedConstraints {
            available_width: AvailableSpace::Definite(60.0),
            line_height: LineHeight::Px(20.0),
            ..Default::default()
        };
        let breaks = find_optimal_breakpoints(&nodes, &c);
        let layout = position_lines_from_breaks(&nodes, &breaks, &[], &c);
        let b = layout.overflow.unclipped_bounds;
        assert!(
            layout.overflow.overflow_items.is_empty(),
            "nothing is dropped"
        );
        for it in &layout.items {
            assert!(
                it.position.x >= b.x - 0.01 && it.position.x <= b.x + b.width + 0.01,
                "item at {:?} escapes the recorded bounds {b:?}",
                it.position
            );
            assert!(it.position.y >= b.y - 0.01 && it.position.y <= b.y + b.height + 0.01);
        }
    }
    // =====================================================================
    // kp_layout: end-to-end smoke over extreme inputs
    // =====================================================================
    #[test]
    fn kp_layout_of_an_empty_paragraph_is_empty() {
        let layout = kp_layout(&[], &[], &definite(100.0), None, &no_fonts());
        assert!(layout.items.is_empty());
        assert!(layout.overflow.overflow_items.is_empty());
        assert_eq!(layout.overflow.unclipped_bounds.width, 0.0);
        assert_eq!(layout.overflow.unclipped_bounds.height, 0.0);
    }
    #[test]
    fn kp_layout_round_trips_the_paragraph_text_minus_hanging_spaces() {
        let items = items_of("aa bb cccc");
        let layout = kp_layout(&items, &[], &definite(60.0), None, &no_fonts());
        let round_tripped: String = (0..line_count(&layout))
            .map(|l| line_text(&layout, l))
            .collect::<Vec<_>>()
            .join(" ");
        assert_eq!(
            round_tripped, "aa bb cccc",
            "re-joining the lines with their trimmed break spaces must reproduce the source text"
        );
    }
    #[test]
    fn kp_layout_no_panic_smoke_over_extreme_inputs() {
        let inputs: Vec<Vec<ShapedItem>> = vec![
            Vec::new(),
            items_of(" "),
            items_of("   "),
            items_of("-"),
            items_of("a-b"),
            items_of("\u{200B}"),
            vec![object(0.0)],
            vec![object(f32::MAX)],
            vec![tab(0.0), tab(f32::INFINITY)],
            vec![hard_break(), hard_break()],
            vec![cl("a", -50.0), cl(" ", -5.0), cl("b", -50.0)],
            vec![cl("a", f32::MAX), cl(" ", f32::MAX), cl("b", f32::MAX)],
            vec![cl("x", f32::NAN), tab(f32::NAN), object(f32::NAN)],
        ];
        let constraints = [
            definite(0.0),
            definite(-10.0),
            definite(f32::NAN),
            definite(f32::MAX),
            UnifiedConstraints {
                available_width: AvailableSpace::MinContent,
                text_align: TextAlign::JustifyAll,
                text_justify: JustifyContent::Distribute,
                ..Default::default()
            },
            UnifiedConstraints {
                available_width: AvailableSpace::MaxContent,
                text_align: TextAlign::End,
                text_align_last: TextAlign::Center,
                text_indent: -25.0,
                ..Default::default()
            },
        ];
        for items in &inputs {
            for c in &constraints {
                let layout = kp_layout(items, &[], c, None, &no_fonts());
                assert!(
                    layout.items.len() <= items.len() + 2,
                    "no item may be duplicated: {} positioned from {} shaped",
                    layout.items.len(),
                    items.len()
                );
                assert!(layout.overflow.overflow_items.is_empty());
            }
        }
    }
}