Skip to content

Commit 7b6f874

Browse files
committed
Fix orphans never enforced on a paragraph's first page-fragment
InlineFragmentation.ApplyLineBreaking's orphans merge-back correction only ever ran once at least one earlier break already existed (breaks.Count > 1), which can never be true while still deciding the first run - so a paragraph starting close enough to a page's bottom that fewer than `orphans` lines fit there was left with a too-small stranded first fragment. Confirmed by temporarily reverting the fix: it reliably reproduced a 1-line first page against orphans:2 at several filler counts. Generalizes the existing "first line taller than the remaining room" push (now folded into the same check, since 0 fitting lines is just the orphans violation that can never be waived) - if fewer than `orphans` lines fit in the room remaining on the starting page, the whole paragraph now moves to start fresh on the next page instead.
1 parent 9bd7663 commit 7b6f874

2 files changed

Lines changed: 112 additions & 13 deletions

File tree

‎Source/HtmlRenderer/Core/Fragmentation/InlineFragmentation.cs‎

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -59,16 +59,27 @@ internal static void ApplyLineBreaking(CssBox blockBox)
5959
var firstPageIndex = container.PageIndexOf(lines[0].LineTop);
6060
var firstRunCapacity = container.PageBottomOf(firstPageIndex) - lines[0].LineTop;
6161

62-
// The box's own first line can itself fail to fit the room remaining on the page it starts
63-
// on (this box may start very close to a page's bottom) - every OTHER run always starts
64-
// fresh at a full page's top, where this can't happen unless a single line is individually
65-
// taller than a whole page (an unrelated, unhandled-here monolithic-overflow concern the
66-
// main loop's ordinary straddle test still catches the same way it always did). The main
67-
// loop below only ever compares a later line's cumulative height back to line 0's position -
68-
// it never re-examines whether line 0 itself already overflowed there, so this has to be
69-
// decided first and folded into where the first run is considered to begin.
70-
var firstLineNeedsOwnPage = lines[0].LineBottom - lines[0].LineTop > firstRunCapacity;
71-
if (firstLineNeedsOwnPage)
62+
// How many lines actually fit in the room remaining on the page this box starts on - a
63+
// run's total height measured from line 0 is invariant under a uniform shift (see the
64+
// two-phase remark above), so this natural-position count is valid regardless of where the
65+
// run ends up landing.
66+
var firstRunLineCount = 0;
67+
while (firstRunLineCount < lines.Count && lines[firstRunLineCount].LineBottom - lines[0].LineTop <= firstRunCapacity)
68+
firstRunLineCount++;
69+
70+
// Orphans (css-break-3 §5.4) applies to the box's very first run exactly like every later
71+
// one: a paragraph starting close enough to a page's bottom that fewer than `orphans` lines
72+
// fit there must move in its ENTIRETY to the next page, not leave a too-small first fragment
73+
// behind. The main loop below cannot fix this on its own - its merge-back correction only
74+
// ever runs once at least one earlier break already exists (`breaks.Count > 1`), which is
75+
// never true while still deciding the first run, so an otherwise-identical violation at the
76+
// very start of a paragraph was silently exempt. Folding it into where the first run begins
77+
// (the same mechanism already used for a single first line taller than the remaining room)
78+
// fixes it without needing a special case in the main loop. Subsumes that single-line case
79+
// too - it is just the `orphans` violation that can never be waived (0 lines fitting is
80+
// always fewer than any orphans value of at least 1).
81+
var firstRunMovedToFreshPage = firstRunLineCount < lines.Count && firstRunLineCount < orphans;
82+
if (firstRunMovedToFreshPage)
7283
{
7384
firstPageIndex++;
7485
firstRunCapacity = pageHeight;
@@ -115,9 +126,9 @@ internal static void ApplyLineBreaking(CssBox blockBox)
115126
}
116127

117128
// Phase 2: apply the decided breaks as cumulative shifts, in one forward pass. The first
118-
// run's own delta is seeded up front (zero unless firstLineNeedsOwnPage moved it) since the
119-
// loop below only assigns a fresh delta when it crosses breaks[1] onward.
120-
var delta = firstLineNeedsOwnPage ? container.PageTopOf(firstPageIndex) - lines[0].LineTop : 0.0;
129+
// run's own delta is seeded up front (zero unless firstRunMovedToFreshPage moved it) since
130+
// the loop below only assigns a fresh delta when it crosses breaks[1] onward.
131+
var delta = firstRunMovedToFreshPage ? container.PageTopOf(firstPageIndex) - lines[0].LineTop : 0.0;
121132
var breakOrdinal = 0;
122133

123134
for (var i = 0; i < lines.Count; i++)
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
using System.Collections.Generic;
2+
using System.Drawing;
3+
using System.Linq;
4+
using System.Reflection;
5+
using Microsoft.VisualStudio.TestTools.UnitTesting;
6+
using TheArtOfDev.HtmlRenderer.Core;
7+
using TheArtOfDev.HtmlRenderer.Core.Fragments;
8+
using TheArtOfDev.HtmlRenderer.WinForms;
9+
10+
namespace TheArtOfDev.HtmlRenderer.IntegrationTest;
11+
12+
/// <summary>
13+
/// Verifies a real, previously-undocumented gap found while auditing this port's fragmentation engine
14+
/// against PeachPDF a second time (the first audit produced the R0-R10 plan; this is a later, separate
15+
/// pass over what remained): <c>InlineFragmentation.ApplyLineBreaking</c>'s orphans merge-back correction
16+
/// only ever ran once at least one earlier break already existed (<c>breaks.Count > 1</c>), which can
17+
/// never be true while still deciding a paragraph's very FIRST run - so a paragraph starting close enough
18+
/// to a page's bottom that fewer than <c>orphans</c> lines fit there was left with a too-small stranded
19+
/// first fragment, uncorrected. Confirmed by temporarily reverting the fix and re-running this exact test:
20+
/// it reliably reproduced a 1-line first page against <c>orphans:2</c> at several filler counts (13, 28,
21+
/// 43, 58 - the same ~15-count period the page-height/line-height ratio produces).
22+
/// </summary>
23+
[TestClass]
24+
[DoNotParallelize]
25+
public sealed class OrphansOnFirstRunTest
26+
{
27+
private static HtmlContainerInt GetInternal(HtmlContainer wrapper)
28+
{
29+
var prop = typeof(HtmlContainer).GetProperty("HtmlContainerInt", BindingFlags.NonPublic | BindingFlags.Instance)!;
30+
return (HtmlContainerInt)prop.GetValue(wrapper)!;
31+
}
32+
33+
private static IEnumerable<(string Text, double Top)> AllTargetWords(BoxFragment f)
34+
{
35+
foreach (var w in f.Words)
36+
if (!w.Word.IsLineBreak && w.Word.Text.StartsWith("TargetLine"))
37+
yield return (w.Word.Text, w.Rect.Top);
38+
foreach (var c in f.Children)
39+
foreach (var x in AllTargetWords(c))
40+
yield return x;
41+
}
42+
43+
[TestMethod]
44+
public async Task ParagraphStartingNearPageBottom_NeverStrandsFewerThanOrphansLines()
45+
{
46+
// Sweep filler counts rather than hardcoding one - this is a "just barely fits" calibration
47+
// (see this session's own established testing lesson), and the exact boundary depends on
48+
// font-metric arithmetic other changes are expected to keep touching.
49+
for (var fillerCount = 1; fillerCount < 60; fillerCount++)
50+
{
51+
using var wrapper = new HtmlContainer();
52+
var filler = string.Concat(Enumerable.Repeat("<p style='margin:0;'>filler line</p>", fillerCount));
53+
await wrapper.SetHtml(
54+
$"""
55+
<html><body>
56+
{filler}
57+
<p style="margin:0; orphans:2;">TargetLineOne TargetLineTwo TargetLineThree TargetLineFour TargetLineFive TargetLineSix TargetLineSeven TargetLineEight TargetLineNine TargetLineTen</p>
58+
</body></html>
59+
""");
60+
61+
var container = GetInternal(wrapper);
62+
container.PageSize = new TheArtOfDev.HtmlRenderer.Adapters.Entities.RSize(200, 300);
63+
container.MarginTop = 0;
64+
wrapper.MaxSize = new SizeF(200, 0);
65+
66+
using var bitmap = new Bitmap(200, 20000);
67+
using var g = Graphics.FromImage(bitmap);
68+
wrapper.PerformLayout(g);
69+
70+
var tree = container.FragmentTree;
71+
Assert.IsNotNull(tree);
72+
73+
var wordInfo = new List<(string Text, int Page, double Top)>();
74+
for (var pi = 0; pi < tree.Fragmentainers.Count; pi++)
75+
foreach (var w in AllTargetWords(tree.Fragmentainers[pi].Root))
76+
wordInfo.Add((w.Text, pi, System.Math.Round(w.Top, 1)));
77+
78+
if (wordInfo.Count == 0)
79+
continue; // paragraph didn't appear in this bitmap height at this filler count - try the next
80+
81+
var firstPage = wordInfo[0].Page;
82+
var linesOnFirstPage = wordInfo.Where(w => w.Page == firstPage).Select(w => w.Top).Distinct().Count();
83+
84+
Assert.IsGreaterThanOrEqualTo(2, linesOnFirstPage,
85+
$"at fillerCount={fillerCount}, the paragraph's first page-fragment kept only {linesOnFirstPage} line(s), fewer than orphans:2 requires");
86+
}
87+
}
88+
}

0 commit comments

Comments
 (0)