Skip to content

Commit cb1bdf9

Browse files
committed
Fix catastrophic layout corruption when a keep-with-next run exceeds one page
EnforceKeepWithNext previously pulled the WHOLE preceding break-after:avoid chain to a child's page unconditionally, without checking whether the run fit there. For a long chain taller than one page, each subsequent chained sibling's own keep-with-next check re-fired against the now-stretched-out run, compounding OffsetTop shifts on the same earlier boxes without bound - found via a targeted stress test (60-member chain), reaching a box position around 8.6e11 and producing zero fragmentainers (FragmentEmitter couldn't bucket geometry that far out of range). Implements css-break-3 section 4.3's actual staged relaxation: trim the run from its front until what remains fits alongside the child on the target page, or leave the run in place entirely (RunDropped) if even its last member doesn't fit. Matches the BreakRelaxation enum's documented but previously unused RunTrimmed/RunDropped cases.
1 parent 23cd304 commit cb1bdf9

2 files changed

Lines changed: 120 additions & 6 deletions

File tree

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

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,22 @@ internal static void RelocateIfNeeded(RGraphics g, CssBox child)
156156
/// preceding sibling is exactly as "left behind" as in the ordinary case, and this method treats
157157
/// both identically).
158158
/// </remarks>
159+
/// <remarks>
160+
/// A second real bug found while investigating the fragmentation-engine-parity plan's R9 stage:
161+
/// an earlier version of this method always pulled the WHOLE preceding run to <paramref name="child"/>'s
162+
/// page, without checking whether the run (which can be arbitrarily tall - a long chain of
163+
/// <c>break-after:avoid</c> siblings) then fit there at all. This did not just mis-place content -
164+
/// it corrupted layout outright: when a run too tall for one page got pulled, its own later
165+
/// members remained just as likely to trigger their own keep-with-next check against the now
166+
/// artificially-stretched-out run, each firing its own unconditional pull and compounding
167+
/// <see cref="CssBox.OffsetTop"/> shifts on the same earlier boxes without bound (observed
168+
/// empirically reaching a box position around 8.6e11 for a 60-member chain on a short page). The
169+
/// fix is css-break-3 §4.3's actual staged relaxation: trim the run from its front (the earliest,
170+
/// least-important-to-keep members) until what remains actually fits the target page alongside
171+
/// <paramref name="child"/> (<see cref="BreakRelaxation.RunTrimmed"/>), or leave the run in place
172+
/// entirely if even its last member doesn't fit there (<see cref="BreakRelaxation.RunDropped"/>) -
173+
/// never pull a run that can't actually fit.
174+
/// </remarks>
159175
internal static void EnforceKeepWithNext(RGraphics g, CssBox child)
160176
{
161177
var container = child.HtmlContainer;
@@ -177,16 +193,30 @@ internal static void EnforceKeepWithNext(RGraphics g, CssBox child)
177193
var run = CollectPrecedingKeepWithNextRun(prevSibling);
178194
run.Add(prevSibling);
179195

180-
// Simplified for this stage: always pull the whole run to child's page, without checking
181-
// whether the run then fits alongside child there - the progressive relaxation ladder
182-
// (trim the run, drop it, leave the container behind) is a later plan stage's refinement.
183-
var delta = container.PageTopOf(childTopSlot) - run[0].EffectiveTop;
196+
// Trim from the front (earliest members) until what remains fits alongside child on the
197+
// target page - see the second remarks block above for why pulling an oversized run
198+
// unconditionally is not just suboptimal but actively corrupts layout.
199+
var childHeight = child.ActualBottom - child.EffectiveTop;
200+
var pageHeight = container.PageSize.Height;
201+
var start = 0;
202+
while (start < run.Count)
203+
{
204+
var runHeight = run[run.Count - 1].ActualBottom - run[start].EffectiveTop;
205+
if (runHeight + childHeight <= pageHeight)
206+
break;
207+
start++;
208+
}
209+
210+
if (start >= run.Count)
211+
return; // RunDropped - not even the run's last member fits alongside child; leave everything in place.
212+
213+
var delta = container.PageTopOf(childTopSlot) - run[start].EffectiveTop;
184214
if (delta <= 0)
185215
return; // Defensive - a positive shift is the only sensible outcome here.
186216

187-
foreach (var member in run)
217+
for (var i = start; i < run.Count; i++)
188218
{
189-
member.OffsetTop(delta);
219+
run[i].OffsetTop(delta);
190220
}
191221

192222
child.ResumeAt(null, null);
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
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 bug found while investigating the fragmentation-engine-parity plan's R9 stage: an
14+
/// earlier version of <see cref="TheArtOfDev.HtmlRenderer.Core.Fragmentation.BlockFragmentation.EnforceKeepWithNext"/>
15+
/// always pulled the WHOLE preceding <c>break-after:avoid</c>-chained run to a child's page without
16+
/// checking whether the run then fit there. For a long chain (taller than one page combined), this did
17+
/// not just mis-place content - it corrupted layout outright: each subsequent chained sibling's own
18+
/// keep-with-next check re-fired against the now artificially-stretched-out run, compounding
19+
/// <c>CssBox.OffsetTop</c> shifts on the same earlier boxes without bound (observed reaching a box
20+
/// position of roughly 8.6e11 for a 60-member chain on a short page, before the fix). The fix implements
21+
/// css-break-3 §4.3's actual staged relaxation - trim the run from its front until what remains fits, or
22+
/// drop it entirely rather than pulling something that can't fit.
23+
/// </summary>
24+
[TestClass]
25+
[DoNotParallelize]
26+
public sealed class StageR9OversizedKeepWithNextRunTest
27+
{
28+
private static HtmlContainerInt GetInternal(HtmlContainer wrapper)
29+
{
30+
var prop = typeof(HtmlContainer).GetProperty("HtmlContainerInt", BindingFlags.NonPublic | BindingFlags.Instance)!;
31+
return (HtmlContainerInt)prop.GetValue(wrapper)!;
32+
}
33+
34+
private static IEnumerable<string> AllWords(BoxFragment f)
35+
{
36+
foreach (var w in f.Words)
37+
if (!w.Word.IsLineBreak)
38+
yield return w.Word.Text;
39+
foreach (var c in f.Children)
40+
foreach (var w in AllWords(c))
41+
yield return w;
42+
}
43+
44+
[TestMethod]
45+
public async Task LongAvoidChainTallerThanOnePage_NeverCorruptsGeometry_AndLosesNothing()
46+
{
47+
using var wrapper = new HtmlContainer();
48+
var runMembers = string.Concat(Enumerable.Range(0, 60).Select(i =>
49+
$"<p style='margin:0; break-after: avoid;'>RunMember{i} filler filler filler filler filler</p>"));
50+
await wrapper.SetHtml(
51+
$"""
52+
<html><body>
53+
<div style="margin:0;">TopMarker</div>
54+
{runMembers}
55+
<p style="margin:0;">FinalParagraph</p>
56+
</body></html>
57+
""");
58+
59+
var container = GetInternal(wrapper);
60+
container.PageSize = new TheArtOfDev.HtmlRenderer.Adapters.Entities.RSize(595, 400);
61+
container.MarginTop = 20;
62+
wrapper.MaxSize = new SizeF(595, 0);
63+
64+
using var bitmap = new Bitmap(595, 20000);
65+
using var g = Graphics.FromImage(bitmap);
66+
wrapper.PerformLayout(g);
67+
68+
var tree = container.FragmentTree;
69+
Assert.IsNotNull(tree);
70+
71+
// The real bug produced an ActualSize.Height in the hundreds of billions and zero fragmentainers
72+
// (FragmentEmitter could not bucket geometry that far out of range) - a sane document is nowhere
73+
// close to that regardless of exact page count, which depends on font metrics.
74+
Assert.IsLessThan(100_000.0, wrapper.ActualSize.Height, "document height must stay sane - not blow up from compounding OffsetTop shifts");
75+
Assert.IsGreaterThan(0, tree.Fragmentainers.Count);
76+
77+
var allWords = tree.Fragmentainers.SelectMany(f => AllWords(f.Root)).ToList();
78+
var expected = Enumerable.Range(0, 60).Select(i => $"RunMember{i}").Append("FinalParagraph").Append("TopMarker");
79+
foreach (var e in expected)
80+
{
81+
Assert.AreEqual(1, allWords.Count(w => w == e), $"'{e}' must appear exactly once - not lost or duplicated");
82+
}
83+
}
84+
}

0 commit comments

Comments
 (0)