Skip to content

Commit 2015821

Browse files
committed
Fix container-left-behind: a moved box's ancestor now follows it up
css-break-3 3.1's break-point propagation was only ever applied to forced breaks (TryGetForcedBreakTarget's own "no previous sibling" check), never to RelocateIfNeeded's relocation, EnforceKeepWithNext's run-pull, or InlineFragmentation's own orphans-driven whole-box push. A box moved by any of these while it's its parent's first in-flow child left the parent spanning from its original page to the moved content's new one - its own background/border rendered as a stub-then-continuation (e.g. a card/panel div wrapping a single table, or a section wrapping a heading+paragraph pair). Confirmed via three separate reproductions, each failing without the fix and passing with it. New BlockFragmentation.PropagateContainerRelocation(movedBox, delta): climbs the first-in-flow-child chain, shifting each such ancestor's own top by the same delta. Deliberately touches only Location, never ActualBottom - a container's bottom is already correctly, independently computed from its last child via ordinary block flow, so no "does the whole group move together" bookkeeping is needed, unlike an earlier, more complex version of this fix that tried (and got wrong) recomputing both edges from a moved group's combined extent. Investigating the EnforceKeepWithNext case surfaced a second, more fundamental bug along the way: CssBox.OffsetTop kept the box's own Rectangles dictionary in sync with a shift but never the corresponding CssLineBox.Rectangles entry (a separate dictionary, keyed the other way, that LineTop/LineBottom - and therefore EffectiveTop for any inline-only box - read from). Location.Y was correctly updated while EffectiveTop silently kept reporting the pre-shift position. Fixed by having OffsetTop update both sides together, matching what CssLineBox.ShiftLine already does when a line-level shift initiates the move instead.
1 parent 4f7ffcd commit 2015821

6 files changed

Lines changed: 366 additions & 4 deletions

File tree

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

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1514,6 +1514,19 @@ private double MarginBottomCollapse()
15141514
/// Deeply offsets the top of the box and its contents
15151515
/// </summary>
15161516
/// <param name="amount"></param>
1517+
/// <remarks>
1518+
/// A real gap found while auditing this port's fragmentation engine against PeachPDF a second
1519+
/// time: this box's own <see cref="Rectangles"/> entry for a line was kept in sync, but the
1520+
/// line's OWN mirror of the same value (<see cref="CssLineBox.Rectangles"/>, keyed the other way
1521+
/// around) was not - the two are separate dictionaries updated by separate call sites
1522+
/// (<see cref="CssLineBox.ShiftLine"/> keeps both in sync when a line-level shift initiates the
1523+
/// move; this method didn't when a box-level shift does). <see cref="CssLineBox.LineTop"/>/
1524+
/// <c>LineBottom</c> - and therefore <see cref="EffectiveTop"/> for any inline-only box, since it
1525+
/// reads them - went stale after this method ran, even though <see cref="Location"/> (this
1526+
/// method's own last statement) was correctly updated. Confirmed by directly inspecting both
1527+
/// dictionaries after a real <c>EnforceKeepWithNext</c> run-shift: <c>Location.Y</c> reflected the
1528+
/// new position while <c>EffectiveTop</c> still reported the old one.
1529+
/// </remarks>
15171530
internal void OffsetTop(double amount)
15181531
{
15191532
List<CssLineBox> lines = new List<CssLineBox>();
@@ -1523,7 +1536,9 @@ internal void OffsetTop(double amount)
15231536
foreach (CssLineBox line in lines)
15241537
{
15251538
RRect r = Rectangles[line];
1526-
Rectangles[line] = new RRect(r.X, r.Y + amount, r.Width, r.Height);
1539+
var shifted = new RRect(r.X, r.Y + amount, r.Width, r.Height);
1540+
Rectangles[line] = shifted;
1541+
line.Rectangles[this] = shifted;
15271542
}
15281543

15291544
foreach (CssRect word in Words)

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

Lines changed: 68 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.Collections.Generic;
33
using TheArtOfDev.HtmlRenderer.Adapters;
4+
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
45
using TheArtOfDev.HtmlRenderer.Core.Dom;
56
using TheArtOfDev.HtmlRenderer.Core.Utils;
67

@@ -105,6 +106,17 @@ internal static bool TryGetForcedBreakTarget(CssBox box, CssBox prevSibling, dou
105106
/// the real page boundaries at the new position, rather than blindly carrying whatever decision
106107
/// they made at the old one.
107108
/// </remarks>
109+
/// <remarks>
110+
/// A real gap found while auditing this port's fragmentation engine against PeachPDF a second
111+
/// time: css-break-3 §3.1's break-point propagation was only ever applied to forced breaks (see
112+
/// <see cref="TryGetForcedBreakTarget"/>'s own remark), never to this kind of relocation. A child
113+
/// moved by this method while it's its parent's first in-flow child - a plain wrapper with no
114+
/// content before it - left the parent spanning from its original page to the child's new one, its
115+
/// own background/border painted as a stub-then-continuation for no reason a CSS author would
116+
/// expect (e.g. a card/panel div wrapping a single table or figure). <see cref="PropagateContainerRelocation"/>
117+
/// fixes this by climbing the first-in-flow-child chain and shifting each such ancestor's own top
118+
/// by the same delta, rather than leaving it behind.
119+
/// </remarks>
108120
internal static void RelocateIfNeeded(RGraphics g, CssBox child)
109121
{
110122
var container = child.HtmlContainer;
@@ -132,6 +144,8 @@ internal static void RelocateIfNeeded(RGraphics g, CssBox child)
132144
var target = container.PageTopOf(topSlot + 1);
133145
child.ResumeAt(null, target);
134146
child.PerformLayout(g);
147+
148+
PropagateContainerRelocation(child, child.EffectiveTop - top);
135149
}
136150

137151
/// <summary>
@@ -185,7 +199,9 @@ internal static void EnforceKeepWithNext(RGraphics g, CssBox child)
185199
return;
186200

187201
var prevBottomSlot = container.PageIndexOf(Math.Max(prevSibling.EffectiveTop, prevSibling.ActualBottom - 0.01));
188-
var childTopSlot = container.PageIndexOf(child.EffectiveTop);
202+
var childTopBeforeRelayout = child.EffectiveTop;
203+
var childBottomBeforeRelayout = child.ActualBottom;
204+
var childTopSlot = container.PageIndexOf(childTopBeforeRelayout);
189205
if (childTopSlot <= prevBottomSlot)
190206
return; // No break actually falls between them - nothing to enforce.
191207

@@ -195,7 +211,7 @@ internal static void EnforceKeepWithNext(RGraphics g, CssBox child)
195211
// Trim from the front (earliest members) until what remains fits alongside child on the
196212
// target page - see the second remarks block above for why pulling an oversized run
197213
// unconditionally is not just suboptimal but actively corrupts layout.
198-
var childHeight = child.ActualBottom - child.EffectiveTop;
214+
var childHeight = childBottomBeforeRelayout - childTopBeforeRelayout;
199215
var pageHeight = container.PageSize.Height;
200216
var start = 0;
201217
while (start < run.Count)
@@ -209,7 +225,8 @@ internal static void EnforceKeepWithNext(RGraphics g, CssBox child)
209225
if (start >= run.Count)
210226
return; // RunDropped - not even the run's last member fits alongside child; leave everything in place.
211227

212-
var delta = container.PageTopOf(childTopSlot) - run[start].EffectiveTop;
228+
var originalGroupTop = run[start].EffectiveTop; // captured before OffsetTop below moves it
229+
var delta = container.PageTopOf(childTopSlot) - originalGroupTop;
213230
if (delta <= 0)
214231
return; // Defensive - a positive shift is the only sensible outcome here.
215232

@@ -220,6 +237,11 @@ internal static void EnforceKeepWithNext(RGraphics g, CssBox child)
220237

221238
child.ResumeAt(null, null);
222239
child.PerformLayout(g);
240+
241+
// css-break-3 §3.1 propagation (see PropagateContainerRelocation and RelocateIfNeeded's own
242+
// remark on the same gap): run[start] is the run's earliest member - if it's also its
243+
// parent's first in-flow child, the parent's own top should follow it up by the same delta.
244+
PropagateContainerRelocation(run[start], delta);
223245
}
224246

225247
/// <summary>
@@ -243,5 +265,48 @@ private static List<CssBox> CollectPrecedingKeepWithNextRun(CssBox box)
243265

244266
return run;
245267
}
268+
269+
/// <summary>
270+
/// css-break-3 §3.1's break-point propagation applied to relocation, not just to forced breaks
271+
/// (see <see cref="TryGetForcedBreakTarget"/>'s own "no previous sibling" check, which tests the
272+
/// same condition): while <paramref name="movedBox"/> is its parent's first in-flow child, the
273+
/// parent's own top has no meaning independent of it - so the parent's <see cref="CssBox.Location"/>
274+
/// is shifted by the same <paramref name="delta"/>, and the check repeats one level further up
275+
/// (the parent, now itself "the thing that moved").
276+
/// </summary>
277+
/// <remarks>
278+
/// Deliberately touches only the parent's top, never its bottom/<see cref="CssBoxProperties.ActualBottom"/>:
279+
/// a container's bottom is independently, correctly computed from its LAST child once that child
280+
/// finishes its own layout (ordinary block flow, unaffected by an EARLIER sibling moving) - only
281+
/// the top, decided once before any child is laid out and never revisited otherwise, needs this
282+
/// correction. This also means the check doesn't need "does the parent have any OTHER content" at
283+
/// all: a later sibling that hasn't been laid out yet (or moved by a different amount) has no
284+
/// bearing on whether the FIRST child's own top should still anchor the parent's.
285+
/// </remarks>
286+
/// <remarks>
287+
/// Deliberately narrower than PeachPDF's actual anchor-climbing (which participates in the same
288+
/// call-stack-unwind bubbling every break decision does): this port has no such bubbling for
289+
/// RelocateIfNeeded/EnforceKeepWithNext/InlineFragmentation's relocations (each fires and completes
290+
/// within its own parent's child loop, several stack frames below any grandparent that might also
291+
/// need to react), so climbing further and actually re-laying out an ancestor from underneath its
292+
/// own in-progress layout call would be reentrant and unsafe. This version only ever adjusts the
293+
/// parent's own <see cref="CssBox.Location"/> directly - never a subtree-wide <see cref="CssBox.OffsetTop"/>
294+
/// (<paramref name="movedBox"/> has already been repositioned; shifting it again would double-count
295+
/// it) and never a relayout.
296+
/// </remarks>
297+
internal static void PropagateContainerRelocation(CssBox movedBox, double delta)
298+
{
299+
if (delta == 0)
300+
return;
301+
302+
var current = movedBox;
303+
var parent = current.ParentBox;
304+
while (parent != null && DomUtils.GetPreviousSibling(current) == null)
305+
{
306+
parent.Location = new RPoint(parent.Location.X, parent.Location.Y + delta);
307+
current = parent;
308+
parent = parent.ParentBox;
309+
}
310+
}
246311
}
247312
}

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,14 @@ internal static void ApplyLineBreaking(CssBox blockBox)
4848
if (lines.Count == 0)
4949
return;
5050

51+
// Captured before any shifting, for BlockFragmentation.PropagateContainerRelocation at the
52+
// end - see that method's own remarks for why css-break-3 §3.1 propagation applies here too,
53+
// not only to BlockFragmentation's own relocations: a box whose orphans violation pushes its
54+
// whole first run to a fresh page (below) moves its own EffectiveTop exactly the way
55+
// RelocateIfNeeded's block-level relocation does, and a parent that starts with this box
56+
// needs its own top to follow just the same.
57+
var originalTop = lines[0].LineTop;
58+
5159
var orphans = blockBox.ActualOrphans;
5260
var widows = blockBox.ActualWidows;
5361
var pageHeight = container.PageSize.Height;
@@ -154,6 +162,8 @@ internal static void ApplyLineBreaking(CssBox blockBox)
154162
{
155163
blockBox.ActualBottom = maxBottom + blockBox.ActualPaddingBottom + blockBox.ActualBorderBottomWidth;
156164
}
165+
166+
BlockFragmentation.PropagateContainerRelocation(blockBox, lines[0].LineTop - originalTop);
157167
}
158168
}
159169
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
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.Dom;
8+
using TheArtOfDev.HtmlRenderer.WinForms;
9+
10+
namespace TheArtOfDev.HtmlRenderer.IntegrationTest;
11+
12+
/// <summary>
13+
/// Verifies the same css-break-3 §3.1 propagation gap as <see cref="ContainerLeftBehindTest"/>, applied
14+
/// to <c>EnforceKeepWithNext</c>'s run-pull instead of <c>RelocateIfNeeded</c>'s relocation: a heading
15+
/// pulled onto a paragraph's page (because they're chained by <c>break-after:avoid</c>) is also the
16+
/// section wrapping both of them's first in-flow child - the section's own top needs to follow the
17+
/// heading up, or the section is left spanning from its original page to the pulled-together pair's new
18+
/// one.
19+
/// </summary>
20+
/// <remarks>
21+
/// Diagnosing this surfaced a SECOND, more fundamental bug along the way: <c>CssBox.OffsetTop</c> (what
22+
/// <c>EnforceKeepWithNext</c> uses to pull the run) kept the box's own <c>Rectangles</c> dictionary in
23+
/// sync but never the corresponding <c>CssLineBox.Rectangles</c> entry (a separate dictionary, keyed the
24+
/// other way, that <c>CssLineBox.LineTop</c>/<c>LineBottom</c> - and therefore <c>CssBox.EffectiveTop</c>
25+
/// for any inline-only box - read from). <c>Location.Y</c> (this method's own last statement) was
26+
/// correctly updated while <c>EffectiveTop</c> silently kept reporting the pre-shift position - confirmed
27+
/// by inspecting both dictionaries directly on a real shifted heading before the fix. Fixed by having
28+
/// <c>OffsetTop</c> also update the line's own mirror entry for each line it touches.
29+
/// </remarks>
30+
[TestClass]
31+
[DoNotParallelize]
32+
public sealed class ContainerLeftBehindKeepWithNextTest
33+
{
34+
private static HtmlContainerInt GetInternal(HtmlContainer wrapper)
35+
{
36+
var prop = typeof(HtmlContainer).GetProperty("HtmlContainerInt", BindingFlags.NonPublic | BindingFlags.Instance)!;
37+
return (HtmlContainerInt)prop.GetValue(wrapper)!;
38+
}
39+
40+
private static IEnumerable<CssBox> Walk(CssBox box)
41+
{
42+
yield return box;
43+
foreach (var b in box.Boxes)
44+
foreach (var d in Walk(b))
45+
yield return d;
46+
}
47+
48+
[TestMethod]
49+
public async Task SectionWrappingHeadingAndParagraph_MovesWithThePulledHeading_NeverSpansBothPages()
50+
{
51+
var checkedAnyPull = false;
52+
53+
for (var fillerCount = 1; fillerCount < 60; fillerCount++)
54+
{
55+
using var wrapper = new HtmlContainer();
56+
var filler = string.Concat(Enumerable.Repeat("<p style='margin:0;'>filler line</p>", fillerCount));
57+
await wrapper.SetHtml(
58+
$"""
59+
<html><body>
60+
{filler}
61+
<div class="section" style="margin:0;">
62+
<h2 style="margin:0; break-after:avoid;">SectionHeading WordTwo WordThree WordFour WordFive WordSix WordSeven WordEight WordNine WordTen</h2>
63+
<p style="margin:0;">SectionParagraph</p>
64+
</div>
65+
</body></html>
66+
""");
67+
68+
var container = GetInternal(wrapper);
69+
container.PageSize = new TheArtOfDev.HtmlRenderer.Adapters.Entities.RSize(300, 300);
70+
container.MarginTop = 0;
71+
wrapper.MaxSize = new SizeF(300, 0);
72+
73+
using var bitmap = new Bitmap(300, 20000);
74+
using var g = Graphics.FromImage(bitmap);
75+
wrapper.PerformLayout(g);
76+
77+
var allBoxes = Walk(container.Root).ToList();
78+
var section = allBoxes.FirstOrDefault(b => b.HtmlTag?.Name == "div" && b.GetAttribute("class") == "section");
79+
var heading = allBoxes.FirstOrDefault(b => b.HtmlTag?.Name == "h2");
80+
if (section == null || heading == null)
81+
continue;
82+
83+
var sectionSlot = container.PageIndexOf(section.Location.Y);
84+
var headingSlot = container.PageIndexOf(heading.EffectiveTop);
85+
86+
// Only meaningful once the heading has actually been pulled forward (flush at a fresh page
87+
// top) - otherwise there's no run-pull for the section to have gotten left behind by.
88+
if (System.Math.Abs(heading.EffectiveTop - container.PageTopOf(headingSlot)) > 0.5)
89+
continue;
90+
91+
checkedAnyPull = true;
92+
93+
Assert.AreEqual(headingSlot, sectionSlot,
94+
$"at fillerCount={fillerCount}, the section wrapper is on page slot {sectionSlot} but its heading was pulled to slot {headingSlot}");
95+
}
96+
97+
Assert.IsTrue(checkedAnyPull, "no filler count in range actually exercised a keep-with-next pull - test is not meaningful as written");
98+
}
99+
}

0 commit comments

Comments
 (0)