Skip to content

Commit b5b1408

Browse files
committed
R1: real resumable pass loop for forced page breaks
Replaces the local-correction handling of forced break-before/after:page with a genuine multi-pass driver loop, the foundation stage of the plan to match PeachPDF's resumable fragmentation architecture instead of this port's single-pass-plus-OffsetTop-shift model. HtmlContainerInt.PerformLayout gains DriveLayoutPasses: when the container has a real page grid, it repeatedly calls CssBox.PerformLayout on the root, resuming from wherever the previous pass left off (root.PendingBreakToken), until nothing is left pending. For a document with no forced breaks, or no real page grid (WinForms/WPF), this runs exactly once - behaviorally identical to the old single call. CssBox gains the actual resumption machinery: ResumeAt seeds a box's incoming BreakToken/top-override for the pass about to run; PendingBreakToken/RequestedBreakBeforeTop are how a break discovered arbitrarily deep in the tree reaches the driver - every block-child loop checks its own child's outcome immediately after the child's layout call returns, wraps it in a BlockBreakToken naming itself, and stops laying out further siblings this pass, so the signal bubbles up through call-stack unwind alone, matching PeachPDF's actual mechanism. A box whose forced break fires is not placed at all this pass (RectanglesReset/ MeasureWordsSize already ran, but no Location/content-layout work happens) - deferred whole to the pass that resumes at it. BlockFragmentation.ResolveBlockTop loses its forced-break branch (now handled by CssBox itself, before ResolveBlockTop is even reached); the decision logic moves to a new TryGetForcedBreakTarget, unchanged in substance from the old inline computation. Margin truncation and break-inside:avoid/monolithic relocation remain local single-pass corrections for now - later plan stages (R2-R4) replace those too. New tests exercise the loop across multiple passes specifically (two forced breaks in sequence, and 50 in sequence terminating promptly), which the existing single-break tests don't. Full regression suite (37 IntegrationTest + 16 PdfSharp tests, up from 35+16) passes unchanged - every existing forced-break test now runs through the new pass loop rather than the old inline computation, with identical output.
1 parent fda44e3 commit b5b1408

4 files changed

Lines changed: 343 additions & 36 deletions

File tree

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

Lines changed: 136 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,47 @@ internal CssBox ListItemBox
9292
/// </summary>
9393
internal List<CssBox> RepeatedHeaderRows { get; set; }
9494

95+
/// <summary>
96+
/// The resumption record this box should re-enter its own child loop with this pass, seeded by
97+
/// the parent's <see cref="ResumeAt"/> call right before invoking this box's layout - null for a
98+
/// box entered fresh this pass (no earlier pass stopped inside it). See <see cref="BreakToken"/>'s
99+
/// own doc comment for the chain shape.
100+
/// </summary>
101+
private BreakToken _incomingToken;
102+
103+
/// <summary>
104+
/// A pre-decided document-Y top this box must place itself at this pass, rather than deriving one
105+
/// from its previous sibling - set only for a box being placed for the first time after an earlier
106+
/// pass requested a break before it (<see cref="RequestedBreakBeforeTop"/>). Must not be re-derived:
107+
/// re-deriving it would reach the same "doesn't fit" conclusion and request a break before itself
108+
/// again, forever.
109+
/// </summary>
110+
private double? _resumeTopOverride;
111+
112+
/// <summary>
113+
/// Set by this box's own child-loop right after a child's layout call returns with either
114+
/// <see cref="RequestedBreakBeforeTop"/> set (wrapped as an <c>IsBreakBefore</c> link) or its own
115+
/// <see cref="PendingBreakToken"/> set (wrapped as a continuation link) - the mechanism that lets a
116+
/// break discovered arbitrarily deep in the tree reach <see cref="HtmlContainerInt"/>'s pass loop:
117+
/// every ancestor's own child loop checks this immediately after its child's layout call returns,
118+
/// and if set, stops laying out further siblings this pass and reflects the same fact to its own
119+
/// parent. Reset to null at the top of every <see cref="PerformLayoutImp"/> call.
120+
/// </summary>
121+
internal BreakToken PendingBreakToken { get; private set; }
122+
123+
/// <summary>
124+
/// Set by this box's own layout when a forced <c>break-before</c>/<c>break-after</c> means it
125+
/// cannot be placed this pass at all - the box performs no further layout work and returns
126+
/// immediately, leaving its parent's child loop to notice this (right after the layout call
127+
/// returns) and stop, wrapping <see cref="RequestedBreakBeforeSlot"/>/this value into a
128+
/// <c>BlockBreakToken(IsBreakBefore: true)</c>. Reset to null at the top of every
129+
/// <see cref="PerformLayoutImp"/> call.
130+
/// </summary>
131+
internal double? RequestedBreakBeforeTop { get; private set; }
132+
133+
/// <summary>The pagination slot <see cref="RequestedBreakBeforeTop"/> falls in.</summary>
134+
internal int RequestedBreakBeforeSlot { get; private set; }
135+
95136
private CssLineBox _firstHostingLineBox;
96137
private CssLineBox _lastHostingLineBox;
97138

@@ -520,6 +561,27 @@ public void PerformLayout(RGraphics g)
520561
}
521562
}
522563

564+
/// <summary>
565+
/// Seeds this box's resumption state for the upcoming <see cref="PerformLayout"/> call - called
566+
/// by a parent's child loop right before re-entering a box on a break token's resume path (or by
567+
/// <see cref="HtmlContainerInt"/> on the document root at the start of every pass). Both parameters
568+
/// default to null/absent for a box being entered fresh this pass.
569+
/// </summary>
570+
/// <param name="token">
571+
/// how this box should resume its own child/content loop - <see cref="_incomingToken"/>. Null both
572+
/// for a genuinely fresh box and for a box being placed for the first time via
573+
/// <paramref name="resumeTopOverride"/> (nothing to resume into, since it was never entered before).
574+
/// </param>
575+
/// <param name="resumeTopOverride">
576+
/// a pre-decided top this box must place itself at, bypassing its own natural-position derivation
577+
/// - <see cref="_resumeTopOverride"/>.
578+
/// </param>
579+
internal void ResumeAt(BreakToken token, double? resumeTopOverride = null)
580+
{
581+
_incomingToken = token;
582+
_resumeTopOverride = resumeTopOverride;
583+
}
584+
523585
/// <summary>
524586
/// Set this box in
525587
/// </summary>
@@ -711,6 +773,11 @@ private void ApplyHeight()
711773
/// <param name="g">Device context to use</param>
712774
protected virtual void PerformLayoutImp(RGraphics g)
713775
{
776+
// Pass-scoped signal state - stale values from an earlier pass must never leak into this one.
777+
PendingBreakToken = null;
778+
RequestedBreakBeforeTop = null;
779+
RequestedBreakBeforeSlot = 0;
780+
714781
if (Display != CssConstants.None)
715782
{
716783
RectanglesReset();
@@ -777,7 +844,35 @@ protected virtual void PerformLayoutImp(RGraphics g)
777844
{
778845
left = ContainingBlock.Location.X + ContainingBlock.ActualPaddingLeft + ActualMarginLeft + ContainingBlock.ActualBorderLeftWidth;
779846
var baseTopWithoutMargin = (prevSibling == null && ParentBox != null ? ParentBox.ClientTop : ParentBox == null ? Location.Y : 0) + (prevSibling != null ? prevSibling.ActualBottom + prevSibling.ActualBorderBottomWidth : 0);
780-
top = BlockFragmentation.ResolveBlockTop(this, prevSibling, baseTopWithoutMargin);
847+
848+
if (_incomingToken != null && ReferenceEquals(_incomingToken.Box, this))
849+
{
850+
// Resuming this box's own interrupted child/content loop, not placing it fresh
851+
// - css-break-3 §2 gives a box one inline position across all its fragments, so
852+
// there is nothing to re-derive here; Location already holds it from the pass
853+
// that placed this box originally.
854+
top = Location.Y;
855+
}
856+
else if (_resumeTopOverride.HasValue)
857+
{
858+
// A break-before target an earlier pass already decided (see
859+
// RequestedBreakBeforeTop's doc comment) - must not be re-derived.
860+
top = _resumeTopOverride.Value;
861+
}
862+
else if (BlockFragmentation.TryGetForcedBreakTarget(this, prevSibling, baseTopWithoutMargin, out var breakSlot, out var breakTop))
863+
{
864+
// A forced break-before/after applies and this is a genuinely fresh entry (no
865+
// resume state of any kind) - defer this box (and everything after it in its
866+
// parent's child loop) to a later pass entirely, rather than positioning it now.
867+
RequestedBreakBeforeSlot = breakSlot;
868+
RequestedBreakBeforeTop = breakTop;
869+
return;
870+
}
871+
else
872+
{
873+
top = BlockFragmentation.ResolveBlockTop(this, prevSibling, baseTopWithoutMargin);
874+
}
875+
781876
Location = new RPoint(left, top);
782877
ActualBottom = top;
783878

@@ -803,10 +898,49 @@ protected virtual void PerformLayoutImp(RGraphics g)
803898
}
804899
else if (_boxes.Count > 0)
805900
{
806-
foreach (var childBox in Boxes)
901+
// Resuming our OWN child loop (as opposed to a fresh entry) if the incoming token
902+
// names this box - ResumeChildIndex says which child to pick back up at; every
903+
// child before it already has a finished fragment from an earlier pass and is
904+
// never touched again.
905+
var resumeToken = _incomingToken as BlockBreakToken;
906+
var resumingHere = resumeToken != null && ReferenceEquals(resumeToken.Box, this);
907+
var startIndex = resumingHere ? resumeToken.ResumeChildIndex : 0;
908+
909+
for (var i = startIndex; i < Boxes.Count; i++)
807910
{
911+
var childBox = Boxes[i];
912+
913+
if (i == startIndex && resumingHere)
914+
{
915+
if (resumeToken.IsBreakBefore)
916+
childBox.ResumeAt(null, resumeToken.ResumeTopOverride);
917+
else
918+
childBox.ResumeAt(resumeToken.ChildToken);
919+
}
920+
808921
childBox.PerformLayout(g);
922+
923+
if (childBox.RequestedBreakBeforeTop.HasValue)
924+
{
925+
// Child declined to be placed this pass at all - stop here too, so this
926+
// box's own parent bubbles the same fact upward (see PendingBreakToken's
927+
// doc comment for how this reaches HtmlContainerInt's pass loop).
928+
PendingBreakToken = new BlockBreakToken(
929+
this, childBox.RequestedBreakBeforeSlot, i, null, true, childBox.RequestedBreakBeforeTop);
930+
return;
931+
}
932+
809933
BlockFragmentation.RelocateIfNeeded(childBox);
934+
935+
if (childBox.PendingBreakToken != null)
936+
{
937+
// Child placed itself but stopped somewhere inside its own content/child
938+
// loop - wrap its token in a link naming this box and stop laying out any
939+
// further siblings this pass.
940+
PendingBreakToken = new BlockBreakToken(
941+
this, childBox.PendingBreakToken.ResumeSlotIndex, i, childBox.PendingBreakToken, false, null);
942+
return;
943+
}
810944
}
811945
ActualRight = CalculateActualRight();
812946

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

Lines changed: 56 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,24 @@
66
namespace TheArtOfDev.HtmlRenderer.Core.Fragmentation
77
{
88
/// <summary>
9-
/// Block-level page-break corrections applied as part of HTML-Renderer's existing single-pass
10-
/// positioning, rather than via PeachPDF's break-token/pass-loop model. Every correction here is
11-
/// local: it only needs a box's own natural position, or (for relocation) its already-finished
12-
/// height - none of them need multi-pass resumption, because they never re-enter content that
13-
/// hasn't been measured yet. Real resumption (BreakToken/FragmentainerContext) is reserved for
14-
/// where it's actually needed: inline flow (can't restart word measurement/hyphenation from
15-
/// scratch) and table row continuation.
9+
/// Block-level page-break decisions. Being replaced, stage by stage, with real resumable-pass-loop
10+
/// equivalents matching PeachPDF's architecture (see the fragmentation-engine-parity plan) - forced
11+
/// breaks (<see cref="TryGetForcedBreakTarget"/>) already go through <c>CssBox</c>'s real pass loop
12+
/// as of that plan's R1. Margin truncation (<see cref="ResolveBlockTop"/>) and relocation
13+
/// (<see cref="RelocateIfNeeded"/>) remain local, single-pass corrections for now - they only need a
14+
/// box's own natural position, or its already-finished height, and never re-enter content that
15+
/// hasn't been measured yet - until later plan stages replace them too.
1616
/// </summary>
1717
internal static class BlockFragmentation
1818
{
1919
/// <summary>
20-
/// Resolves a block box's document-space top, applying forced page breaks
21-
/// (<c>break-before</c>/<c>break-after: page</c>, including the legacy <c>always</c> value) and
22-
/// css-break-3 §5.2 margin truncation at unforced breaks. <paramref name="baseTopWithoutMargin"/>
23-
/// is the position before this box's own collapsed top margin is added (the containing block's
24-
/// content top, or the previous sibling's border-box bottom).
20+
/// Resolves a block box's document-space top, applying css-break-3 §5.2 margin truncation at
21+
/// unforced breaks. Forced <c>break-before</c>/<c>break-after: page</c> is handled earlier, by
22+
/// <see cref="TryGetForcedBreakTarget"/> and <c>CssBox</c>'s own pass loop - a box this method is
23+
/// reached for has already been confirmed not to have a forced break pending.
24+
/// <paramref name="baseTopWithoutMargin"/> is the position before this box's own collapsed top
25+
/// margin is added (the containing block's content top, or the previous sibling's border-box
26+
/// bottom).
2527
/// </summary>
2628
internal static double ResolveBlockTop(CssBox box, CssBox prevSibling, double baseTopWithoutMargin)
2729
{
@@ -31,26 +33,6 @@ internal static double ResolveBlockTop(CssBox box, CssBox prevSibling, double ba
3133
if (container == null || !container.HasRealPageGrid)
3234
return naturalTop;
3335

34-
// Suppressed when there's no previous sibling: css-break-3 §3.1 propagation says the break
35-
// point before a container's first in-flow child IS the break point before the container
36-
// itself - so a forced break here would really belong to an ancestor (and ultimately, if
37-
// that ancestor also has no previous sibling, to the fragmentation root, where it's
38-
// inherently inert - there's no earlier page to break away from). Full cross-ancestor
39-
// propagation is out of scope for this port; suppressing at the box's own level is what
40-
// keeps a heading that merely happens to be first on the page from forcing a spurious
41-
// leading blank page - the common case this UA default (`h1 { page-break-before: always }`)
42-
// exists for is a heading that starts a new section partway through a document, not one.
43-
var forcedBefore = prevSibling != null && BreakValues.IsForcedBreak(box.BreakBefore);
44-
var forcedAfter = prevSibling != null && BreakValues.IsForcedBreak(prevSibling.BreakAfter);
45-
46-
if (forcedBefore || forcedAfter)
47-
{
48-
var slot = container.PageIndexOf(naturalTop);
49-
var pageTop = container.PageTopOf(slot);
50-
// Already flush at a fresh page's top - a forced break here does not skip a page.
51-
return naturalTop > pageTop + 0.01 ? container.PageTopOf(slot + 1) : naturalTop;
52-
}
53-
5436
// css-break-3 §5.2: a collapsed margin that, by itself, pushes content across one or more
5537
// page boundaries is truncated to zero - content starts flush at the next page instead of
5638
// paginating through blank vertical space.
@@ -59,6 +41,48 @@ internal static double ResolveBlockTop(CssBox box, CssBox prevSibling, double ba
5941
return naturalSlot > baseSlot ? container.PageTopOf(baseSlot + 1) : naturalTop;
6042
}
6143

44+
/// <summary>
45+
/// Whether <paramref name="box"/> has a forced page break before it (its own <c>break-before</c>,
46+
/// or <paramref name="prevSibling"/>'s <c>break-after</c> - including the legacy <c>always</c>
47+
/// value) that isn't already satisfied by its natural top landing flush at a page top - and if so,
48+
/// the pagination slot/document-Y it must be deferred to. A box with a forced break pending is not
49+
/// placed this pass at all (see <c>CssBox.RequestedBreakBeforeTop</c>); its parent's child loop
50+
/// stops and the pass ends, resuming with this box placed fresh at <paramref name="targetTop"/>.
51+
/// </summary>
52+
/// <remarks>
53+
/// Suppressed when there's no previous sibling: css-break-3 §3.1 propagation says the break point
54+
/// before a container's first in-flow child IS the break point before the container itself - so a
55+
/// forced break here would really belong to an ancestor (and ultimately, if that ancestor also has
56+
/// no previous sibling, to the fragmentation root, where it's inherently inert - there's no earlier
57+
/// page to break away from). Full cross-ancestor propagation is out of scope for this port;
58+
/// suppressing at the box's own level is what keeps a heading that merely happens to be first on
59+
/// the page from forcing a spurious leading blank page - the common case this UA default
60+
/// (`h1 { page-break-before: always }`) exists for is a heading that starts a new section partway
61+
/// through a document, not one.
62+
/// </remarks>
63+
internal static bool TryGetForcedBreakTarget(CssBox box, CssBox prevSibling, double baseTopWithoutMargin, out int slot, out double targetTop)
64+
{
65+
slot = 0;
66+
targetTop = 0;
67+
68+
var container = box.HtmlContainer;
69+
if (container == null || !container.HasRealPageGrid || prevSibling == null)
70+
return false;
71+
72+
if (!BreakValues.IsForcedBreak(box.BreakBefore) && !BreakValues.IsForcedBreak(prevSibling.BreakAfter))
73+
return false;
74+
75+
var naturalTop = baseTopWithoutMargin + box.MarginTopCollapse(prevSibling);
76+
var naturalSlot = container.PageIndexOf(naturalTop);
77+
var pageTop = container.PageTopOf(naturalSlot);
78+
if (naturalTop <= pageTop + 0.01)
79+
return false; // Already flush at a fresh page's top - a forced break here does not skip a page.
80+
81+
slot = naturalSlot + 1;
82+
targetTop = container.PageTopOf(slot);
83+
return true;
84+
}
85+
6286
/// <summary>
6387
/// Called by a block container's child loop right after <paramref name="child"/> (and its whole
6488
/// subtree) has finished laying out. If the child straddles a page boundary and either asks not

0 commit comments

Comments
 (0)