Skip to content

Commit 380a207

Browse files
committed
R5/R6: neither needed new resumption machinery - fixed real bugs instead
Investigated the plan's R5 (inline resumption via line-index InlineBreakToken) and R6 (widows as a driver-level rewind) before building either. Conclusion: CreateLineBoxes already computes a whole paragraph's lines in one unbounded, side-effect-free, idempotent call - there is never a point where a LATER pass would reveal information the SAME-shot correction didn't already have, which is the entire reason PeachPDF's resumption/rewind machinery exists. Building BreakToken/pass machinery for inline flow would have been solving a problem this architecture doesn't have (same conclusion as R2's finding for ordinary block overflow). What the investigation found instead: a real, confirmed bug in the EXISTING same-shot algorithm. The old InlineFragmentation.ApplyLineBreaking shifted lines incrementally as it walked them, driven by "did this line straddle a page boundary". Once a shift happened to land a run in perfect page-boundary alignment (common with uniform line heights), no line ever straddled again for the rest of the paragraph - so widows was silently never re-checked for any later page transition. Confirmed via a paragraph spanning 60 pages: its final page ended with 1 line despite widows:3, and nothing corrected it. Rewrote ApplyLineBreaking as two phases: decide every break point from each line's own NATURAL (never-shifted) position (immune to the alignment blind spot, and lets widows cascade backward across more than one earlier break by removing entries from a decided break list, rather than needing to undo a shift already applied to specific lines), then apply the decided breaks as shifts in one separate pass. Also handles a case the old code never covered either: a box's own first line not fitting the room left on its starting page. Fixing this surfaced a second real bug in R4's own EnforceKeepWithNext: it read CssBox.Location.Y to determine which page an already-laid-out box's content starts on, but for an inline-only box, Location is committed once before content layout runs and InlineFragmentation never updates it - even though it can move the box's one-and-only line to an entirely different page. A single-line heading whose own line got pushed to the next page still reported its OLD page via Location.Y, so keep-with-next silently compared against stale geometry. Added CssBox.EffectiveTop (the first line's actual top for inline-only boxes, Location.Y otherwise) and switched both RelocateIfNeeded and EnforceKeepWithNext to use it. New tests confirm both the fixable case (a long paragraph correctly pulls lines back across more than one earlier page to satisfy widows when room allows) and the honest unsatisfiable case (widows is left unsatisfied rather than forcing an overflowing page, with word-count conservation and per-page height checked directly). StageR4KeepWithNextTest was also made self-calibrating (searches for the exact boundary filler count rather than a hardcoded one) after the InlineFragmentation rewrite shifted where that boundary falls by one - a hardcoded magic number turned out to be fragile to unrelated, still-correct changes. Full regression suite (41 IntegrationTest + 16 PdfSharp tests) passes.
1 parent d8c4c00 commit 380a207

5 files changed

Lines changed: 278 additions & 57 deletions

File tree

‎Source/HtmlRenderer/Core/Dom/CssBox.cs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,18 @@ internal List<CssLineBox> LineBoxes
404404
get { return _lineBoxes; }
405405
}
406406

407+
/// <summary>
408+
/// This box's actual rendered top, for page-index comparisons against an already-laid-out box -
409+
/// <see cref="CssBoxProperties.Location"/>'s Y for a block container, but the first line's actual
410+
/// top for an inline-only box. <c>Location</c> is committed once, before content layout runs, and
411+
/// <see cref="Fragmentation.InlineFragmentation.ApplyLineBreaking"/> never updates it even though
412+
/// it can move the box's one-and-only line (or first of several) to an entirely different page -
413+
/// a single-line paragraph pushed whole onto the next page by orphans/widows is the case that
414+
/// actually surfaces this: <c>Location.Y</c> stays wherever the box was originally positioned,
415+
/// silently wrong for any caller using it to ask "which page does this box's content start on."
416+
/// </summary>
417+
internal double EffectiveTop => _lineBoxes.Count > 0 ? _lineBoxes[0].LineTop : Location.Y;
418+
407419
/// <summary>
408420
/// Gets the linebox(es) that contains words of this box (if inline)
409421
/// </summary>

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ internal static void RelocateIfNeeded(RGraphics g, CssBox child)
111111
if (container == null || !container.HasRealPageGrid || child.IsOutOfFlow)
112112
return;
113113

114-
var top = child.Location.Y;
114+
var top = child.EffectiveTop;
115115
var bottom = child.ActualBottom;
116116
if (bottom <= top)
117117
return;
@@ -169,8 +169,8 @@ internal static void EnforceKeepWithNext(RGraphics g, CssBox child)
169169
if (!BreakValues.AvoidsBreak(prevSibling.BreakAfter) && !BreakValues.AvoidsBreak(child.BreakBefore))
170170
return;
171171

172-
var prevBottomSlot = container.PageIndexOf(Math.Max(prevSibling.Location.Y, prevSibling.ActualBottom - 0.01));
173-
var childTopSlot = container.PageIndexOf(child.Location.Y);
172+
var prevBottomSlot = container.PageIndexOf(Math.Max(prevSibling.EffectiveTop, prevSibling.ActualBottom - 0.01));
173+
var childTopSlot = container.PageIndexOf(child.EffectiveTop);
174174
if (childTopSlot <= prevBottomSlot)
175175
return; // No break actually falls between them - nothing to enforce.
176176

@@ -180,7 +180,7 @@ internal static void EnforceKeepWithNext(RGraphics g, CssBox child)
180180
// Simplified for this stage: always pull the whole run to child's page, without checking
181181
// whether the run then fits alongside child there - the progressive relaxation ladder
182182
// (trim the run, drop it, leave the container behind) is a later plan stage's refinement.
183-
var delta = container.PageTopOf(childTopSlot) - run[0].Location.Y;
183+
var delta = container.PageTopOf(childTopSlot) - run[0].EffectiveTop;
184184
if (delta <= 0)
185185
return; // Defensive - a positive shift is the only sensible outcome here.
186186

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

Lines changed: 94 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
using System;
2+
using System.Collections.Generic;
13
using TheArtOfDev.HtmlRenderer.Core.Dom;
24

35
namespace TheArtOfDev.HtmlRenderer.Core.Fragmentation
@@ -12,14 +14,30 @@ namespace TheArtOfDev.HtmlRenderer.Core.Fragmentation
1214
/// </summary>
1315
internal static class InlineFragmentation
1416
{
15-
private const double Epsilon = 0.01;
16-
1717
/// <summary>
1818
/// Called right after <see cref="CssLayoutEngine.CreateLineBoxes"/> finishes for
19-
/// <paramref name="blockBox"/>: pushes any line that straddles a page boundary - and, honoring
20-
/// <c>orphans</c>/<c>widows</c>, the lines around it - down to the next page's content top, then
21-
/// updates <see cref="CssBoxProperties.ActualBottom"/> to match.
19+
/// <paramref name="blockBox"/>: pushes any line that would land on a later page than its run's
20+
/// break down to that page's content top - and, honoring <c>orphans</c>/<c>widows</c>, the lines
21+
/// around it - then updates <see cref="CssBoxProperties.ActualBottom"/> to match.
2222
/// </summary>
23+
/// <remarks>
24+
/// Two phases, deliberately kept separate. Phase 1 decides every break index using each line's
25+
/// own NATURAL (never-shifted) position - a run's total height is preserved under a uniform
26+
/// shift, so "does a candidate run fit on one page" (and therefore where the next break falls)
27+
/// can be decided without knowing where the run will actually land. This is what lets widows
28+
/// cascade backward across more than one earlier break when needed (by removing entries from the
29+
/// decided break list) without having to undo a shift already applied to specific lines - an
30+
/// earlier single-pass version of this method shifted lines incrementally as it went, which
31+
/// couldn't cleanly support that. It also had a subtler failure mode worth recording: once a
32+
/// shift happens to land a run's lines in perfect page-boundary alignment (uniform line heights
33+
/// make this common), no line ever straddles again, so a single-pass method driven purely by "did
34+
/// this line straddle" silently stopped checking orphans/widows for every later page transition -
35+
/// found via a paragraph long enough to span dozens of pages, whose final page ended up with
36+
/// fewer lines than <c>widows</c> required and was never corrected. Phase 1's height-cumulative
37+
/// natural-position test has no such blind spot, since it never depends on whether a straddle was
38+
/// observed. Phase 2 applies the decided breaks as cumulative shifts to the real line boxes, in
39+
/// one forward pass - no decisions left to make there, just arithmetic.
40+
/// </remarks>
2341
internal static void ApplyLineBreaking(CssBox blockBox)
2442
{
2543
var container = blockBox.HtmlContainer;
@@ -32,57 +50,93 @@ internal static void ApplyLineBreaking(CssBox blockBox)
3250

3351
var orphans = blockBox.ActualOrphans;
3452
var widows = blockBox.ActualWidows;
35-
36-
var delta = 0.0;
37-
// Index of the first line of the current "page run" within this box - what orphans/widows
38-
// are counted against.
39-
var pageStart = 0;
40-
41-
for (var i = 0; i < lines.Count; i++)
53+
var pageHeight = container.PageSize.Height;
54+
55+
// The first run starts wherever CreateLineBoxes naturally placed line 0 - not necessarily a
56+
// page's top (this box may start partway down a page, after preceding sibling content) - so
57+
// its capacity is only whatever room remains on that page, not a full page height the way
58+
// every later run (which always starts fresh at a page's top, by construction) gets.
59+
var firstPageIndex = container.PageIndexOf(lines[0].LineTop);
60+
var firstRunCapacity = container.PageBottomOf(firstPageIndex) - lines[0].LineTop;
61+
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)
4272
{
43-
if (delta != 0)
44-
lines[i].ShiftLine(delta);
73+
firstPageIndex++;
74+
firstRunCapacity = pageHeight;
75+
}
4576

46-
var top = lines[i].LineTop;
47-
var bottom = lines[i].LineBottom;
48-
if (bottom <= top)
49-
continue;
77+
var breaks = new List<int> { 0 };
5078

51-
// Bottom-edge convention: a bottom landing exactly on a boundary belongs to the band above it.
52-
if (container.PageIndexOf(System.Math.Max(top, bottom - Epsilon)) <= container.PageIndexOf(top))
53-
continue; // this line doesn't straddle - nothing to do
79+
for (var i = 1; i < lines.Count; i++)
80+
{
81+
var runStart = breaks[breaks.Count - 1];
82+
var capacity = runStart == 0 ? firstRunCapacity : pageHeight;
83+
if (lines[i].LineBottom - lines[runStart].LineTop <= capacity)
84+
continue; // line i still fits in the run that started at runStart
5485

55-
var breakIndex = i;
86+
var linesBefore = i - runStart;
87+
if (linesBefore > 0 && linesBefore < orphans && breaks.Count > 1)
88+
{
89+
// Too few lines to justify breaking here - the attempted run merges into the
90+
// previous page's run instead of leaving a near-empty fragment behind. Re-test this
91+
// same line against the now-earlier run start (cascades further back if needed).
92+
breaks.RemoveAt(breaks.Count - 1);
93+
i--;
94+
}
95+
else
96+
{
97+
breaks.Add(i);
98+
}
99+
}
56100

57-
// Orphans: at least `orphans` lines must remain on the page before the break.
58-
var linesBefore = breakIndex - pageStart;
59-
if (linesBefore > 0 && linesBefore < orphans)
60-
breakIndex = pageStart;
101+
// Widows: the run after the LAST break must have at least `widows` lines - if not, merge
102+
// break points backward (as many as needed) until it does, or until only one run is left, or
103+
// until merging further would make the run taller than a page can hold - honoring widows by
104+
// creating a run that can never fit isn't honoring it, it's trading one violation for a worse
105+
// one, so this is where the relaxation gives up rather than forcing it (css-break-3 §4.3's
106+
// own "some constraints can't always be satisfied" philosophy).
107+
while (breaks.Count > 1 && lines.Count - breaks[breaks.Count - 1] < widows)
108+
{
109+
var candidateStart = breaks[breaks.Count - 2];
110+
var candidateCapacity = candidateStart == 0 ? firstRunCapacity : pageHeight;
111+
if (lines[lines.Count - 1].LineBottom - lines[candidateStart].LineTop > candidateCapacity)
112+
break;
61113

62-
// Widows: at least `widows` lines must remain after the break, in total for this box.
63-
var linesAfter = lines.Count - breakIndex;
64-
if (linesAfter > 0 && linesAfter < widows && lines.Count - widows >= pageStart)
65-
breakIndex = System.Math.Min(breakIndex, lines.Count - widows);
114+
breaks.RemoveAt(breaks.Count - 1);
115+
}
66116

67-
var target = container.PageTopOf(container.PageIndexOf(lines[breakIndex].LineTop) + 1);
68-
var shift = target - lines[breakIndex].LineTop;
117+
// 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;
121+
var breakOrdinal = 0;
69122

70-
if (shift > 0)
123+
for (var i = 0; i < lines.Count; i++)
124+
{
125+
if (breakOrdinal + 1 < breaks.Count && i == breaks[breakOrdinal + 1])
71126
{
72-
for (var j = breakIndex; j <= i; j++)
73-
{
74-
lines[j].ShiftLine(shift);
75-
}
76-
delta += shift;
127+
breakOrdinal++;
128+
var target = container.PageTopOf(firstPageIndex + breakOrdinal);
129+
delta = target - lines[i].LineTop; // lines[i] not yet shifted this pass
77130
}
78131

79-
pageStart = breakIndex;
132+
if (delta != 0)
133+
lines[i].ShiftLine(delta);
80134
}
81135

82136
var maxBottom = 0.0;
83137
foreach (var line in lines)
84138
{
85-
maxBottom = System.Math.Max(maxBottom, line.LineBottom);
139+
maxBottom = Math.Max(maxBottom, line.LineBottom);
86140
}
87141

88142
if (maxBottom > 0)

‎Source/Test/HtmlRenderer.IntegrationTest/StageR4KeepWithNextTest.cs‎

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,6 @@ namespace TheArtOfDev.HtmlRenderer.IntegrationTest;
2727
[DoNotParallelize]
2828
public sealed class StageR4KeepWithNextTest
2929
{
30-
private const int FillerCount = 39;
31-
3230
private static HtmlContainerInt GetInternal(HtmlContainer wrapper)
3331
{
3432
var prop = typeof(HtmlContainer).GetProperty("HtmlContainerInt", BindingFlags.NonPublic | BindingFlags.Instance)!;
@@ -67,33 +65,55 @@ static void Collect(BoxFragment f, List<string> into)
6765
}
6866
}
6967

70-
private static string Filler() =>
71-
string.Concat(Enumerable.Repeat("<p style='margin:0;'>filler line of text</p>", FillerCount));
68+
private static string Filler(int count) =>
69+
string.Concat(Enumerable.Repeat("<p style='margin:0;'>filler line of text</p>", count));
7270

7371
// WinForms reports media type "screen", not "print" - the UA stylesheet's h1-h6 { break-after: avoid }
7472
// rule lives under @media print (see PdfSharpAdapter vs RAdapter.DefaultMediaType) and never applies
7573
// to this IntegrationTest project's WinForms-based HtmlContainer. Set it explicitly rather than
7674
// relying on the UA default.
7775
private const string HeadingStyle = "margin:0; break-after: avoid;";
7876

79-
[TestMethod]
80-
public async Task Precondition_HeadingAloneFitsOnPageZero()
77+
/// <summary>
78+
/// Finds, by direct search rather than a hardcoded magic number, a filler count where the heading
79+
/// fits alone on page 0 but heading+paragraph together do not - the exact boundary this stage's real
80+
/// test needs. Hardcoding the count made this test fragile to unrelated, still-correct changes
81+
/// elsewhere in the pagination arithmetic (this happened once already, when InlineFragmentation's
82+
/// algorithm was rewritten for an unrelated widows bug and shifted the boundary by one filler).
83+
/// </summary>
84+
private static async Task<int> FindBoundaryFillerCountAsync()
8185
{
82-
// Establishes the calibration this stage's real test depends on: with FillerCount fillers and no
83-
// trailing paragraph, the heading fits on the same page as the filler (a stray trailing blank
84-
// fragmentainer past it is an unrelated pre-existing quirk, not what this checks).
85-
var tree = await LayoutAsync($"{Filler()}<h4 style='{HeadingStyle}'>Section heading</h4>");
86-
StringAssert.Contains(AllText(tree.Fragmentainers[0].Root), "Section heading");
86+
for (var count = 20; count < 80; count++)
87+
{
88+
var headingAlone = await LayoutAsync($"{Filler(count)}<h4 style='{HeadingStyle}'>Section heading</h4>");
89+
var headingFitsAlone = StringContains(AllText(headingAlone.Fragmentainers[0].Root), "Section heading");
90+
if (!headingFitsAlone)
91+
continue;
92+
93+
var withParagraph = await LayoutAsync(
94+
$"{Filler(count)}<h4 style='{HeadingStyle}'>Section heading</h4><p style='margin:0;'>Paragraph right after the heading.</p>");
95+
var bothFitOnPageZero = withParagraph.Fragmentainers.Count >= 1
96+
&& StringContains(AllText(withParagraph.Fragmentainers[0].Root), "Paragraph right after the heading.");
97+
if (!bothFitOnPageZero)
98+
return count; // heading alone fits; heading+paragraph together doesn't - the boundary.
99+
}
100+
101+
Assert.Fail("could not find a filler count where the heading fits alone but not with its paragraph");
102+
return -1;
87103
}
88104

105+
private static bool StringContains(string haystack, string needle) => haystack.Contains(needle);
106+
89107
[TestMethod]
90108
public async Task HeadingAndParagraph_LandOnTheSamePage_NotStranded()
91109
{
110+
var count = await FindBoundaryFillerCountAsync();
111+
92112
var tree = await LayoutAsync(
93-
$"{Filler()}<h4 style='{HeadingStyle}'>Section heading</h4><p style='margin:0;'>Paragraph right after the heading.</p>");
113+
$"{Filler(count)}<h4 style='{HeadingStyle}'>Section heading</h4><p style='margin:0;'>Paragraph right after the heading.</p>");
94114

95115
// Page 0's own text must NOT contain the heading - it should have been pulled forward to join
96-
// the paragraph, not left stranded where the precondition test shows it would otherwise fit.
116+
// the paragraph, not left stranded where the boundary search shows it would otherwise fit alone.
97117
var pageZeroText = AllText(tree.Fragmentainers[0].Root);
98118
StringAssert.DoesNotMatch(pageZeroText, new System.Text.RegularExpressions.Regex("Section heading"));
99119

0 commit comments

Comments
 (0)