diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f113a597..e18f28d3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -224,6 +224,23 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). simple fonts shipped in 2.3.2, and `docs/architecture.md` says the Layout track runs A to G. Released CHANGELOG sections are unchanged. +- **Layout places every element through one loop, and a renderer can report where it landed + (#288).** The page-counting pass and the drawing pass used to be two copies of the same branching + (`CountPlaceRenderer` and `PlaceRenderer`). One routine now runs both, so the too-tall refusal, + the 50,000-continuation cap and every later placement rule exist once. This is an internal + change with no output change: the normalised bytes, the order and areas of every `Layout` call, + the exception types and messages, and the pages a caller-owned `PdfDocument` holds after a + caught `Render` exception are pinned by tests recorded on the commit before the change, and a + document without a running band still runs one pass. A running band still adds one counting + pass. New internals: `IPlacementSource`, which an internal renderer implements explicitly to + report a target and the box it was placed in (only headings report so far, and a heading split + across pages reports from the piece that holds its first line); `PaginationPlan`, built from + those reports; and `IPlanDependent`, a renderer whose text depends on the plan, resolved over + at most five counting runs before the drawing pass. No public renderer is such a dependent yet, + so no existing document reaches the five-run limit or the check that the drawing pass paginates + as the counting runs did. Removed with no effect on output: `DocumentRenderer.PendingBookmarks` + and the internal `BookmarkEntry`, which nothing wrote or read. + ### Fixed - **On .NET 10 an empty stream was written as `/FlateDecode` with no data (#640).** `PdfStream` diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index 56ca3b4eb..133cd6f34 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -1230,7 +1230,7 @@ private static void TryDelete(string path) } } - private DocumentRenderer CreateRenderer() + internal DocumentRenderer CreateRenderer() { var renderer = new DocumentRenderer(_pdf, _pdf.DefaultPageSize, Margins) { diff --git a/src/VellumPdf.Layout/Elements/BookmarkEntry.cs b/src/VellumPdf.Layout/Elements/BookmarkEntry.cs deleted file mode 100644 index 74d8d3efa..000000000 --- a/src/VellumPdf.Layout/Elements/BookmarkEntry.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright © Timothy van der Ham (@Tim81) -// SPDX-License-Identifier: Apache-2.0 - -namespace VellumPdf.Layout.Elements; - -/// -/// A pending bookmark to be placed at the position of the next rendered element. -/// -internal sealed class BookmarkEntry(string Title, int Level) -{ - public string Title { get; } = Title; - public int Level { get; } = Level; -} diff --git a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs index a609fa757..e759309c8 100644 --- a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs @@ -44,13 +44,13 @@ public sealed class DocumentRenderer // instead. The message names the causes it can, because only one of them is the caller's own. private const int MaxContinuationsPerElement = 50_000; - // Shared by PlaceRenderer and CountPlaceRenderer so the two passes cannot drift to different - // wording, or different verdicts, on an element neither can place (#460). It does not make the - // passes agree in general: with a running band and no content at all, pass 1 still counts one - // page where pass 2 creates none, which predates this change. Making pass 1 throw also moves - // the throw earlier when a band is set, so a caller that catches it is left holding an empty - // PdfDocument rather than the pages pass 2 had already committed; PdfDocument.Save then reports - // that the document has no pages. + // Thrown from the one placement loop, which both passes run, so the two passes cannot drift to + // different wording, or different verdicts, on an element neither can place (#460). It does not + // make the passes agree in general: with a running band and no content at all, the measuring + // pass still counts one page where the drawing pass creates none, which predates the loop. + // The throw comes in the measuring pass when a band is set, so a caller that catches it is left + // holding an empty PdfDocument rather than the pages the drawing pass had already committed; + // PdfDocument.Save then reports that the document has no pages. private const string ElementTooTallMessage = "An element is too tall to fit on a single page and cannot be rendered. " + "Reduce the element's content or increase the page size."; @@ -208,9 +208,6 @@ public IReadOnlyList BandTruncations /// public RunningBand? Footer { get; set; } - // Pending bookmarks: queued by Document.AddBookmark, drained on next Draw. - internal readonly List PendingBookmarks = []; - /// Creates a renderer that paginates content onto using the given page size and margins. /// /// The page size and margins are checked here. A page width or height that is not a positive @@ -403,6 +400,11 @@ internal void RunLayout() { // A refusal belongs to the layout that raised it; a renderer reused for another layout starts clean. _deferredCanvasRefusal = null; + MeasureRuns = 0; + LayoutCalls = 0; + _measureSink = null; + _drawSink = null; + _guard = null; var contentArea = ContentArea; if (contentArea.Width <= 0 || contentArea.Height <= 0) @@ -413,35 +415,42 @@ internal void RunLayout() "Reduce the margins or band heights.", "margins"); + // The check above refuses before any renderer has measured, so the document is still + // saveable once the caller has fixed what it names: a save that fails after the layout + // started cannot be retried, one refused before it can. The walk below, over the added + // elements, finds the plan-dependent ones. + // From here the renderers measure and cache; see Document.MarkFailedIfLaidOut. HasStartedLayout = true; + var dependents = FindPlanDependents(); + + // Reports are collected only when something reads them: a dependent resolves against them + // and the guard compares the drawing pass with them. Tests set RecordPlacements. + _collect = dependents is not null || RecordPlacements; + int totalPages; - if (Header is not null || Footer is not null) + if (dependents is not null) { - // Pass 1: count pages via the same PlaceRenderer code path (no PDF objects created). - totalPages = CountPages(); + // Resolves the dependents against each run's plan until they stop changing, so what the + // drawing pass prints names the page its target is drawn on. + totalPages = MeasureUntilStable(dependents); } - else + else if (Header is not null || Footer is not null) { - totalPages = 0; // unknown / irrelevant + // One measuring run: the same loop as the drawing pass, with no PDF objects created. + totalPages = RunPass(measure: true, totalPages: 0); } - - // Pass 2 (or only pass): full render with running bands resolved. - // The location is that of the element the document added, set here and not in - // PlaceRenderer: PlaceRenderer's variable becomes the overflow renderer, which for a - // heading is a plain paragraph renderer, and mapping that would call a heading's second - // page a paragraph. - for (var i = 0; i < _renderers.Count; i++) + else { - _sink.CurrentKind = KindOf(_renderers[i]); - _sink.CurrentIndex = i; - PlaceRenderer(_renderers[i], totalPages); + totalPages = 0; // unknown / irrelevant } - _sink.CurrentKind = LayoutElementKind.Document; - _sink.CurrentIndex = null; - FinishCurrentPage(totalPages); + // The drawing pass, with running bands resolved. A document with a dependent compares each + // placement it reports with the last measuring run's, which is what the dependents were + // resolved against. + _guard = dependents is not null ? _measureSink : null; + RunPass(measure: false, totalPages); ReportBandTruncations(); if (_deferredCanvasRefusal is not null) @@ -529,39 +538,277 @@ private void FinishCurrentPage(int totalPages) } } + // ── The placement loop ──────────────────────────────────────────────────── + + /// + /// The most measuring runs a document with a plan-dependent renderer gets before the save + /// refuses it. The first run resolves against the placeholder and each later one against the + /// run before it, so five runs allow four refinements. + /// + internal const int MaxMeasureRuns = 5; + + /// Measuring runs of the last , read by tests. + internal int MeasureRuns { get; private set; } + + /// + /// calls the placement loop made in the last + /// , both passes together. Read by tests. + /// + internal int LayoutCalls { get; private set; } + + /// + /// The plan of the last measuring run, or null when none ran. Built on each read. + /// + internal PaginationPlan? MeasurePlan => + _measureSink is null ? null : new PaginationPlan(_measureSink.Placements, _measurePages); + + /// + /// The plan the drawing pass reported, or null before it ran. Built on each read. + /// + internal PaginationPlan? DrawPlan => + _drawSink is null ? null : new PaginationPlan(_drawSink.Placements, _drawPages); + + // The pass the loop is in. A measuring pass creates no page and keeps its own cursor, so a + // page a failed drawing pass left open is not disturbed by it. + private bool _measuring; + private LayoutBox _measureArea; + private double _measureY; + + // 0-based page of the cursor, counted the same way in both passes and from this layout's first + // page. _pdf.Pages.Count would differ between the passes for a kernel document that already + // holds pages. + private int _pageIndex; + + private PlacementSink _placements = new(); + private PlacementSink? _measureSink; + private PlacementSink? _drawSink; + private int _measurePages; + private int _drawPages; + + // The measuring run the drawing pass is compared with; set only when a dependent exists. + private PlacementSink? _guard; + + private bool _collect; + + /// + /// Collect placement reports even when no dependent reads them. Off by default, so a document + /// pays for reports only when a dependent needs them; tests turn it on to read the plans. + /// + internal bool RecordPlacements { get; set; } + + private double Cursor + { + get => _measuring ? _measureY : _currentY; + set + { + if (_measuring) _measureY = value; + else _currentY = value; + } + } + + // The measuring pass reads the content area once, as it always has; the drawing pass reads it + // as it goes. + private LayoutBox PlaceArea => _measuring ? _measureArea : ContentArea; + + // Only the renderers added to this document are searched, not ones a renderer holds inside + // itself. + private List? FindPlanDependents() + { + List? found = null; + foreach (var renderer in _renderers) + if (renderer is IPlanDependent dependent) + (found ??= []).Add(dependent); + return found; + } + + /// + /// Runs one pass over every renderer. Returns the pages it counted: in a measuring pass, one + /// more than the pages it moved past, so a band with no content still counts one page. + /// + private int RunPass(bool measure, int totalPages) + { + _measuring = measure; + _pageIndex = 0; + _placements = new PlacementSink(); + if (measure) + { + _measureArea = ContentArea; + _measureY = _margins.Top + HeaderHeight; + MeasureRuns++; + } + + for (var i = 0; i < _renderers.Count; i++) + { + // The diagnostics location is that of the element the document added, set here and not + // in PlaceRenderer: its variable becomes the overflow renderer, which for a heading is + // a plain paragraph renderer, and mapping that would call a heading's second page a + // paragraph. Diagnostics are reported from the drawing pass only, so the measuring + // pass leaves them alone. + if (!measure) + { + _sink.CurrentKind = KindOf(_renderers[i]); + _sink.CurrentIndex = i; + } + + PlaceRenderer(_renderers[i], totalPages); + } + + if (!measure) + { + _sink.CurrentKind = LayoutElementKind.Document; + _sink.CurrentIndex = null; + FinishCurrentPage(totalPages); + if (_guard is not null && _placements.Count != _guard.Count) + throw PaginationChanged(); + _drawSink = _placements; + _drawPages = _pageIndex + 1; + return _drawPages; + } + + _measureSink = _placements; + _measurePages = _pageIndex + 1; + return _measurePages; + } + + private int MeasureUntilStable(List dependents) + { + var history = new List[dependents.Count]; + for (var i = 0; i < history.Length; i++) + history[i] = []; + var changedLast = new bool[dependents.Count]; + var pageCounts = new List(MaxMeasureRuns); + + var plan = PaginationPlan.Placeholder; + var previousPages = -1; + for (var run = 1; run <= MaxMeasureRuns; run++) + { + var anyChanged = false; + for (var i = 0; i < dependents.Count; i++) + { + changedLast[i] = dependents[i].Resolve(plan); + anyChanged |= changedLast[i]; + history[i].Add(dependents[i].ResolvedText); + } + + var pages = RunPass(measure: true, totalPages: 0); + pageCounts.Add(pages); + + // Run 1 has no earlier run to equal. From run 2, a run that resolved nothing new laid + // out the same strings as the run before it, so its plan is that run's plan. + if (run >= 2 && !anyChanged && pages == previousPages) + return pages; + + plan = new PaginationPlan(_measureSink!.Placements, pages); + previousPages = pages; + } + + throw PaginationDidNotSettle(dependents, history, changedLast, pageCounts); + } + + private static InvalidOperationException PaginationDidNotSettle( + List dependents, List[] history, bool[] changedLast, List pageCounts) + { + const int named = 3; + var parts = new List(named); + var unstable = 0; + for (var i = 0; i < dependents.Count; i++) + { + if (!changedLast[i]) continue; + if (++unstable > named) continue; + parts.Add( + $"the text for '{dependents[i].TargetName}' read " + + string.Join(", ", history[i].Select(s => $"'{s}'"))); + } + + var more = unstable > named ? $", and {unstable - named} more" : ""; + // No dependent changed in the last run, so the page count was what kept moving. + var cause = parts.Count > 0 + ? string.Join("; ", parts) + more + : "the page count read " + string.Join(", ", pageCounts); + return new InvalidOperationException( + $"Pagination did not settle after {MaxMeasureRuns} layout passes: {cause}. " + + "A string that depends on where its target lands can change the layout and so move " + + "that target, and here the passes keep changing it instead of settling. " + + "The renderers have already measured, so lay the content out again in a new renderer " + + "or document."); + } + + private static InvalidOperationException PaginationChanged() => + new("Pagination changed between the measuring and the drawing pass: the drawing pass " + + "reported a placement that differs from the last measuring run's, so a renderer " + + "answered differently the later time. " + + "The renderers have already measured, so lay the content out again in a new renderer " + + "or document."); + + private LayoutResult CallLayout(IRenderer renderer, LayoutBox area) + { + LayoutCalls++; + return renderer.Layout(new LayoutContext(area)); + } + + // Tells the renderer whose result was just accepted to report where it landed. Called before + // the cursor moves, in both passes, so the two passes record the same positions. + private void ReportPlacements(IRenderer? accepted) + { + if (!_collect || accepted is not IPlacementSource source) return; + + var first = _placements.Count; + _placements.Enter(accepted, _pageIndex); + source.ReportPlacements(_placements); + + if (_measuring || _guard is null) return; + for (var i = first; i < _placements.Count; i++) + if (i >= _guard.Count + || _guard[i].PageIndex != _placements[i].PageIndex + || !ReferenceEquals(_guard[i].Key, _placements[i].Key)) + throw PaginationChanged(); + } + + // Moves the cursor to the top of the next page. The drawing pass commits the open page; the + // measuring pass has none. + private void AdvancePage(int totalPages) + { + if (!_measuring) FinishCurrentPage(totalPages); + _pageIndex++; + if (_measuring) _measureY = _measureArea.Y; + } + private void PlaceRenderer(IRenderer renderer, int totalPages) { var continuations = 0; while (true) { - EnsurePage(); + if (!_measuring) EnsurePage(); + var contentArea = PlaceArea; var availableArea = new LayoutBox( - ContentArea.X, _currentY, - ContentArea.Width, ContentArea.Bottom - _currentY); + contentArea.X, Cursor, + contentArea.Width, contentArea.Bottom - Cursor); - var result = renderer.Layout(new LayoutContext(availableArea)); + var result = CallLayout(renderer, availableArea); switch (result.Status) { case LayoutResult.Outcome.Full: - DrawRenderer(renderer); - _currentY = result.OccupiedArea!.Value.Bottom; + ReportPlacements(renderer); + if (!_measuring) DrawRenderer(renderer); + Cursor = result.OccupiedArea!.Value.Bottom; return; case LayoutResult.Outcome.Partial: - DrawRenderer(result.SplitRenderer!); - FinishCurrentPage(totalPages); + ReportPlacements(result.SplitRenderer); + if (!_measuring) DrawRenderer(result.SplitRenderer!); + AdvancePage(totalPages); renderer = result.OverflowRenderer!; break; case LayoutResult.Outcome.Nothing: - FinishCurrentPage(totalPages); - EnsurePage(); - var retry = renderer.Layout(new LayoutContext(ContentArea)); + AdvancePage(totalPages); + if (!_measuring) EnsurePage(); + var retry = CallLayout(renderer, PlaceArea); if (retry.Status == LayoutResult.Outcome.Nothing) { - FinishCurrentPage(totalPages); + if (!_measuring) FinishCurrentPage(totalPages); throw ElementTooTall(); } break; @@ -576,11 +823,11 @@ private void PlaceRenderer(IRenderer renderer, int totalPages) if (++continuations > MaxContinuationsPerElement) { - // Symmetry with the too-tall throw above: commit the open page rather than leave - // its canvas unflushed. The page still stays in the document. Both - // branches reach this throw, but only the Nothing branch can arrive with a page - // still open, because the Partial branch has already finished one. - FinishCurrentPage(totalPages); + // Commit the open page rather than leave its canvas unflushed; the page still + // stays in the document. Both branches reach this throw, but only the Nothing + // branch can arrive with a page still open, because the Partial branch has + // already finished one. The measuring pass has no page to commit. + if (!_measuring) FinishCurrentPage(totalPages); throw TooManyContinuations(); } } @@ -869,70 +1116,6 @@ private static (string Drawn, double Width) FitToWidth(TextStyle style, string t : (text[..cut], width); } - // ── Pass 1: page counting ───────────────────────────────────────────────── - - /// - /// Counts pages by running the same placement logic as the real render pass, - /// but without creating PDF objects. This guarantees the count matches the actual render. - /// - private int CountPages() - { - var pages = 1; - var currentY = _margins.Top + HeaderHeight; - var contentArea = ContentArea; - - foreach (var renderer in _renderers) - CountPlaceRenderer(renderer, ref currentY, ref pages, contentArea); - - return pages; - } - - private void CountPlaceRenderer(IRenderer renderer, ref double currentY, ref int pages, LayoutBox contentArea) - { - var continuations = 0; - while (true) - { - var availableArea = new LayoutBox( - contentArea.X, currentY, - contentArea.Width, contentArea.Bottom - currentY); - - var result = renderer.Layout(new LayoutContext(availableArea)); - - switch (result.Status) - { - case LayoutResult.Outcome.Full: - currentY = result.OccupiedArea!.Value.Bottom; - return; - - case LayoutResult.Outcome.Partial: - pages++; - currentY = contentArea.Y; - renderer = result.OverflowRenderer!; - break; - - case LayoutResult.Outcome.Nothing: - pages++; - currentY = contentArea.Y; - var retry = renderer.Layout(new LayoutContext(contentArea)); - if (retry.Status == LayoutResult.Outcome.Nothing) - { - // This pass used to skip the element and undercount here while - // PlaceRenderer threw on it; the two passes must agree (#460). - throw ElementTooTall(); - } - break; - - default: - // Unreachable for the same reason as PlaceRenderer's arm above, and kept for - // the same reason (#459). - throw new InvalidOperationException($"Unknown layout outcome {result.Status}."); - } - - if (++continuations > MaxContinuationsPerElement) - throw TooManyContinuations(); - } - } - // ── Validation ──────────────────────────────────────────────────────────── /// diff --git a/src/VellumPdf.Layout/Rendering/HeadingRenderer.cs b/src/VellumPdf.Layout/Rendering/HeadingRenderer.cs index b1d7c4099..ae1049897 100644 --- a/src/VellumPdf.Layout/Rendering/HeadingRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/HeadingRenderer.cs @@ -11,7 +11,7 @@ namespace VellumPdf.Layout.Rendering; /// and additionally registers a document /// outline entry at the exact position where the heading lands. /// -internal sealed class HeadingRenderer : IRenderer +internal sealed class HeadingRenderer : IRenderer, IPlacementSource { private readonly Heading _heading; private readonly ParagraphRenderer _inner; @@ -78,6 +78,11 @@ public LayoutResult Layout(LayoutContext context) return result; } + // Explicit, and for the same y the outline entry below uses, so the plan and the /Dest it + // writes are two routes to one fact. A split heading reports from the piece that holds its + // first line; the overflow is a plain paragraph and reports nothing. + void IPlacementSource.ReportPlacements(PlacementSink sink) => sink.Report(_heading, _occupied); + public void Draw(DrawContext ctx) { // Register outline entry at the top of the occupied area. diff --git a/src/VellumPdf.Layout/Rendering/PaginationPlan.cs b/src/VellumPdf.Layout/Rendering/PaginationPlan.cs new file mode 100644 index 000000000..b22e4ffe6 --- /dev/null +++ b/src/VellumPdf.Layout/Rendering/PaginationPlan.cs @@ -0,0 +1,93 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; + +namespace VellumPdf.Layout.Rendering; + +/// +/// Where each reported target landed in one pass, a measuring run or the drawing pass, and how +/// many pages the pass counted. +/// Page indices are 0-based and relative to the first page of the layout, whatever pages the +/// already held. +/// +internal sealed class PaginationPlan +{ + private readonly Dictionary? _targets; + + /// + /// What the first measuring run resolves against: every target is on the first page, at y 0. A + /// fixed answer, so the first run does not depend on anything a previous run produced. + /// + internal static PaginationPlan Placeholder { get; } = new(null, 1); + + /// + /// The placements the run reported, or null for the placeholder. A key reported twice keeps its + /// first placement. + /// + /// The pages the run counted. + internal PaginationPlan(IReadOnlyList? placements, int pageCount) + { + PageCount = pageCount; + Placements = placements ?? []; + if (placements is null) + return; + _targets = new Dictionary(ReferenceEqualityComparer.Instance); + foreach (var p in placements) + _targets.TryAdd(p.Key, (p.PageIndex, p.Y)); + } + + internal int PageCount { get; } + + /// What the run reported, in report order. Empty for the placeholder. + internal IReadOnlyList Placements { get; } + + internal bool IsPlaceholder => _targets is null; + + /// + /// The page index and layout y of . The placeholder answers true with + /// (0, 0) for every key; any other plan answers false for a key nothing reported. + /// + internal bool TryGetTarget(object key, out int pageIndex, out double y) + { + if (_targets is null) + { + pageIndex = 0; + y = 0; + return true; + } + + if (_targets.TryGetValue(key, out var found)) + { + (pageIndex, y) = found; + return true; + } + + pageIndex = 0; + y = 0; + return false; + } + + /// The label of the page: its decimal number. + internal string LabelOf(int pageIndex) => (pageIndex + 1).ToString(CultureInfo.InvariantCulture); +} + +/// +/// A renderer whose text depends on the plan. resolves it between +/// measuring runs, so every string it draws names the page its target is drawn on. +/// +internal interface IPlanDependent +{ + /// + /// Takes the strings this renderer will lay out and draw from . Returns + /// true when they differ from the ones it held, and then drops whatever it cached from them, + /// such as its wrap. A renderer that returns false keeps its cache. + /// + bool Resolve(PaginationPlan plan); + + /// Names the target, for the message about a plan that does not settle. + string TargetName { get; } + + /// The text the last left, for the same message. + string ResolvedText { get; } +} diff --git a/src/VellumPdf.Layout/Rendering/ParagraphRenderer.cs b/src/VellumPdf.Layout/Rendering/ParagraphRenderer.cs index 330ed1408..a51da9501 100644 --- a/src/VellumPdf.Layout/Rendering/ParagraphRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/ParagraphRenderer.cs @@ -26,6 +26,9 @@ public sealed class ParagraphRenderer : IRenderer // Computed during Layout: private List? _lines; + + /// How many times this instance wrapped its text; the cache keeps it at one. + internal int WrapCalls { get; private set; } private double _lineHeight; // max EffectiveLeading across the paragraph private LayoutBox _occupied; @@ -98,6 +101,7 @@ public LayoutResult Layout(LayoutContext context) { _lines = WordWrap(_para.Runs, area.Width, out var nullStyleRuns); _nullStyleRuns = nullStyleRuns; + WrapCalls++; } // Line height = max EffectiveLeading across every fragment in every line. diff --git a/src/VellumPdf.Layout/Rendering/PlacementSink.cs b/src/VellumPdf.Layout/Rendering/PlacementSink.cs new file mode 100644 index 000000000..9666d180b --- /dev/null +++ b/src/VellumPdf.Layout/Rendering/PlacementSink.cs @@ -0,0 +1,70 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using VellumPdf.Layout.Core; + +namespace VellumPdf.Layout.Rendering; + +/// +/// A renderer that can say where a part of what it placed landed. +/// calls on the renderer whose result it accepted: the renderer +/// itself for , the +/// for . The call comes from the placement loop, not from +/// , so the measuring run, which never draws, reports the same +/// positions as the drawing run (#288). +/// +/// +/// Implement it explicitly. The built-in renderers are public classes, so an implicit +/// implementation would be a new public method. +/// +internal interface IPlacementSource +{ + /// + /// Reports only what lies in the placed part: a split heading reports from the piece that holds + /// its first line and the overflow piece reports nothing. + /// + void ReportPlacements(PlacementSink sink); +} + +/// +/// One reported placement. A struct with named fields so a later target kind (an anchor, an index +/// mark, a structure element's page) adds a field rather than changing every report site. +/// +/// What was placed, compared by reference. +/// 0-based, relative to the first page of this layout. +/// The layout-space y of the top of , which for a heading +/// is its first placed line. +/// The renderer whose result was accepted. +/// The area the placed part occupies. +internal readonly record struct Placement(object Key, int PageIndex, double Y, IRenderer Renderer, LayoutBox Box); + +/// +/// Collects the placements of one pass. The loop says which renderer is reporting and on which page +/// with ; the renderer supplies only the key and the box. +/// +internal sealed class PlacementSink +{ + // Created on the first report: a document without a reporting renderer allocates no list. + private List? _placements; + private IRenderer? _renderer; + private int _pageIndex; + + internal int Count => _placements?.Count ?? 0; + + internal Placement this[int index] => _placements![index]; + + internal IReadOnlyList Placements => _placements ?? (IReadOnlyList)[]; + + internal void Enter(IRenderer renderer, int pageIndex) + { + _renderer = renderer; + _pageIndex = pageIndex; + } + + /// Reports that was placed in . + internal void Report(object key, LayoutBox box) + { + _placements ??= []; + _placements.Add(new Placement(key, _pageIndex, box.Y, _renderer!, box)); + } +} diff --git a/tests/VellumPdf.Layout.Tests/LayoutGen.cs b/tests/VellumPdf.Layout.Tests/LayoutGen.cs index 41567469b..5148f8113 100644 --- a/tests/VellumPdf.Layout.Tests/LayoutGen.cs +++ b/tests/VellumPdf.Layout.Tests/LayoutGen.cs @@ -83,14 +83,16 @@ internal static class LayoutGen /// shape this field exists to reach). Deliberately excludes both — a table with no data rows at /// all reports unconditionally from /// TableRenderer.Layout regardless of how much page is actually free, which - /// DocumentRenderer.CountPlaceRenderer then reads as "this element can never render" and - /// throws ElementTooTall even on an empty page with room to spare. Measured directly: + /// the measuring pass of DocumentRenderer then reads as "this element can never + /// render" and throws ElementTooTall even on an empty page with room to spare. + /// Measured directly: /// widening this generator to include it broke both /// PropertyTests.ValidDocument_rendersWithoutThrowing and /// ValidDocument_placesNothingOutsideThePage on the very first run, on documents whose /// content area had hundreds of points to spare. That is a real defect, filed as #488, and - /// outside this pull request's scope; excluding the shape that reaches it keeps the property sweep testing what - /// #480 fixed rather than failing on something else it happens to have found. + /// outside this pull request's scope; excluding the shape that reaches it keeps the property + /// sweep testing what #480 fixed rather than failing on something else it happens to have + /// found. /// private static Gen<(bool Row0IsHeader, bool Row1IsHeader)> RowHeaderShape => Gen.OneOf( (false, false), diff --git a/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs b/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs index 019f1b69f..aec275515 100644 --- a/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs +++ b/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs @@ -12,9 +12,10 @@ namespace VellumPdf.Layout.Tests; /// -/// DocumentRenderer.PlaceRenderer and CountPlaceRenderer used to recurse once per page -/// continuation, so a single element spanning thousands of pages overflowed the CLR stack and -/// killed the process (#459). The too-tall cases also pin the two passes to one verdict (#460). +/// DocumentRenderer's placement loops used to recurse once per page continuation (the drawing +/// pass in PlaceRenderer, the page-counting pass in a second method), so a single element spanning +/// thousands of pages overflowed the CLR stack and killed the process (#459). One loop now runs +/// both passes. The too-tall cases also pin the two passes to one verdict (#460). /// public sealed class PaginationDepthTests { @@ -47,12 +48,12 @@ public void PlaceRenderer_manyContinuations_stackDepthStaysFlat() } [Fact] - public void CountPlaceRenderer_manyContinuations_stackDepthStaysFlat() + public void MeasuringPass_manyContinuations_stackDepthStaysFlat() { var probe = Paginate(new StackDepthProbeRenderer(ProbeContinuations), withFooter: true); - // A footer makes RunLayout count pages before drawing them, so the whole walk happens - // twice — once in each of the two methods that used to recurse. + // A footer makes RunLayout run a measuring pass before the drawing pass, so the whole + // walk happens twice, each time under the one loop. Assert.Equal(2 * (ProbeContinuations + 1), probe.Samples.Count); AssertFlat(probe.Samples); } @@ -64,30 +65,22 @@ public void CountPlaceRenderer_manyContinuations_stackDepthStaysFlat() /// claim that recursion can never be flattened. Measured against the pre-fix renderer in /// Release with DOTNET_TieredCompilation=0: RyuJIT emits the tail call for /// PlaceRenderer, so its probe passes and the no-footer deep-list test renders; but - /// CountPlaceRenderer takes ref parameters, which block a fast tail call, so - /// its probe still fails and the footer deep-list test still dies of stack overflow. Half the - /// file therefore keeps working on the setting that defeats the other half. Release matters in + /// the counting method that has since been merged into it took ref parameters, which + /// block a fast tail call, so its probe still failed and the footer deep-list test still died + /// of stack overflow. Half the file therefore kept working on the setting that defeated the + /// other half. Release matters in /// that sentence: a Debug assembly carries DebuggableAttribute with optimisations off, /// so the JIT never flattens anything and the setting changes nothing at all. /// - private static void AssertFlat(IReadOnlyList<(int Place, int Count)> samples) + private static void AssertFlat(IReadOnlyList samples) { - // Each frame is present (1) only while its own pass is on the stack and absent (0) - // otherwise — e.g. the no-footer probe never runs CountPlaceRenderer at all, so its - // Count component is 0 throughout. Bounding the two components separately, rather than - // asserting their summed value, means a regression confined to a single loop (say, - // PlaceRenderer alone growing past 1) is reported against that component by name instead - // of an ambiguous "the sum of both moved" — which would surface inside - // CountPlaceRenderer_manyContinuations_stackDepthStaysFlat too, since it runs PlaceRenderer - // as its second pass, and wrongly read as CountPlaceRenderer's fault (review round 2, #459). - // The trailing sum check still catches the case neither assertion above would: both - // frames present, or neither, at the same sample. Bounds rather than Assert.All, because - // a recursion regression otherwise prints one near-identical failure block per sample — - // measured at 200 blocks and 34,670 characters for a single test. - Assert.InRange(samples.Max(s => s.Place), 0, 1); - Assert.InRange(samples.Max(s => s.Count), 0, 1); - Assert.Equal(1, samples.Min(s => s.Place + s.Count)); - Assert.Equal(1, samples.Max(s => s.Place + s.Count)); + // The count is of PlaceRenderer frames on the stack at each Layout call. Both passes run + // that one method, so it is 1 whichever pass is running; a recursion regression makes it + // grow with the continuation count. Bounds rather than Assert.All, because a recursion + // regression otherwise prints one near-identical failure block per sample — measured at + // 200 blocks and 34,670 characters for a single test. + Assert.Equal(1, samples.Min()); + Assert.Equal(1, samples.Max()); } private static StackDepthProbeRenderer Paginate(StackDepthProbeRenderer probe, bool withFooter) @@ -104,32 +97,30 @@ private static StackDepthProbeRenderer Paginate(StackDepthProbeRenderer probe, b } /// - /// Splits a fixed number of times, recording how many PlaceRenderer and CountPlaceRenderer - /// frames are on the stack at each Layout call. Each overflow is a fresh instance sharing the + /// Splits a fixed number of times, recording how many PlaceRenderer frames are on the stack at + /// each Layout call. Each overflow is a fresh instance sharing the /// same recording list, as the library's renderers do, so a second pass repeats the walk from /// the start instead of resuming a spent counter. /// private sealed class StackDepthProbeRenderer : IRenderer { private readonly int _remaining; - private readonly List<(int Place, int Count)> _samples; + private readonly List _samples; public StackDepthProbeRenderer(int continuations) : this(continuations, []) { } - private StackDepthProbeRenderer(int remaining, List<(int Place, int Count)> samples) + private StackDepthProbeRenderer(int remaining, List samples) { _remaining = remaining; _samples = samples; } - public IReadOnlyList<(int Place, int Count)> Samples => _samples; + public IReadOnlyList Samples => _samples; public LayoutResult Layout(LayoutContext context) { var frames = new StackTrace(false).GetFrames() ?? []; - _samples.Add(( - frames.Count(f => f.GetMethod()?.Name == "PlaceRenderer"), - frames.Count(f => f.GetMethod()?.Name == "CountPlaceRenderer"))); + _samples.Add(frames.Count(f => f.GetMethod()?.Name == "PlaceRenderer")); var occupied = context.Area.WithHeight(0); return _remaining > 0 @@ -176,8 +167,8 @@ public void DocumentRenderer_deepList_producesExpectedPageCount() [Fact] public void DocumentRenderer_deepList_withFooter_producesExpectedPageCount() { - // A footer makes RunLayout run CountPlaceRenderer before PlaceRenderer, so this drives - // both of the loops that used to recurse (#459) over a ten-thousand-page document. + // A footer makes RunLayout run a measuring pass before the drawing pass, so this drives + // both passes of the loop over a ten-thousand-page document (#459). var pageCount = RenderDeepList(withFooter: true); Assert.Equal(ExpectedPages, pageCount); } @@ -239,10 +230,10 @@ private static void CountLayoutCall(ref int calls, string renderer) // to thread it into (same pattern as MalformedInputTests' CmapFormat4 case). #pragma warning disable xUnit1069 [Fact(Timeout = CapTestTimeoutMs)] - public void CountPlaceRenderer_nonAdvancingOverflow_throwsAfterCap() + public void MeasuringPass_nonAdvancingOverflow_throwsAfterCap() { var pdf = new PdfDocument(); - // Footer set so pass 1 (CountPlaceRenderer) runs first. It never creates PDF objects + // Footer set so the measuring pass runs first. It never creates PDF objects // and never reads OccupiedArea on its Partial branch, so 50,001 trivial turns are cheap. var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, 200), new EdgeInsets(10)) { @@ -275,7 +266,7 @@ public void PlaceRenderer_nonAdvancingOverflow_throwsAfterCap() // No header or footer, so RunLayout skips CountPages() entirely and this renderer's // overflow is placed straight through PlaceRenderer — the path every document with no // running bands takes, and the one the sibling test above never reaches (its footer makes - // CountPlaceRenderer throw first, so pass 2 is never entered). Small page size keeps the + // the measuring pass throw first, so pass 2 is never entered). Small page size keeps the // ~50,001 real page objects this creates cheap. var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, 200), new EdgeInsets(10)); renderer.Add(new NeverAdvancingRenderer()); @@ -444,10 +435,10 @@ public void PlaceRenderer_continuationCap_boundaryIsExact() // 0.7s locally, cancelled at 10s on a CI runner executing seven test assemblies at once. // That is #400's failure mode, and rendering ~50,001 pages twice is what makes it slow. [Fact] - public void CountPlaceRenderer_continuationCap_boundaryIsExact() + public void MeasuringPass_continuationCap_boundaryIsExact() { var pdf = new PdfDocument(); - // Footer set so pass 1 (CountPlaceRenderer) is the one whose cap this pins; pass 2 + // Footer set so the measuring pass is the one whose cap this pins; pass 2 // (PlaceRenderer) then walks the same, freshly-instanced split chain again and must // also complete without error for the render to succeed at all. var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, 200), new EdgeInsets(10)) @@ -475,7 +466,7 @@ public void CountPlaceRenderer_continuationCap_boundaryIsExact() }); Assert.Contains("more than 50000 page continuations", ex.Message); - // CountPlaceRenderer never calls EnsurePage, so if pass 1 is the one that throws here, + // the measuring pass never calls EnsurePage, so if pass 1 is the one that throws here, // as it must — pass 2 never gets far enough to need 50,001 continuations of its own — // no PdfPage exists yet. Assert.Empty(pdfOverflow.Pages); @@ -517,16 +508,16 @@ public void PlaceRenderer_tooTallElement_throwsInvalidOperation() } [Fact] - public void CountPlaceRenderer_tooTallElement_throwsInvalidOperation() + public void MeasuringPass_tooTallElement_throwsInvalidOperation() { - // Footer set so pass 1 (CountPlaceRenderer) is the one that hits the too-tall element + // Footer set so the measuring pass is the one that hits the too-tall element // and must throw the same exception PlaceRenderer would. Before the fix this pass // silently skipped the element and undercounted the document (#460). // // Both passes reach one producer by design, so the message alone cannot tell - // "CountPlaceRenderer threw" apart from "the return the #460 fix replaced was restored, and + // "the measuring pass threw" apart from "the return the #460 fix replaced was restored, and // PlaceRenderer threw on the same element moments later instead". The page count can: - // CountPlaceRenderer never calls EnsurePage, so if pass 1 is the one that throws, RunLayout + // the measuring pass never calls EnsurePage, so if pass 1 is the one that throws, RunLayout // never reaches pass 2 and no PdfPage exists yet. // // The message names the bands here, because with a footer set they are what shrank the @@ -573,7 +564,7 @@ private static void RenderOversizedChart(bool withFooter, out PdfDocument pdf) // ── (e) Nothing-then-fits still counts as a page turn ──────────────────── [Fact] - public void CountPlaceRenderer_nothingThenFitsOnFreshPage_pagesTokenMatchesActualCount() + public void MeasuringPass_nothingThenFitsOnFreshPage_pagesTokenMatchesActualCount() { // Regresses the Nothing branch's pages++ (#460 review): a first element that partly // fills page 1, followed by one that does not fit in what remains but does fit on a @@ -600,7 +591,7 @@ public void CountPlaceRenderer_nothingThenFitsOnFreshPage_pagesTokenMatchesActua Slices = [new PieSlice(1, ColorRgb.Black)], }; // Nothing in page 1's remainder, then Full when retried on a fresh page — the exact - // branch CountPlaceRenderer's pages++ guards. + // branch the measuring pass's pages++ guards. renderer.Add(new PieChartRenderer(chart)); using var ms = new MemoryStream(); @@ -642,15 +633,15 @@ public void Draw(DrawContext context) { } // -> Partial again, after items 1-2. // page 3 (full 266.4pt): the last item (90 <= 266.4) -> Full. // Three pages, reached through two Partial page turns of one top-level ListRenderer — the - // exact path that drives CountPlaceRenderer's Partial branch, not the Nothing branch (b)/(e) + // exact path that drives the measuring pass's Partial branch, not the Nothing branch (b)/(e) // above already cover. private const int SplittingListItemCount = 4; private const int SplittingListExpectedPages = 3; [Fact] - public void CountPlaceRenderer_splittingElement_pagesTokenMatchesActualCount() + public void MeasuringPass_splittingElement_pagesTokenMatchesActualCount() { - // Regresses two lines on CountPlaceRenderer's Partial branch (#460 review round 2): + // Regresses two lines on the measuring pass's Partial branch (#460 review round 2): // - pages++: without it, pass 1 never advances past page 1, so every footer resolves // {pages} to 1 no matter how many pages pass 2 actually draws. // - currentY = contentArea.Y: without it, pass 1's continuation pages measure from diff --git a/tests/VellumPdf.Layout.Tests/PlacementLoopGoldenTests.cs b/tests/VellumPdf.Layout.Tests/PlacementLoopGoldenTests.cs new file mode 100644 index 000000000..6dfa5c714 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/PlacementLoopGoldenTests.cs @@ -0,0 +1,270 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using VellumPdf.Core; +using VellumPdf.Document; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Rendering; +using VellumPdf.TestSupport; +using static VellumPdf.Layout.Tests.PlacementLoopSupport; + +namespace VellumPdf.Layout.Tests; + +/// +/// #288 pins for the placement loop on inputs that exist today: the bytes (after normalisation), +/// the order and areas of every Layout call, and what a caught Render exception +/// leaves in a caller-owned . Each value was recorded on the commit +/// before the loop was merged into one routine, so a difference here means the output or the +/// call sequence of an existing input moved. +/// +public sealed class PlacementLoopGoldenTests +{ + // Assert.Equal truncates long strings, and a pin is only useful if a failure prints the new + // value. + private static void Pin(string expected, string actual) => + Assert.True(expected == actual, $"computed {actual}"); + + private static string Summary(RunningBand? header, RunningBand? footer, bool existingPage = false) + { + var pdf = NewPdf(); + if (existingPage) + pdf.AddPage(Page); + var renderer = new DocumentRenderer(pdf, Page, Margins) { Header = header, Footer = footer }; + var log = new CallLog(); + foreach (var r in StandardContent(log)) + renderer.Add(r); + var bytes = Render(renderer); + return $"{NormalisedSha256(bytes)} calls={Sha256(log.Text)} n={log.Calls} pages={PageCount(bytes)}"; + } + + [Fact] + public void Plain_pinsBytesAndLayoutCalls() => + Pin("EF54931F3AF68214B4771AB1A0C7D6A033FF32C63B81EC31F635ED781BC37E41 calls=5D97D336CB4974A41BB055CEDB427D9218F684911ABAF90A92337B2637FD42C6 n=36 pages=8", Summary(null, null)); + + [Fact] + public void Footer_pinsBytesAndLayoutCalls() => + Pin("7E385010EDBBC5CC3F478F52B7E044C956711D15155EBFD704A08E905A20FC8D calls=CD9A78B740AB92E75C5B11ABC97C5E7A335CE41B0919195C880437881D243519 n=68 pages=8", Summary(null, new RunningBand("Page {page}"))); + + [Fact] + public void HeaderAndFooterWithPagesToken_pinBytesAndLayoutCalls() => + Pin("DB554F95C62B4DDBD2A7AB99D8F64112F3BC1E015CE352CB3E8777757B5781FF calls=5ADF195645B63065606DBC400D2EA692F093D9B1027C6C6BAE9E607D1AFEC8EB n=76 pages=9", Summary(new RunningBand("Header"), new RunningBand("{page} of {pages}"))); + + // A caller-owned PdfDocument that already holds a page: {page} counts it, {pages} does not. + [Fact] + public void PdfDocumentWithAnExistingPage_andAFooter_pinsBytesAndLayoutCalls() => + Pin("4DBD3B2D411EECBDBAF7681AE2BE3E099573259114FC76A47044CDEBB0E4E6BB calls=CD9A78B740AB92E75C5B11ABC97C5E7A335CE41B0919195C880437881D243519 n=68 pages=9", Summary(null, new RunningBand("{page}/{pages}"), existingPage: true)); + + // ── Too tall, in each pass, and what the caller's document holds afterwards ─ + + private sealed class NothingRenderer : IRenderer + { + public LayoutResult Layout(LayoutContext context) => LayoutResult.Nothing(); + public void Draw(DrawContext context) { } + } + + private static string CatchTooTall(RunningBand? footer) + { + var pdf = NewPdf(); + var renderer = new DocumentRenderer(pdf, Page, Margins) { Footer = footer }; + renderer.Add(new ParagraphRenderer(new Paragraph("before", Body))); + renderer.Add(new NothingRenderer()); + var ex = Assert.Throws(() => renderer.Render(new MemoryStream())); + return $"{ex.Message}|{pdf.Pages.Count}"; + } + + [Fact] + public void TooTall_inTheDrawPass_leavesTheCommittedPages() => + Pin("An element is too tall to fit on a single page and cannot be rendered. Reduce the element's content or increase the page size.|2", CatchTooTall(null)); + + // The drawing pass commits the page it has open before it throws: only Finish turns a page's + // ContentBytes from null into an array. + [Fact] + public void TooTall_inTheDrawPass_commitsTheOpenPageBeforeThrowing() + { + var pdf = NewPdf(); + var renderer = new DocumentRenderer(pdf, Page, Margins); + renderer.Add(new ParagraphRenderer(new Paragraph("before", Body))); + renderer.Add(new NothingRenderer()); + Assert.Throws(() => renderer.Render(new MemoryStream())); + Assert.All(pdf.Pages, page => Assert.NotNull(page.ContentBytes)); + } + + [Fact] + public void TooTall_inTheMeasurePass_leavesNoPages() => + Pin("An element is too tall to fit on a single page and cannot be rendered. On a 300.0pt page, 40.0pt of margins and 18.4pt of running bands (header 0.0pt, footer 18.4pt) leave a content area 241.6pt tall. Reduce the element's content, lower the band heights, reduce the margins, or increase the page size.|0", CatchTooTall(new RunningBand("f"))); + + // ── The continuation cap, in each pass ─────────────────────────────────── + + private const string CapMessage = + "A single element needed more than 50000 page continuations, so its layout is not converging. Either an overflow renderer never advances, or the element genuinely spans more pages than one element may and should be split into several, or its height sits within a rounding error of the content area, so pagination refuses and accepts it by turns."; + + private sealed class NeverAdvancing : IRenderer + { + public LayoutResult Layout(LayoutContext context) => + LayoutResult.Partial(context.Area.WithHeight(0), this, this); + public void Draw(DrawContext context) { } + } + + private static string CatchCap(RunningBand? footer) + { + var pdf = NewPdf(); + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, 200), new EdgeInsets(10)) { Footer = footer }; + renderer.Add(new NeverAdvancing()); + var ex = Assert.Throws(() => renderer.Render(new MemoryStream())); + return $"{ex.Message}|{pdf.Pages.Count}"; + } + +#pragma warning disable xUnit1069 // DocumentRenderer.Render takes no cancellation token. + [Fact(Timeout = 300_000)] + public void Cap_inTheDrawPass_pinsMessageAndPages() => + Pin(CapMessage + "|50001", CatchCap(null)); + + [Fact(Timeout = 300_000)] + public void Cap_inTheMeasurePass_pinsMessageAndPages() => + Pin(CapMessage + "|0", CatchCap(new RunningBand("f"))); +#pragma warning restore xUnit1069 + + // ── A footer and nothing to place ──────────────────────────────────────── + + [Fact] + public void BandAndNoContent_saysTheDocumentHasNoPages() + { + var pdf = NewPdf(); + var renderer = new DocumentRenderer(pdf, Page, Margins) { Footer = new RunningBand("f") }; + var ex = Assert.Throws(() => renderer.Render(new MemoryStream())); + Pin("The document has no pages.|0", $"{ex.Message}|{pdf.Pages.Count}"); + } + + // ── A custom renderer that answers differently per call, with a band ───── + + /// Full at 20pt on its first call and at 200pt on every later one. + private sealed class ShrinkThenGrow : IRenderer + { + private int _calls; + public LayoutResult Layout(LayoutContext context) => + LayoutResult.Full(context.Area.WithHeight(_calls++ == 0 ? 20 : 200)); + public void Draw(DrawContext context) { } + } + + [Fact] + public void CustomRendererAnsweringDifferentlyPerCall_withABand_savesAndPinsBytes() + { + var pdf = NewPdf(); + var renderer = new DocumentRenderer(pdf, Page, Margins) { Footer = new RunningBand("{page} of {pages}") }; + var log = new CallLog(); + renderer.Add(Logging.Wrap(new ShrinkThenGrow(), log)); + renderer.Add(Logging.Wrap(new ParagraphRenderer(new Paragraph("after", Body)), log)); + var bytes = Render(renderer); + Pin("9BE80EE031AA3DB29B5B00C5E6A7673FD3922EF88A009AAE42630DDE312115E1 calls=A1ED36B08776FD606503253BF737F648DAE802C9206EC1460A4B25BE0D10CF98 n=4 pages=1", $"{NormalisedSha256(bytes)} calls={Sha256(log.Text)} n={log.Calls} pages={PageCount(bytes)}"); + } + + // ── Cost: Layout calls and allocation, no clock (#400) ─────────────────── + + private static (int Calls, long Allocated) MeasureCost(Func> content, RunningBand? footer) + { + var pdf = NewPdf(); + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 595, 842), new EdgeInsets(40)) { Footer = footer }; + var log = new CallLog(); + foreach (var r in content()) + renderer.Add(Logging.Wrap(r, log)); + using var ms = new MemoryStream(); + var before = GC.GetAllocatedBytesForCurrentThread(); + renderer.Render(ms); + return (log.Calls, GC.GetAllocatedBytesForCurrentThread() - before); + } + + private static List ThousandParagraphs() => + [ + .. Enumerable.Range(0, 1000).Select(i => (IRenderer)new ParagraphRenderer(new Paragraph(ParagraphText(i), Body))), + ]; + + private static List BigTable() + { + var table = new Elements.Table.TableElement(); + for (var r = 0; r < 1000; r++) + { + var row = table.AddRow(); + row.AddCell($"Row {r} cell A"); + row.AddCell($"Row {r} cell B with a little more text to wrap in the column"); + } + return [new Rendering.Table.TableRenderer(table)]; + } + + [Fact] + public void Cost_thousandParagraphs_pinsLayoutCallsAndTheAllocationRatio() + { + // Warm the JIT and the font metrics, so the first measured run does not carry them. + MeasureCost(ThousandParagraphs, null); + var plain = MeasureCost(ThousandParagraphs, null); + var banded = MeasureCost(ThousandParagraphs, new RunningBand("Page {page}")); + Assert.Equal((1076, 2116), (plain.Calls, banded.Calls)); + Assert.True(banded.Allocated <= plain.Allocated * 1.05, $"{plain.Allocated} {banded.Allocated}"); + } + + // Only the call counts are pinned. Table allocation is not: its cost belongs to #517. + [Fact] + public void Cost_thousandRowTable_pinsLayoutCalls() + { + var plain = MeasureCost(BigTable, null); + var banded = MeasureCost(BigTable, new RunningBand("Page {page}")); + Assert.Equal((30, 62), (plain.Calls, banded.Calls)); + } + + // ── PDF/A-2u, headings (the second splits across two pages), a footer with a page count ─── + + private static readonly string Regular = + Path.Combine(AppContext.BaseDirectory, "Fonts", "LiberationSans-Regular.ttf"); + + private static byte[] PdfA2uDocument() + { + using var doc = new Document + { + PageSize = Page, + Margins = Margins, + Timestamp = new DateTimeOffset(2026, 11, 20, 12, 0, 0, TimeSpan.Zero), + DocumentId = Convert.FromHexString("000102030405060708090A0B0C0D0E0F"), + Conformance = PdfConformance.PdfA2u, + Tagged = true, + Language = "en-US", + }; + doc.Info.Title = "Placement loop"; + var handle = doc.LoadTrueTypeFont(Regular); + var style = new TextStyle { FontRef = handle, FontSize = 12 }; + doc.SetFooter("Page {page} of {pages}", style); + for (var chapter = 1; chapter <= 4; chapter++) + { + doc.Add(new Heading(string.Join(' ', Enumerable.Repeat($"Chapter {chapter} heading", chapter == 2 ? 30 : 1)), style)); + for (var i = 0; i < (chapter == 1 ? 4 : 6); i++) + doc.Add(new Paragraph(ParagraphText(i), style)); + } + + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + [Fact] + public void PdfA2uDocument_pinsBytes() => + Pin("DD46E6108AF15BC933A173578B994924276DB5CAB0690B44D3D553CFCB074870", NormalisedSha256(PdfA2uDocument(), foldToUnicodeLineEnds: true)); + + [Fact] + public void PdfA2uDocument_veraPdfReportsCompliant() + { + var path = Path.Combine(Path.GetTempPath(), $"vellum-placement-{Guid.NewGuid():N}.pdf"); + File.WriteAllBytes(path, PdfA2uDocument()); + try + { + ExternalTool.TryRun("verapdf", ["--flavour", "2u", path], + out var exit, out var report, out var stderr, out var timedOut, timeoutMs: 120_000); + + Assert.False(timedOut, $"veraPDF timed out.\nstderr:\n{stderr}"); + Assert.True(exit is 0 or 1, $"veraPDF exited {exit}: {VeraPdfExitCode.Describe(exit)}\n{report}\n{stderr}"); + Assert.Contains("isCompliant=\"true\"", report, StringComparison.Ordinal); + } + finally + { + File.Delete(path); + } + } +} diff --git a/tests/VellumPdf.Layout.Tests/PlacementLoopSupport.cs b/tests/VellumPdf.Layout.Tests/PlacementLoopSupport.cs new file mode 100644 index 000000000..3c6f600eb --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/PlacementLoopSupport.cs @@ -0,0 +1,160 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using VellumPdf.Core; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Elements.Table; +using VellumPdf.Layout.Rendering; +using VellumPdf.Layout.Rendering.Table; + +namespace VellumPdf.Layout.Tests; + +/// +/// Shared by the placement-loop tests (#288): documents built only from public renderers over a +/// caller-owned , a wrapper that logs every Layout call, and the +/// normalisation that lets one hash serve net10.0 and net11.0. +/// +internal static class PlacementLoopSupport +{ + internal static readonly PdfRectangle Page = new(0, 0, 300, 300); + internal static readonly EdgeInsets Margins = new(20); + + internal static readonly TextStyle Body = new() { Font = Standard14.Helvetica, FontSize = 12 }; + + internal static PdfDocument NewPdf() => new() + { + Timestamp = new DateTimeOffset(2026, 11, 20, 12, 0, 0, TimeSpan.Zero), + DocumentId = Convert.FromHexString("000102030405060708090A0B0C0D0E0F"), + }; + + /// + /// One line per Layout call: the wrapper's number, then the area offered. + /// + internal sealed class CallLog + { + private readonly List _lines = []; + private int _next; + + internal int Calls => _lines.Count; + internal int NextId() => _next++; + internal void Add(int id, LayoutBox area) => + _lines.Add(string.Create(CultureInfo.InvariantCulture, $"{id} {area.X:F3} {area.Y:F3} {area.Width:F3} {area.Height:F3}")); + internal string Text => string.Join('\n', _lines); + } + + /// + /// Forwards to and logs each Layout call. A split or overflow + /// renderer it returns is wrapped under the same number. + /// + internal sealed class Logging(IRenderer inner, CallLog log, int id) : IRenderer + { + internal static Logging Wrap(IRenderer inner, CallLog log) => new(inner, log, log.NextId()); + + public LayoutResult Layout(LayoutContext context) + { + log.Add(id, context.Area); + var result = inner.Layout(context); + if (result.Status == LayoutResult.Outcome.Partial) + return LayoutResult.Partial( + result.OccupiedArea!.Value, + new Logging(result.SplitRenderer!, log, id), + new Logging(result.OverflowRenderer!, log, id)); + return result; + } + + public void Draw(DrawContext context) => inner.Draw(context); + } + + internal static string ParagraphText(int i) => + $"Paragraph {i}: the quick brown fox jumps over the lazy dog, again and again, over a line that wraps."; + + /// Paragraphs, a table and a list: several pages at 300 x 300 pt. + internal static List StandardContent(CallLog? log = null) + { + var list = new List(); + for (var i = 0; i < 12; i++) + list.Add(new ParagraphRenderer(new Paragraph(ParagraphText(i), Body))); + var table = new TableElement(); + for (var r = 0; r < 14; r++) + { + var row = table.AddRow(); + row.AddCell($"Row {r} cell A"); + row.AddCell($"Row {r} cell B with a little more text to wrap in the column"); + } + list.Add(new TableRenderer(table)); + var items = new ListElement(ListStyle.OrderedDecimal); + for (var i = 0; i < 10; i++) + items.Add($"Item {i} of the list, with enough words to take two lines on this narrow page.", Body); + list.Add(new ListRenderer(items)); + for (var i = 12; i < 24; i++) + list.Add(new ParagraphRenderer(new Paragraph(ParagraphText(i), Body))); + return log is null ? list : [.. list.Select(r => (IRenderer)Logging.Wrap(r, log))]; + } + + internal static byte[] Render(DocumentRenderer renderer) + { + using var ms = new MemoryStream(); + renderer.Render(ms); + return ms.ToArray(); + } + + internal static int PageCount(byte[] pdf) => + Regex.Matches(Encoding.Latin1.GetString(pdf), @"/Type\s*/Page(?![s\w])").Count; + + internal static string Sha256(string text) => + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))); + + internal static string NormalisedSha256(byte[] pdf, bool foldToUnicodeLineEnds = false) => + Convert.ToHexString(SHA256.HashData(Encoding.Latin1.GetBytes(Normalise(pdf, foldToUnicodeLineEnds)))); + + // The same rule as CatalogGoldenTests.Normalise in VellumPdf.Kernel.Tests (#626): inflate every + // Flate stream and blank the xref offsets, so the compressor of the runtime drops out. + private static readonly Regex StreamObject = new( + @"(?\d+ 0 obj\n)(?<<(?:(?!\nstream\n|endobj).)*?>>)(?\nstream\n)(?.*?)(?\nendstream)", + RegexOptions.Singleline | RegexOptions.CultureInvariant); + + // foldToUnicodeLineEnds: an embedded font's ToUnicode CMap is written with CR LF line ends on + // Windows and LF on Linux (#630), so a hash that must hold on both folds CR LF to LF in every + // Flate stream whose inflated text contains `begincmap`, and nowhere else. In the pinned + // document that is the one ToUnicode stream. It does nothing once #630 is fixed (#647), + // because every line end is then LF already. + internal static string Normalise(byte[] pdf, bool foldToUnicodeLineEnds = false) + { + var text = Encoding.Latin1.GetString(pdf); + text = StreamObject.Replace(text, m => + { + var dictionary = m.Groups["dict"].Value; + if (!dictionary.Contains("/FlateDecode", StringComparison.Ordinal)) + return m.Value; + var inflated = Inflate(Encoding.Latin1.GetBytes(m.Groups["data"].Value)); + if (foldToUnicodeLineEnds && inflated.Contains("begincmap", StringComparison.Ordinal)) + inflated = inflated.Replace("\r\n", "\n", StringComparison.Ordinal); + dictionary = Regex.Replace(dictionary, @"/Length \d+", "/Length " + inflated.Length); + dictionary = dictionary.Replace("/Filter /FlateDecode", "/Filter /FlateDecode (inflated)", StringComparison.Ordinal); + return m.Groups["head"].Value + dictionary + m.Groups["mid"].Value + inflated + m.Groups["tail"].Value; + }); + text = Regex.Replace(text, @"\d{10} (\d{5}) ([nf])", "# $1 $2"); + text = Regex.Replace(text, @"startxref\n\d+", "startxref\n#"); + return text; + } + + // An empty stream has no zlib header on net10.0, so there is nothing to inflate. + private static string Inflate(byte[] data) + { + if (data.Length == 0) + return string.Empty; + using var input = new MemoryStream(data); + using var zlib = new ZLibStream(input, CompressionMode.Decompress); + using var output = new MemoryStream(); + zlib.CopyTo(output); + return Encoding.Latin1.GetString(output.ToArray()); + } +} diff --git a/tests/VellumPdf.Layout.Tests/PlacementLoopTests.cs b/tests/VellumPdf.Layout.Tests/PlacementLoopTests.cs new file mode 100644 index 000000000..b8e7c606a --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/PlacementLoopTests.cs @@ -0,0 +1,726 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using CsCheck; +using VellumPdf.Core; +using VellumPdf.Document; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Rendering; +using VellumPdf.TestSupport; +using static VellumPdf.Layout.Tests.PlacementLoopSupport; + +namespace VellumPdf.Layout.Tests; + +/// +/// #288: the one placement loop, the placement reports a heading makes from it, the plan they +/// build, and the measuring loop that resolves plan-dependent renderers. Everything here reads +/// internals (, +/// , the plans), which no public member exposes. +/// +public sealed class PlacementLoopTests +{ + // ── Test renderers ─────────────────────────────────────────────────────── + + /// A block of fixed height. + private sealed class Block(double height) : IRenderer + { + public LayoutResult Layout(LayoutContext context) => + context.Area.Height < height + ? LayoutResult.Nothing() + : LayoutResult.Full(context.Area.WithHeight(height)); + + public void Draw(DrawContext context) { } + } + + /// + /// A plan-dependent renderer whose text is the label of its target's page, and whose height + /// depends on that label. It caches the height and drops the cache when + /// reports a change, as says it must. + /// + private sealed class LabelDependent(object target, Func heightOf) : IRenderer, IPlanDependent + { + private string _text = ""; + private double? _height; + + public int ResolveCalls { get; private set; } + public string TargetName => "target"; + public string ResolvedText => _text; + + public bool Resolve(PaginationPlan plan) + { + ResolveCalls++; + plan.TryGetTarget(target, out var page, out _); + var text = plan.LabelOf(page); + if (text == _text) return false; + _text = text; + _height = null; + return true; + } + + public LayoutResult Layout(LayoutContext context) + { + _height ??= heightOf(_text); + return context.Area.Height < _height + ? LayoutResult.Nothing() + : LayoutResult.Full(context.Area.WithHeight(_height.Value)); + } + + public void Draw(DrawContext context) { } + } + + /// + /// A plan-dependent renderer that takes the next string of a script on each resolve. + /// + private sealed class ScriptedDependent(params string[] script) : IRenderer, IPlanDependent + { + private string _text = ""; + + public string TargetName => "scripted"; + public string ResolvedText => _text; + + public bool Resolve(PaginationPlan plan) + { + var next = script[Math.Min(Resolves++, script.Length - 1)]; + if (next == _text) return false; + _text = next; + return true; + } + + public int Resolves { get; private set; } + public LayoutResult Layout(LayoutContext context) => LayoutResult.Full(context.Area.WithHeight(10)); + public void Draw(DrawContext context) { } + } + + private static Heading NewHeading(string text) => new(text, Body) { Margins = EdgeInsets.Zero }; + + private static DocumentRenderer NewRenderer(PdfDocument pdf, RunningBand? footer = null) => + new(pdf, Page, Margins) { Footer = footer, RecordPlacements = true }; + + // ── Plan correctness ───────────────────────────────────────────────────── + + private static readonly Regex DestPattern = new( + @"/Dest \[(\d+) 0 R /XYZ (\S+) (\S+) null\]", RegexOptions.CultureInvariant); + + /// + /// The page index and PDF y each outline entry of the file points at, in entry order. + /// + private static List<(int PageIndex, double PdfY)> OutlineDests(byte[] pdf) + { + var text = Encoding.Latin1.GetString(pdf); + var kids = Regex.Match(text, @"/Kids \[([^\]]*)\]").Groups[1].Value; + var pages = Regex.Matches(kids, @"(\d+) 0 R") + .Select(m => int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture)) + .ToList(); + return DestPattern.Matches(text) + .Select(m => ( + pages.IndexOf(int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture)), + double.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture))) + .ToList(); + } + + /// + /// Headings among filler, one of them too long for the room left on its page, so it splits. + /// Returns the headings in document order. + /// + private static List HeadingDocument(DocumentRenderer renderer) + { + var headings = new List + { + NewHeading("First"), + NewHeading(string.Join(' ', Enumerable.Repeat("Split", 40))), + NewHeading("Third"), + }; + renderer.Add(new HeadingRenderer(headings[0])); + renderer.Add(new Block(190)); + renderer.Add(new HeadingRenderer(headings[1])); + renderer.Add(new Block(120)); + renderer.Add(new Block(120)); + renderer.Add(new HeadingRenderer(headings[2])); + return headings; + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void HeadingPlan_equalsTheOutlineDestination_includingASplitHeading(bool withBand) + { + var pdf = NewPdf(); + var renderer = NewRenderer(pdf, withBand ? new RunningBand("Page {page}") : null); + var headings = HeadingDocument(renderer); + var bytes = Render(renderer); + + // Two independent routes to one fact: the placement loop's report and the /Dest the draw + // pass wrote. A plan from the measuring run exists only with a band. + var plans = new List { renderer.DrawPlan! }; + if (withBand) plans.Add(renderer.MeasurePlan!); + Assert.Equal(withBand ? 2 : 1, plans.Count); + + var dests = OutlineDests(bytes); + Assert.Equal(3, dests.Count); + Assert.True(PageCount(bytes) >= 3, "the fixture must span at least three pages"); + + foreach (var plan in plans) + { + for (var i = 0; i < headings.Count; i++) + { + Assert.True(plan.TryGetTarget(headings[i], out var page, out var y), $"heading {i} has no placement"); + Assert.Equal(dests[i].PageIndex, page); + Assert.Equal(dests[i].PdfY, Page.Height - y, 4); + } + } + + // The second heading is the one that splits: it starts where the filler left the cursor, + // and its whole height would run past the bottom of the content area. + plans[0].TryGetTarget(headings[1], out _, out var splitY); + var whole = new HeadingRenderer(headings[1]) + .Layout(new LayoutContext(new LayoutBox(20, 0, 260, 10_000))).OccupiedArea!.Value.Height; + Assert.True(splitY + whole > Page.Height - Margins.Bottom, $"{splitY} + {whole} does not overflow the page"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AHeadingThatFindsNoRoom_isPlannedAtTheTopOfTheNextPage(bool withBand) + { + // 5pt are left under the block, less than one line, so the heading answers Nothing and is + // laid out again on the next page. The report belongs to the result that was accepted. + var renderer = NewRenderer(NewPdf(), withBand ? new RunningBand("f") : null); + var heading = NewHeading("Late"); + renderer.Add(new Block(withBand ? 236 : 255)); + renderer.Add(new HeadingRenderer(heading)); + var bytes = Render(renderer); + + var plan = renderer.DrawPlan!; + Assert.True(plan.TryGetTarget(heading, out var page, out var y)); + Assert.Equal(1, page); + Assert.Equal(Margins.Top, y); + Assert.Single(plan.Placements); + var dest = Assert.Single(OutlineDests(bytes)); + Assert.Equal((page, Page.Height - y), dest); + } + + [Fact] + public void MeasurePlan_andDrawPlan_reportTheSamePlacements() + { + var renderer = NewRenderer(NewPdf(), new RunningBand("Page {page}")); + HeadingDocument(renderer); + Render(renderer); + + var measured = renderer.MeasurePlan!.Placements; + var drawn = renderer.DrawPlan!.Placements; + Assert.Equal(3, measured.Count); + Assert.Equal( + measured.Select(p => (p.Key, p.PageIndex, p.Y)).ToList(), + drawn.Select(p => (p.Key, p.PageIndex, p.Y)).ToList()); + Assert.Equal(renderer.MeasurePlan!.PageCount, renderer.DrawPlan!.PageCount); + } + + [Fact] + public void PlanIndices_startAtZero_whenTheKernelDocumentAlreadyHoldsPages() + { + var pdf = NewPdf(); + pdf.AddPage(Page); + var renderer = NewRenderer(pdf, new RunningBand("{page}/{pages}")); + var first = NewHeading("First"); + renderer.Add(new HeadingRenderer(first)); + var bytes = Render(renderer); + + Assert.Equal(2, pdf.Pages.Count); + foreach (var plan in new[] { renderer.MeasurePlan!, renderer.DrawPlan! }) + { + Assert.True(plan.TryGetTarget(first, out var page, out _)); + Assert.Equal(0, page); + } + + // The destination is on the second page of the file: index 0 of the layout is index 1 of + // the document. + Assert.Equal(1, Assert.Single(OutlineDests(bytes)).PageIndex); + } + + // ── Counters ───────────────────────────────────────────────────────────── + + [Theory] + [InlineData(false, 36, 0)] + [InlineData(true, 68, 1)] + public void Counters_forADocumentWithoutADependent(bool withBand, int layoutCalls, int measureRuns) + { + var renderer = NewRenderer(NewPdf(), withBand ? new RunningBand("Page {page}") : null); + foreach (var r in StandardContent()) + renderer.Add(r); + Render(renderer); + + Assert.Equal(layoutCalls, renderer.LayoutCalls); + Assert.Equal(measureRuns, renderer.MeasureRuns); + Assert.Equal(withBand, renderer.MeasurePlan is not null); + } + + [Fact] + public void ThousandParagraphs_makeTheSameLayoutCallsAsBefore_andOneMeasureRunWithAFooter() + { + foreach (var (band, calls, runs) in new[] { (false, 1076, 0), (true, 2116, 1) }) + { + var renderer = new DocumentRenderer(NewPdf(), new PdfRectangle(0, 0, 595, 842), new EdgeInsets(40)) + { + Footer = band ? new RunningBand("Page {page}") : null, + }; + for (var i = 0; i < 1000; i++) + renderer.Add(new ParagraphRenderer(new Paragraph(ParagraphText(i), Body))); + Render(renderer); + + Assert.Equal(calls, renderer.LayoutCalls); + Assert.Equal(runs, renderer.MeasureRuns); + } + } + + [Fact] + public void ADependentGetsAtLeastTwoMeasureRuns_andANonDependentParagraphWrapsOnce() + { + var paragraph = new ParagraphRenderer(new Paragraph(ParagraphText(0), Body)); + var dependent = new ScriptedDependent("a", "b"); + var renderer = NewRenderer(NewPdf()); + renderer.Add(paragraph); + renderer.Add(dependent); + Render(renderer); + + // Run 1 resolves to "a", run 2 to "b", and run 3 resolves nothing new. + Assert.Equal(3, renderer.MeasureRuns); + Assert.Equal(3, dependent.Resolves); + Assert.Equal(1, paragraph.WrapCalls); + // Three measuring runs and the drawing pass: one call each. + Assert.Equal(8, renderer.LayoutCalls); + } + + [Fact] + public void ADependentThatNeverChangesAfterTheFirstRun_stillGetsASecondRun() + { + var dependent = new ScriptedDependent("a"); + var renderer = NewRenderer(NewPdf()); + renderer.Add(dependent); + Render(renderer); + + Assert.Equal(2, renderer.MeasureRuns); + Assert.Equal(2, dependent.Resolves); + } + + [Fact] + public void LayoutCallsAndMeasureRuns_startOverOnEveryRunLayout() + { + var pdf = NewPdf(); + var renderer = NewRenderer(pdf, new RunningBand("f")); + renderer.Add(new Block(10)); + renderer.RunLayout(); + Assert.Equal((2, 1), (renderer.LayoutCalls, renderer.MeasureRuns)); + + // A second layout of the same renderer starts its counters over; accumulating would read + // (4, 2). + renderer.RunLayout(); + Assert.Equal((2, 1), (renderer.LayoutCalls, renderer.MeasureRuns)); + } + + [Fact] + public void WithoutADependentAndWithoutRecording_nothingIsCollected_butThePageCountsAre() + { + var renderer = NewRenderer(NewPdf(), new RunningBand("f")); + renderer.RecordPlacements = false; + renderer.Add(new HeadingRenderer(NewHeading("Unrecorded"))); + var bytes = Render(renderer); + + Assert.Empty(renderer.DrawPlan!.Placements); + Assert.Empty(renderer.MeasurePlan!.Placements); + Assert.Equal(1, renderer.DrawPlan.PageCount); + Assert.Equal(1, PageCount(bytes)); + } + + // ── Convergence and the cap ────────────────────────────────────────────── + + // The label of the target's page decides the dependent's height, and the heading comes after + // the dependent, so each height moves the heading to the other page. With the filler, a short + // dependent leaves room for the heading on page 1; a tall one does not. + private static (DocumentRenderer Renderer, LabelDependent Dependent, Heading Target) OscillatingDocument(bool oscillate) + { + var target = NewHeading("Target"); + // Odd label (page 1): tall. Even label: short. Alternates when oscillating; otherwise the + // height ignores the label and the document settles at once. + var dependent = new LabelDependent(target, label => !oscillate ? 40 : (label == "1" ? 80 : 40)); + var renderer = NewRenderer(NewPdf()); + renderer.Add(new Block(200)); + renderer.Add(dependent); + renderer.Add(new HeadingRenderer(target)); + return (renderer, dependent, target); + } + + [Fact] + public void OscillatingDependent_isRefusedAfterExactlyMaxMeasureRuns_namingTheTargetAndEveryString() + { + var (renderer, dependent, _) = OscillatingDocument(oscillate: true); + + var ex = Assert.Throws(() => Render(renderer)); + + Assert.Equal(5, DocumentRenderer.MaxMeasureRuns); + Assert.Equal(DocumentRenderer.MaxMeasureRuns, renderer.MeasureRuns); + Assert.Equal(DocumentRenderer.MaxMeasureRuns, dependent.ResolveCalls); + Assert.Equal( + "Pagination did not settle after 5 layout passes: the text for 'target' read " + + "'1', '2', '1', '2', '1'. A string that depends on where its target lands can change " + + "the layout and so move that target, and here the passes keep changing it instead of " + + "settling. The renderers have already measured, so lay the content out again in a " + + "new renderer or document.", + ex.Message); + // The drawing pass never ran: the document was refused before any page was added. + Assert.Null(renderer.DrawPlan); + } + + /// + /// A dependent whose text is taken from by resolve number. + /// + private sealed class NamedDependent(string name, Func textOf) : IRenderer, IPlanDependent + { + private string _text = ""; + private int _resolves; + + public string TargetName => name; + public string ResolvedText => _text; + + public bool Resolve(PaginationPlan plan) + { + var next = textOf(_resolves++); + if (next == _text) return false; + _text = next; + return true; + } + + public LayoutResult Layout(LayoutContext context) => LayoutResult.Full(context.Area.WithHeight(10)); + public void Draw(DrawContext context) { } + } + + private static string Flip(int n) => n % 2 == 0 ? "a" : "b"; + + [Fact] + public void FourOscillatingDependents_areRefused_namingExactlyThree() + { + var renderer = NewRenderer(NewPdf()); + for (var i = 0; i < 4; i++) + renderer.Add(new NamedDependent($"d{i}", Flip)); + + var ex = Assert.Throws(() => Render(renderer)); + + Assert.Contains("the text for 'd0' read 'a', 'b', 'a', 'b', 'a'; ", ex.Message, StringComparison.Ordinal); + Assert.Contains("the text for 'd1' read", ex.Message, StringComparison.Ordinal); + Assert.Contains("the text for 'd2' read", ex.Message, StringComparison.Ordinal); + Assert.DoesNotContain("'d3'", ex.Message, StringComparison.Ordinal); + Assert.Contains(", and 1 more. ", ex.Message, StringComparison.Ordinal); + } + + [Fact] + public void ASettledDependentBesideAnOscillatingOne_isNotNamed() + { + var renderer = NewRenderer(NewPdf()); + renderer.Add(new NamedDependent("settled", _ => "x")); + renderer.Add(new NamedDependent("moving", Flip)); + + var ex = Assert.Throws(() => Render(renderer)); + + Assert.Contains("'moving'", ex.Message, StringComparison.Ordinal); + Assert.DoesNotContain("'settled'", ex.Message, StringComparison.Ordinal); + Assert.DoesNotContain("more.", ex.Message, StringComparison.Ordinal); + } + + /// Full at 250pt on its even calls and at 20pt on its odd ones. + private sealed class TallThenShort : IRenderer + { + private int _calls; + public LayoutResult Layout(LayoutContext context) => + LayoutResult.Full(context.Area.WithHeight(_calls++ % 2 == 0 ? 250 : 20)); + public void Draw(DrawContext context) { } + } + + [Fact] + public void APageCountThatKeepsChanging_isNamedWhenNoDependentChanged() + { + var renderer = NewRenderer(NewPdf()); + renderer.Add(new NamedDependent("settled", _ => "x")); + renderer.Add(new TallThenShort()); + renderer.Add(new Block(100)); + + var ex = Assert.Throws(() => Render(renderer)); + + Assert.StartsWith( + "Pagination did not settle after 5 layout passes: the page count read 2, 1, 2, 1, 2. ", + ex.Message, StringComparison.Ordinal); + } + + [Fact] + public void ADependentThatSettles_isDrawnWithItsResolvedStrings_andSaves() + { + var (renderer, dependent, target) = OscillatingDocument(oscillate: false); + + var bytes = Render(renderer); + + Assert.Equal(2, renderer.MeasureRuns); + Assert.Equal("1", dependent.ResolvedText); + Assert.True(renderer.DrawPlan!.TryGetTarget(target, out var page, out _)); + Assert.Equal(0, page); + Assert.Equal(1, PageCount(bytes)); + } + + [Fact] + public void OscillatingDependent_throughDocument_failsTheSave_andASecondSaveSaysItCannotBeSavedAgain() + { + using var doc = new Document { PageSize = Page, Margins = Margins }; + var target = NewHeading("Target"); + doc.Add(new Block(200)); + doc.Add(new LabelDependent(target, label => label == "1" ? 80 : 40)); + doc.Add(target); + + var first = Assert.Throws(() => doc.Save(new MemoryStream())); + Assert.StartsWith("Pagination did not settle after 5 layout passes", first.Message, StringComparison.Ordinal); + + var second = Assert.Throws(() => doc.Save(new MemoryStream())); + Assert.StartsWith("This document cannot be saved again", second.Message, StringComparison.Ordinal); + } + + // ── The determinism guard ──────────────────────────────────────────────── + + /// + /// Answers 20pt for its first calls and 250pt afterwards: the + /// measuring runs see one document and the drawing pass another. A custom renderer may do this; + /// only a document with a plan-dependent renderer refuses it. + /// + private sealed class ChangesItsMind(int steadyCalls) : IRenderer + { + private int _calls; + + public LayoutResult Layout(LayoutContext context) + { + var height = _calls++ < steadyCalls ? 20 : 250; + return LayoutResult.Full(context.Area.WithHeight(height)); + } + + public void Draw(DrawContext context) { } + } + + [Fact] + public void ARendererThatPaginatesDifferentlyInTheDrawingPass_isRefused_whenADependentExists() + { + var renderer = NewRenderer(NewPdf()); + renderer.Add(new ScriptedDependent("a")); + renderer.Add(new ChangesItsMind(steadyCalls: 2)); + renderer.Add(new HeadingRenderer(NewHeading("After"))); + + var ex = Assert.Throws(() => Render(renderer)); + + Assert.StartsWith("Pagination changed between the measuring and the drawing pass", ex.Message, StringComparison.Ordinal); + } + + [Fact] + public void ARendererThatPaginatesDifferentlyInTheDrawingPass_stillSaves_withABandAndNoDependent() + { + var pdf = NewPdf(); + var renderer = NewRenderer(pdf, new RunningBand("{page} of {pages}")); + renderer.Add(new ChangesItsMind(steadyCalls: 1)); + renderer.Add(new HeadingRenderer(NewHeading("After"))); + + var bytes = Render(renderer); + + // One page counted, two drawn: a valid file whose {pages} is wrong, as before the guard + // existed. + Assert.Equal(1, renderer.MeasurePlan!.PageCount); + Assert.Equal(2, renderer.DrawPlan!.PageCount); + Assert.Equal(2, PageCount(bytes)); + } + + // ── Measured pages against drawn pages ─────────────────────────────────── + + // Built-in elements only, with a footer so that both passes run, and a heading at the end so + // the plans hold a placement. The generator is seeded and run on one thread, so the same + // documents come back every time; documents the layout refuses are counted, not skipped + // silently. + [Fact] + public void GeneratedDocuments_measureTheSamePagesAndPlacementsAsTheyDraw() + { + const int iterations = 200; + var refused = 0; + var compared = 0; + + LayoutGen.ValidDoc.Sample(spec => + { + using var doc = LayoutGen.Build(spec); + doc.Footer ??= new RunningBand("{page}/{pages}"); + var heading = new Heading("End"); + doc.Add(heading); + var renderer = doc.CreateRenderer(); + renderer.RecordPlacements = true; + + try + { + renderer.RunLayout(); + } + catch (InvalidOperationException) + { + refused++; + return; + } + + var measured = renderer.MeasurePlan!; + var drawn = renderer.DrawPlan!; + Assert.Equal(1, renderer.MeasureRuns); + Assert.Equal(measured.PageCount, drawn.PageCount); + Assert.Equal( + measured.Placements.Select(p => (p.Key, p.PageIndex, p.Y)).ToList(), + drawn.Placements.Select(p => (p.Key, p.PageIndex, p.Y)).ToList()); + Assert.True(drawn.TryGetTarget(heading, out var page, out _)); + Assert.InRange(page, 0, drawn.PageCount - 1); + compared++; + }, seed: "0N0XIzNsQ0O2", iter: iterations, threads: 1); + + Assert.Equal(iterations, refused + compared); + Assert.True(compared > iterations / 2, $"only {compared} of {iterations} documents were laid out"); + } + + // ── Diagnostics come from the drawing pass only ────────────────────────── + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void MeasuringRunsReportNoDiagnostics_soACutFooterIsReportedOnce(bool withDependent) + { + using var doc = new Document { PageSize = Page, Margins = Margins }; + var style = new TextStyle { FontSize = 10 }; + doc.Footer = new RunningBand(new string('Æ', 40), style); + doc.Add(new Paragraph("body", style)); + if (withDependent) + doc.Add(new NamedDependent("settled", n => n == 0 ? "a" : "b")); + + doc.Save(new MemoryStream()); + + // One footer and a dependent that takes three measuring runs still give one report, with + // a count of one, as with no dependent and a single run. + var item = Assert.Single(doc.Diagnostics); + Assert.Equal(LayoutDiagnosticCode.BandTruncated, item.Code); + Assert.Equal(1, item.Count); + Assert.Equal(1, item.PageNumber); + } + + // ── Retry, through Document ────────────────────────────────────────────── + + private sealed class NothingRenderer : IRenderer + { + public LayoutResult Layout(LayoutContext context) => LayoutResult.Nothing(); + public void Draw(DrawContext context) { } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ASaveThatFailsInTheMeasuringOrTheDrawingPass_cannotBeRetried(bool withBand) + { + using var doc = new Document { PageSize = Page, Margins = Margins }; + if (withBand) doc.SetFooter("f"); + doc.Add(new Paragraph("before", Body)); + doc.Add(new NothingRenderer()); + + var first = Assert.Throws(() => doc.Save(new MemoryStream())); + Assert.Contains("too tall", first.Message, StringComparison.Ordinal); + + var second = Assert.Throws(() => doc.Save(new MemoryStream())); + Assert.StartsWith("This document cannot be saved again", second.Message, StringComparison.Ordinal); + } + + [Fact] + public void ARefusedContentArea_isRetryable_andTheRetrySavesOnce() + { + using var doc = new Document { PageSize = Page, Margins = Margins }; + doc.Footer = new RunningBand("f") { Height = 400 }; + doc.Add(new Paragraph("text", Body)); + + var refusal = Assert.Throws(() => doc.Save(new MemoryStream())); + Assert.Equal("margins", refusal.ParamName); + + doc.Footer = null; + using var ms = new MemoryStream(); + doc.Save(ms); + + Assert.Equal(1, PageCount(ms.ToArray())); + } + + // ── Oracles ────────────────────────────────────────────────────────────── + + private static byte[] BandedHeadingDocument(out PaginationPlan plan, out List headings) + { + var renderer = NewRenderer(NewPdf(), new RunningBand("Page {page}")); + headings = HeadingDocument(renderer); + var bytes = Render(renderer); + plan = renderer.MeasurePlan!; + return bytes; + } + + private static string WriteTemp(byte[] bytes) + { + var path = Path.Combine(Path.GetTempPath(), $"vellum-placement-{Guid.NewGuid():N}.pdf"); + File.WriteAllBytes(path, bytes); + return path; + } + + [Fact] + public void Qpdf_checksTheFile_andItsOutlinePagesAreThePlansPages() + { + var bytes = BandedHeadingDocument(out var plan, out var headings); + var path = WriteTemp(bytes); + try + { + ExternalTool.TryRun("qpdf", ["--check", path], out var exit, out var stdout, out var stderr, out var timedOut); + Assert.False(timedOut, "qpdf --check timed out, or its output could not be fully captured."); + Assert.Contains("No syntax or stream encoding errors found", stdout, StringComparison.Ordinal); + Assert.True(exit == 0, $"qpdf --check exited {exit}.\n{stdout}\n{stderr}"); + + ExternalTool.TryRun("qpdf", ["--json", "--json-key=outlines", "--json-key=pages", path], + out exit, out var json, out stderr, out timedOut); + Assert.False(timedOut, "qpdf --json timed out."); + Assert.True(exit == 0, $"qpdf --json exited {exit}.\n{stderr}"); + + using var document = JsonDocument.Parse(json); + var pages = document.RootElement.GetProperty("pages").EnumerateArray() + .Select(p => p.GetProperty("object").GetString()!) + .ToList(); + var outlines = document.RootElement.GetProperty("outlines").EnumerateArray().ToList(); + Assert.Equal(headings.Count, outlines.Count); + for (var i = 0; i < headings.Count; i++) + { + var destination = outlines[i].GetProperty("dest")[0].GetString()!; + Assert.True(plan.TryGetTarget(headings[i], out var planned, out _)); + Assert.Equal(planned, pages.IndexOf(destination)); + } + } + finally + { + File.Delete(path); + } + } + + [Fact] + public void Pdftotext_findsOneFormFeedPerPage_andTheBandsLastPageNumber() + { + var bytes = BandedHeadingDocument(out var plan, out _); + var path = WriteTemp(bytes); + try + { + ExternalTool.TryRun("pdftotext", ["-layout", path, "-"], out var exit, out var text, out var stderr, out var timedOut); + Assert.False(timedOut, "pdftotext timed out."); + Assert.True(exit == 0, $"pdftotext exited {exit}.\n{stderr}"); + + // The measuring run's page count is the number of pages the file has, and the last + // page carries the band that names it. + Assert.Equal(plan.PageCount, text.Count(c => c == '\f')); + Assert.Contains($"Page {plan.PageCount}", text, StringComparison.Ordinal); + } + finally + { + File.Delete(path); + } + } +}