From 5d3f1d6f7ff651564d52d7ba872dac7fe942dbec Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sat, 21 Nov 2026 22:23:33 +0100 Subject: [PATCH 01/48] fix(layout): read tabs, line breaks and form feeds in cells and bands A table cell split its text on U+0020 only, so a tab reached glyph lookup as glyph 0 (embedded font) or a raw 0x09 byte (Standard 14), and a line feed was one line holding glyph 0 or a string-escaped newline. A running band passed a form feed to the font as it was. A cell now breaks lines as a paragraph does (CR LF, CR and LF each end a line) and draws every other white-space control character as a space. Automatic columns are sized from the widest line. A band draws those characters as spaces and measures them as spaces. Header rows and RowSpan groups are never cut between lines, so honouring breaks there could turn a table that saved into a too-tall refusal. A cell of such rows that would do so keeps the unbroken layout, with each break drawn as a space, and is listed as the new warning CellBreakDrawnAsSpace (301). Closes #611 --- CHANGELOG.md | 40 +- src/VellumPdf.Layout/Core/LayoutText.cs | 86 ++ src/VellumPdf.Layout/Document.cs | 4 +- src/VellumPdf.Layout/Elements/BandTemplate.cs | 9 + src/VellumPdf.Layout/Elements/RunningBand.cs | 14 +- src/VellumPdf.Layout/Elements/Table/Cell.cs | 32 +- src/VellumPdf.Layout/Elements/Table/Row.cs | 5 +- .../Elements/Table/TableElement.cs | 5 + src/VellumPdf.Layout/LayoutDiagnostic.cs | 1 + src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 26 +- src/VellumPdf.Layout/PublicAPI.Unshipped.txt | 1 + .../Rendering/Table/TableGridResolver.cs | 36 +- .../Rendering/Table/TableRenderer.cs | 294 +++++- .../VellumPdf.Layout.Tests/PageBreakTests.cs | 10 +- .../TableCellBreakTests.cs | 848 ++++++++++++++++++ .../VellumPdf.Layout.Tests.csproj | 1 + 16 files changed, 1340 insertions(+), 72 deletions(-) create mode 100644 src/VellumPdf.Layout/Core/LayoutText.cs create mode 100644 tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index e30997a5b..b4e852c03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- **`LayoutDiagnosticCode.CellBreakDrawnAsSpace` (301).** A table cell of a header row, or of rows + joined by a `RowSpan`, holds a line break that was drawn as a space because honouring it would + have made those rows taller than a page. A warning: no text is lost, and `StrictDiagnostics` + saves. `Count` is the number of times the cell was drawn, so a repeated header row counts once + per page. See the entry for #611 under Fixed. + - **`Preformatted`, a block that keeps every space and tab (#591).** `Document.Add(Preformatted)` draws text whose spacing is its meaning: command blocks, configuration, ASCII tables. The default style is Courier at 10 pt. `Document.SetDefaultFont` does not apply. @@ -282,8 +288,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). a null `PageBreak` throws `ArgumentNullException` from `Document.Add`. - A document that uses no break saves byte for byte as before. A form feed (U+000C) in text does not start a page: a paragraph, a heading and a list item draw it as a space, and a table cell - and a running band write it to the font as it is, as before. A custom renderer that returns a - zero-height `Partial` still forces a page. + and a running band wrote it to the font as it was until #611 made them draw it as a space too. + A custom renderer that returns a zero-height `Partial` still forces a page. - **Tab stops with leaders (#298).** `Paragraph.TabStops` takes a list of `TabStop` values, and a tab character in the text then places the text after it at the first stop to the right of the end @@ -425,6 +431,36 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **A tab, a line break or a form feed in a table cell or a running band no longer reaches glyph + lookup (#611, #613).** A cell split its text on spaces only, so a tab was written as glyph 0 + in an embedded font (the ToUnicode map held `<0000> <0009>`, and veraPDF failed PDF/A-2u clause + 6.2.11.8) and as a raw 0x09 byte in a Standard 14 font, and a line feed was one line holding glyph + 0, or a string-escaped `\n`. A cell now reads its text as a paragraph does. A carriage return and + line feed pair, a lone carriage return and a lone line feed each end a line, and an empty line + between two of them, or after the last, is a blank line. Every other white-space control + character (a tab, a form feed, a line tabulation, a next-line character, U+2028 and U+2029) is + drawn as one space. A column sized automatically is as wide as the widest line. The no-break + spaces and the other space separators, such as U+2003, are written as before. + A running band draws the same characters as spaces, so the form feed of #613 item 34 is a space + there too, and a band's text is measured and cut as drawn. + **Deliberate output changes:** `AB` in a cell is `(A B)` in Standard 14 and glyph 3 between + the two letters in an embedded font, with no `<0000>` entry in the ToUnicode map. `line1line2` + is two show strings, the second one leading lower, in a row 14.4 + 14.4 + 8 pt tall at 12 pt, + where it was one. A cell with none of these characters, in a table with none of them, saves to + the same bytes as before. A table whose cell holds a line break gets taller rows and different + automatic column widths, and a paragraph is unchanged. + - **A header row, or rows joined by a `RowSpan`, whose breaks would make them taller than a page + keep the one-line layout.** Those rows are never cut between their lines, so honouring the + breaks would turn a table that saved into a too-tall refusal. A cell of them that holds a + carriage return or line feed is wrapped at spaces alone and sized from its whole text, as + 2.3.3 did, with each break drawn as a space, and the save lists the cell as the new + `LayoutDiagnosticCode.CellBreakDrawnAsSpace` (301, a warning, so `StrictDiagnostics` still + saves). A header row of 46 two-letter lines, 560pt tall, keeps its lines on a 580pt page + beside a 20pt row; one of 47 does not. Every other row keeps its breaks and is cut between + its lines when it is taller than a page. When a header or a group is still too tall, the + header's cells go the same way, and then every cell that holds a tab or a form feed, so a table + that 2.3.3 saved keeps its 2.3.3 row heights and is not refused. A renderer laid out through a + context built with the public constructor knows no page and keeps every break. - **`/FontBBox` of an embedded font is the font's own bounding box (#596).** The descriptor of every embedded TrueType and OpenType font held `[0, hhea descender, 1000 * 1000 / unitsPerEm, hhea ascender]`: a zero for xMin and a constant for xMax, so DejaVu Sans, Liberation Sans and Liberation diff --git a/src/VellumPdf.Layout/Core/LayoutText.cs b/src/VellumPdf.Layout/Core/LayoutText.cs new file mode 100644 index 000000000..08bb7555c --- /dev/null +++ b/src/VellumPdf.Layout/Core/LayoutText.cs @@ -0,0 +1,86 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; + +namespace VellumPdf.Layout.Core; + +/// +/// How a table cell and a running band read the white space in their text, so that a character +/// no font draws never reaches glyph lookup. A paragraph applies the same line-break rule in +/// ; this class is the cell's and the band's copy of it. +/// +/// +/// A character is a control space when holds for it and it is +/// not in the Unicode category Space Separator: the C0 and C1 controls tab, line feed, line +/// tabulation, form feed, carriage return and next line, and the line and paragraph separators +/// U+2028 and U+2029. The no-break spaces and the other space separators, such as U+2003 EM SPACE, +/// are not control spaces: a font draws them, so they are left as written. +/// +internal static class LayoutText +{ + /// + /// True for a white-space character that no font draws a glyph for: every character for which + /// is true except the space separators (U+0020, the + /// no-break spaces and the Unicode space separators). + /// + internal static bool IsControlSpace(char c) => + char.IsWhiteSpace(c) && char.GetUnicodeCategory(c) != UnicodeCategory.SpaceSeparator; + + /// True when holds a control space. + internal static bool HasControlSpace(string? text) + { + if (text is null) return false; + foreach (var c in text) + if (IsControlSpace(c)) return true; + return false; + } + + /// True when holds a carriage return or a line feed. + internal static bool HasLineBreak(string? text) => + text is not null && text.AsSpan().IndexOfAny('\r', '\n') >= 0; + + /// + /// Splits into hard lines: a carriage return followed by a line feed, a + /// lone carriage return and a lone line feed each end one. A trailing break leaves a last, + /// empty line. Text with no break is returned as the one line it is. + /// + internal static string[] SplitHardLines(string text) + { + if (!HasLineBreak(text)) return [text]; + + var lines = new List(); + var start = 0; + for (var i = 0; i < text.Length; i++) + { + var c = text[i]; + if (c != '\r' && c != '\n') continue; + lines.Add(text.Substring(start, i - start)); + if (c == '\r' && i + 1 < text.Length && text[i + 1] == '\n') i++; + start = i + 1; + } + lines.Add(text.Substring(start)); + return [.. lines]; + } + + /// + /// Returns with every control space replaced by U+0020, or the same + /// instance when it holds none. + /// + internal static string ControlSpacesToSpaces(string text) + { + var at = -1; + for (var i = 0; i < text.Length; i++) + { + if (IsControlSpace(text[i])) { at = i; break; } + } + if (at < 0) return text; + + return string.Create(text.Length, (text, at), static (span, state) => + { + state.text.AsSpan().CopyTo(span); + for (var i = state.at; i < span.Length; i++) + if (IsControlSpace(span[i])) span[i] = ' '; + }); + } +} diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index c2b0b6444..f6fbd249e 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -118,7 +118,9 @@ public Document() { } /// selects a Standard 14 font under a conformance claim), /// (mirroring ), /// (a preformatted line split with - /// a marker; a warning, which saves) + /// a marker; a warning, which saves), + /// (a table cell's line break drawn as + /// a space; also a warning) /// and . Every other one saves by /// default; only refuses it, and a later major version refuses /// them all. diff --git a/src/VellumPdf.Layout/Elements/BandTemplate.cs b/src/VellumPdf.Layout/Elements/BandTemplate.cs index 2c6b43e64..21988781c 100644 --- a/src/VellumPdf.Layout/Elements/BandTemplate.cs +++ b/src/VellumPdf.Layout/Elements/BandTemplate.cs @@ -1,6 +1,8 @@ // Copyright © Timothy van der Ham (@Tim81) // SPDX-License-Identifier: Apache-2.0 +using VellumPdf.Layout.Core; + namespace VellumPdf.Layout.Elements; /// @@ -212,7 +214,14 @@ private void Produce(int count) var take = Math.Min(runLength - _offset, count - _produced); if (kind < 0) + { template.Source.CopyTo(template.Starts[_segment] + _offset, _buffer, _produced, take); + + // A band draws one line, so a tab, a line break or a form feed in the template is a + // space: left as written it would reach the font as a control character. + for (var i = _produced; i < _produced + take; i++) + if (LayoutText.IsControlSpace(_buffer[i])) _buffer[i] = ' '; + } else _values[kind].CopyTo(_offset, _buffer, _produced, take); diff --git a/src/VellumPdf.Layout/Elements/RunningBand.cs b/src/VellumPdf.Layout/Elements/RunningBand.cs index 13d1ae9cd..2c4317da8 100644 --- a/src/VellumPdf.Layout/Elements/RunningBand.cs +++ b/src/VellumPdf.Layout/Elements/RunningBand.cs @@ -18,7 +18,10 @@ public sealed class RunningBand { /// Text template — may contain {page} and/or {pages}. /// - /// Not checked when it is set: the constructor stores a null template, and the save throws + /// A band is one line: a tab, a line break, a form feed or any other white-space control + /// character in the template is drawn as one space each, and is measured as one, so no control + /// character reaches the font from it. + /// Not checked when it is set: the constructor stores a null template, and the save throws /// where the band is first drawn. A template that does not /// fit the content box is truncated, and refused only in strict mode; /// says when it @@ -28,17 +31,18 @@ public sealed class RunningBand /// set, the save throws /// from the save, not from this property, and 3.0 will /// refuse it always. Pass an empty string for a band that draws no text, never - /// . + /// . /// The cut bounds the advance width, not the ink. Side bearings and italic /// overhang can still paint a little past it. Nothing in this package sets a clip path. /// Attention: truncation does nothing for text whose glyphs measure zero, because /// each character is measured at the advance of the glyph the font gives it. Every glyph of /// and /// measures zero, and so do the control - /// characters U+0000 to U+001F in every standard-14 font. Any length of such text fits and is + /// characters U+0000 to U+001F in every standard-14 font, except U+0009 to U+000D, which the + /// band draws as spaces. Any length of such text fits and is /// drawn in full. Courier measures U+007F at 600 units where Helvetica measures it at zero. In - /// an embedded font the control characters take the font's own widths: Calibri measures U+0000 - /// and U+000D at zero, and Arial measures every C0 control at 750 units. + /// an embedded font the other control characters take the font's own widths: Calibri measures + /// U+0000 at zero, and Arial measures every C0 control at 750 units. /// You get one report per band per render, naming the page that lost the most rather /// than the first page cut. A {page} or {pages} token lengthens the resolved /// text as the number gains digits, so the worst page is the one that tells you how much diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 433d55630..89924b43a 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -20,12 +20,32 @@ public sealed class Cell /// the cell then draws no text, and the save refuses it only where a column is sized /// automatically, as the constructor describes. /// Spaces are the only break points between words, and a word wider than the cell is broken - /// between characters. A line feed, carriage return or tab is not a break. In a standard-14 - /// font each is written into the cell as it is; in an embedded font each is drawn as whatever - /// glyph the font's character map gives it, which is .notdef (glyph 0) when the map has no - /// entry. The save lists each such character as - /// , and - /// refuses it; see . + /// between characters. + /// A carriage return and line feed pair, a lone carriage return and a lone line feed + /// each end a line, as they do in a . An empty line between + /// two of them, or after the last, is a blank line one leading tall. A column sized + /// automatically is as wide as the widest line, and no narrower than the widest word on any + /// line. Every other white-space control character, which is a tab, a form feed, a line + /// tabulation, a next-line character, U+2028 and U+2029, is drawn as one space, so it + /// reaches no font as a control character. The no-break spaces and the other space + /// separators, such as U+2003, are written as they are. + /// A control character that is not white space, such as U+0001, is written as it is: in a + /// standard-14 font as its WinAnsi code, and in an embedded font as whatever glyph the font's + /// character map gives it, which is .notdef (glyph 0) when the map has no entry. The save lists + /// each such character as , and + /// refuses it; see . + /// A cell has no tab stops, so a tab is one space. A line break in a cell of a header + /// row, or of rows joined by a , is drawn as a space when honouring it + /// would make those rows taller than a page, because such rows are never cut between their + /// lines. The cell is then wrapped at spaces alone and sized from its whole text, and each + /// break in it is a space, and the save lists it as + /// , a warning that + /// saves. Every other cell keeps its breaks, and a + /// row of them that is taller than a page is cut between its lines. Do not pass a line + /// break in a header row or a span group that is that tall and expect the lines to be drawn: + /// move the text to a row that can be cut, or shorten it. A renderer you lay out without the + /// document, through a built with the public constructor, knows no + /// page and keeps every break. /// /// public string Content { get; } diff --git a/src/VellumPdf.Layout/Elements/Table/Row.cs b/src/VellumPdf.Layout/Elements/Table/Row.cs index 21ca890b6..9b6829e7a 100644 --- a/src/VellumPdf.Layout/Elements/Table/Row.cs +++ b/src/VellumPdf.Layout/Elements/Table/Row.cs @@ -87,8 +87,9 @@ public Row AddCell(Cell cell) /// Adds a text cell to the row. Returns this row. /// - /// Creates the cell with and adds it, so a line break in the text is - /// not honoured; see . A null is added as an + /// Creates the cell with and adds it, so a line break in the text + /// ends a line, a tab is a space, and the rest is as describes. A + /// null is added as an /// empty cell. In a row that a cell /// above covers through , the row's cells fill the columns left over, /// in order, and a cell past the last column is not drawn, though its text is still measured. diff --git a/src/VellumPdf.Layout/Elements/Table/TableElement.cs b/src/VellumPdf.Layout/Elements/Table/TableElement.cs index 1e0a024ba..0cdc06165 100644 --- a/src/VellumPdf.Layout/Elements/Table/TableElement.cs +++ b/src/VellumPdf.Layout/Elements/Table/TableElement.cs @@ -30,6 +30,11 @@ namespace VellumPdf.Layout.Elements.Table; /// page, so the cells of a cut row appear on each page it spans: a cell that holds a line on the /// page is a TD, or a TH in a header row, and a cell with no line on the page is an /// empty TD, also in a header row. +/// A carriage return or line feed in a cell ends a line, so it makes the row taller. A +/// header row, or rows joined by a , whose breaks would make them taller +/// than a page are never cut, so the cells of them that hold a break are wrapped at spaces alone +/// with each break drawn as a space, and the save lists each as +/// ; see . /// These are refused, and never cut. /// throws whose message starts with the standard /// too-tall text and ends with a sentence naming the rows, for: header rows that together do not diff --git a/src/VellumPdf.Layout/LayoutDiagnostic.cs b/src/VellumPdf.Layout/LayoutDiagnostic.cs index d8911f936..ec9aa1551 100644 --- a/src/VellumPdf.Layout/LayoutDiagnostic.cs +++ b/src/VellumPdf.Layout/LayoutDiagnostic.cs @@ -85,6 +85,7 @@ internal LayoutDiagnostic( { LayoutDiagnosticCode.DiagnosticsDropped => LayoutDiagnosticSeverity.Warning, LayoutDiagnosticCode.PreformattedLineWrapped => LayoutDiagnosticSeverity.Warning, + LayoutDiagnosticCode.CellBreakDrawnAsSpace => LayoutDiagnosticSeverity.Warning, _ => LayoutDiagnosticSeverity.Error, }; diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index b8d84e014..1e94674e7 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -23,8 +23,8 @@ public enum LayoutDiagnosticCode { // Reserved, not defined here, so that later members do not collide: // 105 SymbolFontMeasuredAsZero (Error), 203 ListIndentClamped, 204 ListDepthCapped, 205 - // ListEntriesCapped, 206 ListEntrySkipped (all Error), 301 ControlCharacterInCell - // (Warning), 302 SurplusCell (Error), 402 UnknownBandToken, one 7xx member for a link + // ListEntriesCapped, 206 ListEntrySkipped (all Error), 302 SurplusCell (Error), 402 + // UnknownBandToken, one 7xx member for a link // dropped from a cell or band under a PDF/UA claim, and the 8xx block for pagination reports. /// @@ -63,7 +63,7 @@ public enum LayoutDiagnosticCode /// renderer's own bytes on the page, is not seen. Text a font draws through a stand-in glyph, /// such as U+202F in a font without it, is not glyph 0 and is not reported. A Standard 14 /// font has no glyph ids here: a character it cannot encode is - /// , and a control character such as a tab is written as + /// , and a control character such as U+0001 is written as /// its WinAnsi code, which the font has no glyph for and which is not reported. /// What is drawn is whatever the font's .notdef glyph holds. Do not pass /// text the font cannot draw to a PDF/A or PDF/UA document; give the element a font that covers @@ -116,6 +116,26 @@ public enum LayoutDiagnosticCode /// TabStopBeyondWidth = 106, + /// + /// A table cell holds a line break, and the save drew it as a space because honouring it + /// would have made rows that cannot be cut between their lines taller than a page. + /// is the number of times the cell was drawn, so a header + /// row that repeats on every page counts once per page, and the message names the row and the + /// cell, counted from zero in the order they were added. + /// + /// + /// No text is lost, so this is a warning and strict mode saves. The rows in question are + /// the leading header rows, which repeat on every page and are never cut, and the rows joined + /// by a , which are never cut either. When the + /// breaks of such a row, honoured, would leave it taller than the page, each cell of it that + /// holds a carriage return or a line feed is wrapped at spaces alone and sized from its whole + /// text, as a cell with no line break is, and each break in it is drawn as a space. A row that is + /// cut between its lines, and any other table, keeps its breaks and is not reported. + /// Do not pass a header row or a span group whose line breaks do not fit one page: put + /// the breaks in rows that can be cut, or shorten the text. + /// + CellBreakDrawnAsSpace = 301, + /// /// A list item that is a child of a child, or deeper, holds a null text, and the save drew /// nothing of it. is the number of such items the list's diff --git a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt index f03156ea0..a38df0cd6 100644 --- a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt +++ b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt @@ -100,4 +100,5 @@ VellumPdf.Layout.Elements.Preformatted.TabWidth.get -> int VellumPdf.Layout.Elements.Preformatted.TabWidth.init -> void VellumPdf.Layout.Elements.Preformatted.Text.get -> string! VellumPdf.Layout.LayoutDiagnosticCode.PreformattedLineWrapped = 104 -> VellumPdf.Layout.LayoutDiagnosticCode +VellumPdf.Layout.LayoutDiagnosticCode.CellBreakDrawnAsSpace = 301 -> VellumPdf.Layout.LayoutDiagnosticCode VellumPdf.Layout.LayoutElementKind.Preformatted = 11 -> VellumPdf.Layout.LayoutElementKind diff --git a/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs b/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs index 0b901ef18..458691745 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs @@ -30,6 +30,13 @@ internal sealed class TableGridResolver public double[] ColWidths { get; private set; } = []; public int ColCount { get; private set; } + /// + /// The cells, as (row, cell) positions in authoring order, that are sized from their whole + /// text, control characters included, because the table could not hold their line breaks. Null + /// when every cell's breaks are honoured. + /// + public IReadOnlySet<(int Row, int Cell)>? OneLineCells { get; init; } + public void Resolve(TableElement table, double availableWidth) { // The column count is the widest row, not merely the first (#480 section 1). Nothing stops @@ -234,7 +241,7 @@ private double[] ReconcileExplicitWidths(TableElement table, double available, i /// Distributes across every column proportionally to its /// max-content width, floored at its own min-content (longest word) width (#468). /// - private static double[] AutoWidth(TableElement table, double available, int cols) + private double[] AutoWidth(TableElement table, double available, int cols) { var (minW, maxW) = ContentWidths(table, cols); @@ -277,26 +284,39 @@ private static void ScaleToFit(double[] widths, double available) /// fully-auto path and the residual distribution runs for /// the columns an explicit array leaves auto. /// - private static (double[] MinW, double[] MaxW) ContentWidths(TableElement table, int cols) + private (double[] MinW, double[] MaxW) ContentWidths(TableElement table, int cols) { var minW = new double[cols]; var maxW = new double[cols]; var style = table.DefaultCellStyle ?? TextStyle.Default; - foreach (var row in table.Rows) + for (var r = 0; r < table.Rows.Count; r++) { var col = 0; - foreach (var cell in row.Cells) + var cells = table.Rows[r].Cells; + for (var c = 0; c < cells.Count; c++) { + var cell = cells[c]; if (col >= cols) break; var cellStyle = cell.Style ?? style; if (cell.Content is null) throw new ArgumentNullException("content", "A table cell has a null text and a column is sized automatically."); - var words = cell.Content.Split(' '); - var longest = words.Max(w => cellStyle.FontRef.MeasureString(w, cellStyle.FontSize)); - var full = cellStyle.FontRef.MeasureString(cell.Content, cellStyle.FontSize) - + cell.Padding.Horizontal; + + // The widest word and the widest line of the lines the cell is measured in. A cell + // of one line, which is every cell that holds no line break, measures as it always has. + var lines = TableRenderer.CellLines(cell.Content, honourBreaks: OneLineCells?.Contains((r, c)) != true); + var longest = 0.0; + var widest = 0.0; + for (var l = 0; l < lines.Length; l++) + { + var words = lines[l].Split(' '); + var lineLongest = words.Max(w => cellStyle.FontRef.MeasureString(w, cellStyle.FontSize)); + var lineWidth = cellStyle.FontRef.MeasureString(lines[l], cellStyle.FontSize); + longest = l == 0 ? lineLongest : Math.Max(longest, lineLongest); + widest = l == 0 ? lineWidth : Math.Max(widest, lineWidth); + } + var full = widest + cell.Padding.Horizontal; var share = cell.ColSpan; for (var s = 0; s < share && col + s < cols; s++) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index b03c24f02..2b429948a 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -52,6 +52,13 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource private RowSlice? _headSlice; private RowSlice? _tailSlice; + // The cells, as (row, cell) in authoring order, that this table lays out unbroken: wrapped at + // spaces alone and measured with their control characters, and drawn with each of those as a + // space, because honouring their breaks would make rows that cannot be cut taller than a page. + // Layout writes it and gives it to the renderers that draw the pages; null when every break is + // kept. + private HashSet<(int Row, int Cell)>? _oneLine; + /// The lines each cell of one row wraps into, at one table width. private sealed class RowLines(int row, double width, List?[] cells) { @@ -132,6 +139,12 @@ public TableRenderer(TableElement table, int startRow = 0) /// cut keeps cutting under such a context only at the width it was cut at. At another width /// the saved lines are dropped and the row is laid out again from its first line, which /// under a context without the box is not cut. + /// A carriage return or line feed in a cell ends a line. When honouring the breaks of a + /// header row or of rows joined by a would make those rows taller + /// than a page, which is known only under a context the document built, the cells that hold + /// them are wrapped at spaces alone and drawn with each break a space, and are reported as + /// . A context built with the public + /// constructor of keeps every break. /// These are refused with the too-tall exception, extended with a sentence naming the /// rows or the cell, and are never cut: the repeated header rows when they do not fit a page; /// a row that declares a above one, or lies under one; a row with a @@ -187,10 +200,16 @@ public LayoutResult Layout(LayoutContext context) && _colWidths.Length > 0 && _rowHeights.Length == rows.Count; + // The boxes a fresh page offers, when the caller says so. A row is cut between its lines + // only when neither box would hold it whole, so a row that fits one of them still moves to + // the next page intact. + var fresh = FreshBoxes(context); + if (!resumed) { _resumeLines = null; _resumeFrom = null; + _oneLine = null; // Before the grid resolves: a ColSpan of zero gives a column count of zero, so Resolve // returns no widths and Layout gives up below, and the caller was told the table was too @@ -204,40 +223,22 @@ public LayoutResult Layout(LayoutContext context) LayoutValidation.ValidateLineWidthIsFinite(_table.BorderWidth, "A table"); - var grid = new TableGridResolver(); - grid.Resolve(_table, area.Width); - _colWidths = grid.ColWidths; + ResolveGrid(area.Width, style); - // #481's third refusal, and the one route to it that no span check covers: a table with no - // rows, or rows holding no cells, resolves to no columns without any bad ColSpan, and - // reporting Nothing here made DocumentRenderer blame the page size. - LayoutValidation.ValidateColumnCount(_colWidths.Length); - - // Compute row heights - _rowHeights = new double[rows.Count]; - - for (var r = 0; r < rows.Count; r++) + // A line break makes a cell taller than a layout that draws it on one line, and a tab + // is one space wide where the raw character was measured at its own width. Rows that + // cannot be cut between their lines must not become too tall for a page because of + // either, so the cells that would make them so are laid out unbroken, and the grid and + // the heights are taken again. Each pass adds cells, so this ends; most tables, which + // hold no control white space, take no second pass. + if (fresh is not null && AnyControlSpace(rows)) { - var row = rows[r]; - var maxH = 0.0; - var col = 0; - var cellIndex = -1; - foreach (var cell in row.Cells) + while (CellsToReadAsOneLine(fresh, style) is { } more) { - cellIndex++; - if (col >= _colWidths.Length) break; - var cs = cell.Style ?? style; - // The authoring index, not col: the two diverge as soon as an earlier cell spans - // more than one column, and naming the column points at a cell nobody wrote. - LayoutValidation.ValidateFontSize(cs, $"Table row {r}, cell {cellIndex}"); - var colW = ColSpanWidth(col, cell.ColSpan); - var innerW = colW - cell.Padding.Horizontal; - var lines = WordWrapCount(cell.Content, cs, Math.Max(1, innerW)); - var cellH = lines * cs.EffectiveLeading + cell.Padding.Vertical; - maxH = Math.Max(maxH, cellH); - col += cell.ColSpan; + _oneLine ??= []; + _oneLine.UnionWith(more); + ResolveGrid(area.Width, style); } - _rowHeights[r] = maxH; } } @@ -254,10 +255,6 @@ public LayoutResult Layout(LayoutContext context) // that continues into the next row. var rowspanBlockedAfter = BuildRowspanBlockedSet(rows, lastHeaderRow); - // The boxes a fresh page offers, when the caller says so. A row is cut between its lines - // only when neither box would hold it whole, so a row that fits one of them still moves to - // the next page intact. - var fresh = FreshBoxes(context); var refusal = new RefusalContext(fresh, headerRowIndices, headerHeight, lastHeaderRow); var y = area.Y; @@ -341,19 +338,177 @@ public LayoutResult Layout(LayoutContext context) _occupied = _occupied, _headSlice = head, _tailSlice = tail, + _oneLine = _oneLine, }; var overflow = tail is null - ? new TableRenderer(_table, lastFit + 1) { _colWidths = _colWidths, _rowHeights = _rowHeights } + ? new TableRenderer(_table, lastFit + 1) { _colWidths = _colWidths, _rowHeights = _rowHeights, _oneLine = _oneLine } : new TableRenderer(_table, tail.Row) { _colWidths = _colWidths, _rowHeights = _rowHeights, _resumeLines = tail.Source, _resumeFrom = tail.Next(), + _oneLine = _oneLine, }; return LayoutResult.Partial(_occupied, split, overflow); } + /// + /// Resolves the column widths and every row's height, reading the breaks of the cells in + /// _oneLine unbroken. The checks run in the order the exceptions are documented in. + /// + private void ResolveGrid(double areaWidth, TextStyle style) + { + var rows = _table.Rows; + var grid = new TableGridResolver { OneLineCells = _oneLine }; + grid.Resolve(_table, areaWidth); + _colWidths = grid.ColWidths; + + // #481's third refusal, and the one route to it that no span check covers: a table with no + // rows, or rows holding no cells, resolves to no columns without any bad ColSpan, and + // reporting Nothing here made DocumentRenderer blame the page size. + LayoutValidation.ValidateColumnCount(_colWidths.Length); + + // Compute row heights + _rowHeights = new double[rows.Count]; + + for (var r = 0; r < rows.Count; r++) + { + var row = rows[r]; + var maxH = 0.0; + var col = 0; + var cellIndex = -1; + foreach (var cell in row.Cells) + { + cellIndex++; + if (col >= _colWidths.Length) break; + var cs = cell.Style ?? style; + // The authoring index, not col: the two diverge as soon as an earlier cell spans + // more than one column, and naming the column points at a cell nobody wrote. + LayoutValidation.ValidateFontSize(cs, $"Table row {r}, cell {cellIndex}"); + var colW = ColSpanWidth(col, cell.ColSpan); + var innerW = colW - cell.Padding.Horizontal; + var lines = WordWrapCount(cell.Content, cs, Math.Max(1, innerW), HonoursBreaks(r, cellIndex)); + var cellH = lines * cs.EffectiveLeading + cell.Padding.Vertical; + maxH = Math.Max(maxH, cellH); + col += cell.ColSpan; + } + _rowHeights[r] = maxH; + } + } + + /// + /// True when the cell's line breaks are kept; false when the table lays the cell out unbroken. + /// + private bool HonoursBreaks(int row, int cell) => _oneLine?.Contains((row, cell)) != true; + + private static bool AnyControlSpace(IReadOnlyList rows) + { + foreach (var row in rows) + foreach (var cell in row.Cells) + if (LayoutText.HasControlSpace(cell.Content)) return true; + return false; + } + + // ── Cells that read their breaks as spaces ── + + /// + /// The cells that hold a line break and sit in rows that cannot be cut between their lines, + /// when those rows do not fit a fresh page with the breaks honoured, or null when there are + /// none that are not already laid out unbroken. The rows are the repeated header rows and the + /// rows joined by a ; the document would refuse them as too tall. + /// A group of rows is relieved first by its own cells. When it holds none left, the header + /// rows' cells go next, because they take room from every group under them. When those hold + /// none either, every cell that holds a tab or another control white-space character is laid out + /// unbroken too, because the width it takes from a column then no longer differs from a plain + /// text's; the rows then measure as a table with no line break measures them. + /// + private HashSet<(int Row, int Cell)>? CellsToReadAsOneLine(LayoutBox[] fresh, TextStyle style) + { + var rows = _table.Rows; + var header = FindHeaderRowIndices(rows); + var lastHeaderRow = header.Count > 0 ? header[^1] + 1 : 0; + var headerHeight = 0.0; + foreach (var i in header) headerHeight += _rowHeights[i]; + + HashSet<(int Row, int Cell)>? found = null; + + // True when a cell was added that the table did not already lay out unbroken. A cell + // qualifies when it holds a line break, or, with anyControlSpace, any control white space, + // which changes a column's width as well. + bool Collect(int first, int last, bool anyControlSpace = false) + { + var added = false; + for (var r = first; r <= last && r < rows.Count; r++) + { + var cells = rows[r].Cells; + for (var c = 0; c < cells.Count; c++) + { + var text = cells[c].Content; + if (!HonoursBreaks(r, c)) continue; + if (!(anyControlSpace ? LayoutText.HasControlSpace(text) : LayoutText.HasLineBreak(text))) continue; + added |= (found ??= []).Add((r, c)); + } + } + return added; + } + + // The header rows are too tall when they do not fit a page, and when they leave a row below + // them no room for one line of one of its cells. + if (header.Count > 0 && (!FitsFresh(fresh, 0, headerHeight) || LeavesNoRoomForALine(fresh, headerHeight, lastHeaderRow, style)) + && !Collect(0, header[^1])) + Collect(0, rows.Count - 1, anyControlSpace: true); + + foreach (var (first, last) in SpanGroups(lastHeaderRow)) + { + var height = 0.0; + for (var i = first; i <= last; i++) height += _rowHeights[i]; + if (FitsFresh(fresh, headerHeight, height)) continue; + if (!Collect(first, last) && !Collect(0, header.Count > 0 ? header[^1] : -1)) + Collect(0, rows.Count - 1, anyControlSpace: true); + } + + return found; + } + + /// + /// True when a row from on has a cell that cannot hold one line + /// under the header rows. + /// + private bool LeavesNoRoomForALine(LayoutBox[] fresh, double headerHeight, int firstDataRow, TextStyle style) + { + for (var r = firstDataRow; r < _table.Rows.Count; r++) + if (CellBeyondProgress(r, fresh, headerHeight, style) is not null) return true; + return false; + } + + /// + /// The runs of rows held together by declarations, from the first + /// data row on, merged where one reaches into another. The same runs as + /// finds one at a time, found in one pass over the rows. + /// + private List<(int First, int Last)> SpanGroups(int firstDataRow) + { + var rows = _table.Rows; + var groups = new List<(int First, int Last)>(); + for (var q = 0; q < rows.Count; q++) + { + var reach = 1; + foreach (var cell in rows[q].Cells) reach = Math.Max(reach, cell.RowSpan); + if (reach <= 1) continue; + + var end = (int)Math.Min((long)q + reach - 1, rows.Count - 1); + var start = Math.Max(q, firstDataRow); + if (end < start) continue; + + if (groups.Count > 0 && start <= groups[^1].Last) + groups[^1] = (groups[^1].First, Math.Max(groups[^1].Last, end)); + else + groups.Add((start, end)); + } + return groups; + } + // ── Cutting a row between its lines ── /// What a layout call knows about the page a refused row would have to fit. @@ -447,7 +602,7 @@ private RowLines WrapRow(Row row, int rowIndex, double width, TextStyle style) var cell = row.Cells[c]; var cs = cell.Style ?? style; var innerW = ColSpanWidth(col, cell.ColSpan) - cell.Padding.Horizontal; - cells[c] = WordWrapLines(cell.Content, cs, Math.Max(1, innerW)); + cells[c] = WordWrapLines(cell.Content, cs, Math.Max(1, innerW), HonoursBreaks(rowIndex, c)); col += cell.ColSpan; } return new RowLines(rowIndex, width, cells); @@ -873,10 +1028,24 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, } else { - wrappedLines = WordWrapLines(cell.Content, cs, Math.Max(1, innerBox.Width)); + wrappedLines = WordWrapLines(cell.Content, cs, Math.Max(1, innerBox.Width), HonoursBreaks(rowIndex, cellIndex)); lineCount = wrappedLines.Count; } + // A cell whose breaks the table read as spaces is reported where it is first drawn: once per + // page for a repeated header row, and from its first slice for a cut row. + if (!HonoursBreaks(rowIndex, cellIndex) && LayoutText.HasLineBreak(cell.Content) + && (slice is null || slice.First[cellIndex] == 0)) + { + ctx.Diagnostics?.Report( + LayoutDiagnosticCode.CellBreakDrawnAsSpace, + ((long)rowIndex << 32) | (uint)cellIndex, + static subject => string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"Table row {subject >> 32}, cell {subject & 0xFFFFFFFF} holds a line break that is drawn as a space, because honouring it would make the repeated header rows or rows joined by a RowSpan taller than a page."), + perElement: true); + } + // A cell with no line on this page keeps its rectangle and writes no text, and is tagged as // an empty cell: a marked-content sequence around nothing would describe nothing. if (lineCount == 0) @@ -1032,8 +1201,8 @@ private double ColSpanWidth(int startCol, int span) /// let the hard-break below (#473) reach both call sites from a single change instead of two /// that would otherwise have to be kept in step by hand. /// - private static int WordWrapCount(string text, TextStyle style, double maxWidth) => - WordWrapLines(text, style, maxWidth).Count; + private static int WordWrapCount(string text, TextStyle style, double maxWidth, bool honourBreaks) => + WordWrapLines(text, style, maxWidth, honourBreaks).Count; /// /// Word-wraps text into lines for drawing. A word wider than on @@ -1058,7 +1227,7 @@ private static int WordWrapCount(string text, TextStyle style, double maxWidth) /// it in the source. ParagraphRenderer already guards on lineFrags.Count == 0 for /// the same reason, which is why it never had this. /// - private static List WordWrapLines(string text, TextStyle style, double maxWidth) + private static List WrapLine(string text, TextStyle style, double maxWidth) { var result = new List(); if (string.IsNullOrEmpty(text)) { result.Add(string.Empty); return result; } @@ -1109,6 +1278,51 @@ private static List WordWrapLines(string text, TextStyle style, double m return result; } + /// + /// The lines a cell's text is drawn in: each hard line of the text, wrapped by + /// . A hard line ends at a carriage return and line feed pair, a lone + /// carriage return or a lone line feed; an empty hard line is a blank line, as in a paragraph. + /// Any other tab, form feed or similar control white space is a space. A null text, and text + /// with nothing in it, is one empty line. With false the text is + /// wrapped at spaces alone, measuring each control white-space character at its own width, and + /// the lines are drawn with each of them as a space. + /// + private static List WordWrapLines(string text, TextStyle style, double maxWidth, bool honourBreaks) + { + if (string.IsNullOrEmpty(text)) return WrapLine(string.Empty, style, maxWidth); + + var hardLines = CellLines(text, honourBreaks); + if (!honourBreaks) + { + var wrapped = WrapLine(hardLines[0], style, maxWidth); + for (var i = 0; i < wrapped.Count; i++) + wrapped[i] = LayoutText.ControlSpacesToSpaces(wrapped[i]); + return wrapped; + } + + if (hardLines.Length == 1) return WrapLine(hardLines[0], style, maxWidth); + + var result = new List(); + foreach (var line in hardLines) + result.AddRange(WrapLine(line, style, maxWidth)); + return result; + } + + /// + /// The lines a cell's text is measured in. When is true, the + /// hard lines of the text with their control white space turned into spaces. Otherwise the + /// text itself as the one line it is measured as, control characters and all. + /// + internal static string[] CellLines(string text, bool honourBreaks) + { + if (!honourBreaks) return [text]; + + var lines = LayoutText.SplitHardLines(text); + for (var i = 0; i < lines.Length; i++) + lines[i] = LayoutText.ControlSpacesToSpaces(lines[i]); + return lines; + } + /// Hard-breaks a word wider than at character granularity. private static void HardBreakWord(string word, TextStyle style, double maxWidth, List lines) { diff --git a/tests/VellumPdf.Layout.Tests/PageBreakTests.cs b/tests/VellumPdf.Layout.Tests/PageBreakTests.cs index 6852728bb..1ea5ab216 100644 --- a/tests/VellumPdf.Layout.Tests/PageBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/PageBreakTests.cs @@ -600,7 +600,7 @@ public void ATaggedDocumentWithARectoBlank_hasNoStructureElementOnTheBlankPage() // ── Text that is not a break ───────────────────────────────────────────── [Fact] - public void AFormFeedInText_neverStartsAPage_andEachElementTreatsItAsItAlwaysDid() + public void AFormFeedInText_neverStartsAPage_andEveryElementDrawsItAsASpace() { var table = new TableElement(); table.AddRow().AddCell("cell\fx"); @@ -617,13 +617,13 @@ public void AFormFeedInText_neverStartsAPage_andEachElementTreatsItAsItAlwaysDid var pages = Pages(Save(doc)); Assert.Single(pages); - // A paragraph, a heading and a list item draw the character as a space; a table cell and a - // running band hand the raw 0x0C character to the font. + // A paragraph, a heading, a list item, a table cell and a running band all draw the + // character as a space. Assert.Contains("para z", pages[0].Texts); Assert.Contains("head w", pages[0].Texts); Assert.Contains("item y", pages[0].Texts); - Assert.Contains("cell\fx", pages[0].Texts); - Assert.Contains("H\fX", pages[0].Texts); + Assert.Contains("cell x", pages[0].Texts); + Assert.Contains("H X", pages[0].Texts); } // ── A document of breaks alone ─────────────────────────────────────────── diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs new file mode 100644 index 000000000..2377333e8 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -0,0 +1,848 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Elements.Table; +using VellumPdf.Layout.Rendering.Table; +using VellumPdf.TestSupport; + +namespace VellumPdf.Layout.Tests; + +/// +/// A tab, a line break or a form feed in a table cell or a running band no longer reaches glyph +/// lookup (#611, #613 item 34). A cell breaks its lines as a paragraph does, and every other +/// control white-space character is a space. +/// +/// The fixtures with a short page are 300x400pt with 10pt margins and two 100pt columns, in +/// Helvetica 12pt: a line is 14.4pt and the default padding adds 8pt, so a cell of n lines is +/// 14.4 n + 8 pt tall. The wide fixtures are 2000x600pt in Helvetica 10pt, where a line is 12pt, a +/// cell of n lines is 12 n + 8 pt tall, and a page holds 580pt. +/// +public sealed class TableCellBreakTests : IDisposable +{ + private static readonly string DejaVu = Path.Combine(AppContext.BaseDirectory, "Fonts", "DejaVuSans.ttf"); + + private readonly string _tempDir; + + public TableCellBreakTests() + { + _tempDir = Path.Combine(Path.GetTempPath(), $"vellumcellbreak_{Guid.NewGuid():N}"); + Directory.CreateDirectory(_tempDir); + } + + public void Dispose() + { + try { Directory.Delete(_tempDir, recursive: true); } + catch (IOException) { /* best-effort cleanup */ } + catch (UnauthorizedAccessException) { /* best-effort cleanup */ } + } + + // ── Fixtures ───────────────────────────────────────────────────────────── + + private static TextStyle Helvetica(double size) => new() + { + FontRef = new FontReference(Standard14.Helvetica), + FontSize = size, + }; + + private static Document ShortPage() => new() + { + PageSize = new PdfRectangle(0, 0, 300, 400), + Margins = new EdgeInsets(10), + }; + + private static Document WidePage() => new() + { + PageSize = new PdfRectangle(0, 0, 2000, 600), + Margins = new EdgeInsets(10), + }; + + private static TableElement Table12() => + new TableElement { DefaultCellStyle = Helvetica(12) }.SetColumnWidths(100, 100); + + private static TableElement Wide10(params double[] widths) => + new TableElement { DefaultCellStyle = Helvetica(10) }.SetColumnWidths(widths); + + /// n two-letter words, joined by . + private static string Words(int n, string separator = "\n") => + string.Join(separator, Enumerable.Repeat("ab", n)); + + private static byte[] Save(Document doc) + { + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + private static string Content(byte[] pdf) => PdfTestUtil.DecompressAllFlatStreams(pdf); + + private static int PageCount(byte[] pdf) => + Regex.Matches(Encoding.Latin1.GetString(pdf), @"/Type\s*/Page\b").Count; + + private static readonly Regex Rect = new( + @"(?\S+ \S+ \S+ \S+) re\s+(?[fS])\b", RegexOptions.CultureInvariant); + + /// Every cell border a page paints, as "x y w h". + private static string[] Borders(string content) => + [.. Rect.Matches(content).Where(m => m.Groups["op"].Value == "S").Select(m => m.Groups["r"].Value)]; + + private static double[] Heights(string content) => + [.. Borders(content).Select(b => double.Parse(b.Split(' ')[3], CultureInfo.InvariantCulture))]; + + private static double[] Widths(string content) => + [.. Borders(content).Select(b => double.Parse(b.Split(' ')[2], CultureInfo.InvariantCulture))]; + + private static List Placements(string content) => + [.. ContentStreamReadback.TextPlacements(content).Where(p => p.Text.Length > 0)]; + + private static string[] Texts(string content) => [.. Placements(content).Select(p => p.Text)]; + + private static List HexShows(string content) => + [.. Regex.Matches(content, @"(?m)^<([0-9A-Fa-f]*)> Tj$").Select(m => m.Groups[1].Value.ToLowerInvariant())]; + + // ── Standard 14: no control byte is written ────────────────────────────── + + /// + /// A tab is one space, so the cell draws "A B" and not a string with a raw 0x09 in it. The row + /// is one line tall. + /// + [Fact] + public void Standard14_aTabIsOneSpace() + { + using var doc = ShortPage(); + var t = Table12(); + t.AddRow().AddCell("A\tB").AddCell("x"); + doc.Add(t); + + var content = Content(Save(doc)); + + Assert.Equal(["A B", "x"], Texts(content)); + Assert.Equal([22.4, 22.4], Heights(content).Select(h => Math.Round(h, 4))); + Assert.DoesNotContain('\t', content); + } + + /// + /// A line feed breaks the line: two show strings, the second baseline one leading (14.4pt) + /// lower, and a row of 2 x 14.4 + 8 = 36.8pt. No string holds the 0x0A byte or its escape. + /// + [Fact] + public void Standard14_aLineFeedBreaksTheLine() + { + using var doc = ShortPage(); + var t = Table12(); + t.AddRow().AddCell("line1\nline2").AddCell("x"); + doc.Add(t); + + var content = Content(Save(doc)); + var placements = Placements(content); + + Assert.Equal(["line1", "line2", "x"], placements.Select(p => p.Text)); + Assert.Equal(14.4, placements[0].Y - placements[1].Y, 4); + Assert.Equal(placements[0].X, placements[1].X); + Assert.Equal([36.8, 36.8], Heights(content).Select(h => Math.Round(h, 4))); + AssertNoControlCharacter(placements); + } + + /// A carriage return and line feed pair is one break, and a lone carriage return is one. + [Theory] + [InlineData("cr1\r\ncr2")] + [InlineData("cr1\rcr2")] + [InlineData("cr1\ncr2")] + public void Standard14_everyLineBreakFormIsOneBreak(string text) + { + using var doc = ShortPage(); + var t = Table12(); + t.AddRow().AddCell(text).AddCell("x"); + doc.Add(t); + + var content = Content(Save(doc)); + + Assert.Equal(["cr1", "cr2", "x"], Texts(content)); + Assert.Equal(36.8, Heights(content)[0], 4); + AssertNoControlCharacter(Placements(content)); + } + + /// + /// A trailing break leaves a blank last line, and two breaks in a row a blank line between, + /// as in a paragraph: "a\n" is two lines tall and "a\n\nb" three. + /// + [Theory] + [InlineData("a\n", 36.8, new[] { "a" })] + [InlineData("a\n\nb", 51.2, new[] { "a", "b" })] + [InlineData("\nb", 36.8, new[] { "b" })] + public void Standard14_anEmptyHardLineIsABlankLine(string text, double height, string[] drawn) + { + using var doc = ShortPage(); + var t = Table12(); + t.AddRow().AddCell(text).AddCell("x"); + doc.Add(t); + + var content = Content(Save(doc)); + + Assert.Equal([.. drawn, "x"], Texts(content)); + Assert.Equal(height, Heights(content)[0], 4); + } + + /// + /// A form feed, a line tabulation and a next-line character are spaces: neither a break nor a + /// raw control byte. The text between them stays one word run, so the cell is one line. + /// + [Fact] + public void Standard14_aFormFeedIsOneSpace() + { + using var doc = ShortPage(); + var t = Table12(); + t.AddRow().AddCell("cell\fx").AddCell("a\vb\u0085c\u2028d\u2029e"); + doc.Add(t); + + var content = Content(Save(doc)); + + Assert.Equal(["cell x", "a b c d e"], Texts(content)); + Assert.Equal(22.4, Heights(content)[0], 4); + Assert.DoesNotContain('\f', content); + } + + /// + /// A cell and a paragraph read the same text the same way: the same lines for a text that holds + /// a tab, a form feed and each form of line break. + /// + [Fact] + public void ACellAndAParagraphBreakTheSameTextIntoTheSameLines() + { + const string text = "x\tb\fc\r\nd\re\nf"; + + using var cellDoc = ShortPage(); + var t = new TableElement { DefaultCellStyle = Helvetica(12) }.SetColumnWidths(250); + t.AddRow().AddCell(text); + cellDoc.Add(t); + + using var paragraphDoc = ShortPage(); + paragraphDoc.Add(new Paragraph(text, Helvetica(12))); + + var inCell = Texts(Content(Save(cellDoc))); + var inParagraph = Texts(Content(Save(paragraphDoc))); + + Assert.Equal(["x b c", "d", "e", "f"], inParagraph); + Assert.Equal(inParagraph, inCell); + } + + /// + /// A space separator that a font draws, such as U+2003, is left as written, so a cell that held + /// one before this change is drawn as it was: Helvetica has no glyph for it and the canvas + /// writes a question mark, and the cell is still one line. The no-break spaces keep their + /// meaning. + /// + [Fact] + public void Standard14_aSpaceSeparatorIsLeftAlone() + { + using var doc = ShortPage(); + var t = Table12(); + t.AddRow().AddCell("a\u2003b").AddCell("c\u00A0d"); + doc.Add(t); + + var content = Content(Save(doc)); + + Assert.Equal(["a?b", "c\u00A0d"], Texts(content)); + Assert.Equal(22.4, Heights(content)[0], 4); + } + + /// + /// Every character that is white space, written alone into a cell between two letters, leaves + /// no control character in a show string, and a control character that is not white space is + /// not touched. + /// + [Fact] + public void Standard14_noWhiteSpaceCharacterReachesTheFontAsAControlCharacter() + { + var whiteSpace = Enumerable.Range(0, 0x10000).Select(i => (char)i).Where(char.IsWhiteSpace).ToList(); + Assert.Contains('\t', whiteSpace); + Assert.Contains('\f', whiteSpace); + Assert.Contains('\u0085', whiteSpace); + Assert.Contains('\u2028', whiteSpace); + + foreach (var c in whiteSpace) + { + using var doc = ShortPage(); + var t = Table12(); + t.AddRow().AddCell("x" + c + "y").AddCell("z"); + doc.Add(t); + + var placements = Placements(Content(Save(doc))); + foreach (var p in placements) + Assert.True( + p.Text.All(ch => ch >= 0x20), + $"U+{(int)c:X4} reached the font as a control character in \"{p.Text}\"."); + } + } + + // ── Column sizing reads the same lines ─────────────────────────────────── + + /// + /// An automatic column is sized from the widest line, not from the whole text: two columns + /// whose widest lines are the same word are the same width, though one of them holds a second + /// line as well. + /// + [Fact] + public void AnAutoColumn_isSizedFromItsWidestLine() + { + using var doc = ShortPage(); + var t = new TableElement { DefaultCellStyle = Helvetica(12) }; + t.AddRow().AddCell("aa\nbbbbbbbb").AddCell("bbbbbbbb"); + doc.Add(t); + + var widths = Widths(Content(Save(doc))); + + Assert.Equal(2, widths.Length); + Assert.Equal(widths[0], widths[1], 6); + Assert.Equal(140, widths[0], 6); + } + + // ── Null text ──────────────────────────────────────────────────────────── + + /// A null cell text with explicit widths still saves and draws nothing, as before. + [Fact] + public void ANullText_withExplicitWidths_drawsNothing() + { + using var doc = ShortPage(); + var t = Table12(); + t.AddRow().AddCell(new Cell(null!)).AddCell("x"); + doc.Add(t); + + var content = Content(Save(doc)); + + Assert.Equal(["x"], Texts(content)); + } + + /// A null cell text in an automatically sized column is still refused, naming content. + [Fact] + public void ANullText_inAnAutoColumn_isStillRefused() + { + using var doc = ShortPage(); + var t = new TableElement { DefaultCellStyle = Helvetica(12) }; + t.AddRow().AddCell(new Cell(null!)).AddCell("x"); + doc.Add(t); + + var ex = Assert.Throws(() => Save(doc)); + + Assert.Equal("content", ex.ParamName); + } + + // ── Embedded font: no glyph 0 ──────────────────────────────────────────── + + private static string GlyphHex(EmbeddedFontHandle font, string text) + { + var ids = new ushort[text.Length]; + var n = font.GetGlyphIds(text, ids); + return string.Concat(ids.Take(n).Select(id => id.ToString("x4", CultureInfo.InvariantCulture))); + } + + private static Document EmbeddedDoc(out EmbeddedFontHandle font, PdfConformance conformance = PdfConformance.None) + { + var doc = new Document + { + PageSize = new PdfRectangle(0, 0, 300, 400), + Margins = new EdgeInsets(10), + Conformance = conformance, + }; + doc.Info.Title = "Cell breaks"; + font = doc.UseTrueTypeFont(File.ReadAllBytes(DejaVu)); + return doc; + } + + private static void RequireDejaVu() + { + if (!File.Exists(DejaVu)) + OracleGate.Unavailable("DejaVuSans.ttf", "DejaVu Sans is needed for an embedded font."); + } + + /// + /// The three cells of the report, in an embedded font: each show string is the font's glyph ids + /// for the text as a paragraph reads it, with glyph 3 (the space) where the tab was and one + /// string per line, and the font's ToUnicode map has no entry for glyph 0 as U+0009, U+000A or + /// U+000D. + /// + [Fact] + public void Embedded_aTabAndALineBreakAreNotGlyphZero() + { + RequireDejaVu(); + using var doc = EmbeddedDoc(out var font, PdfConformance.PdfA2u); + var t = new TableElement { DefaultCellStyle = new TextStyle { FontRef = font, FontSize = 12 } } + .SetColumnWidths(100, 100); + t.AddRow().AddCell("A\tB").AddCell("line1\nline2"); + t.AddRow().AddCell("cr1\r\ncr2").AddCell("tail"); + doc.Add(t); + + var content = Content(Save(doc)); + var shows = HexShows(content); + + Assert.Equal( + [ + GlyphHex(font, "A B"), + GlyphHex(font, "line1"), + GlyphHex(font, "line2"), + GlyphHex(font, "cr1"), + GlyphHex(font, "cr2"), + GlyphHex(font, "tail"), + ], + shows); + Assert.Equal("0003", GlyphHex(font, "A B")[4..8]); + foreach (var show in shows) + for (var i = 0; i < show.Length; i += 4) + Assert.NotEqual("0000", show.Substring(i, 4)); + + Assert.DoesNotContain("<0000> <0009>", content, StringComparison.Ordinal); + Assert.DoesNotContain("<0000> <000A>", content, StringComparison.Ordinal); + Assert.DoesNotContain("<0000> <000D>", content, StringComparison.Ordinal); + Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.NotdefGlyph); + } + + /// + /// A white-space character, between two letters in an embedded font, never produces glyph 0 + /// unless it is a space separator the font has no glyph for, which is written as it always was. + /// A control character that is not white space is not touched: U+0001 still reaches glyph 0. + /// + [Fact] + public void Embedded_noControlWhiteSpaceIsGlyphZero_andOtherControlsStillAre() + { + RequireDejaVu(); + + foreach (var c in Enumerable.Range(0, 0x10000).Select(i => (char)i).Where(char.IsWhiteSpace)) + { + using var doc = EmbeddedDoc(out var font); + var t = new TableElement { DefaultCellStyle = new TextStyle { FontRef = font, FontSize = 12 } } + .SetColumnWidths(250); + t.AddRow().AddCell("x" + c + "y"); + doc.Add(t); + + var shows = HexShows(Content(Save(doc))); + + if (char.GetUnicodeCategory(c) == UnicodeCategory.SpaceSeparator) + { + // Written as the font maps it, exactly as before this change. + Assert.Equal([GlyphHex(font, "x" + c + "y")], shows); + } + else + { + // A line feed and a carriage return break the line; every other one is a space. + var expected = c is '\n' or '\r' + ? new[] { GlyphHex(font, "x"), GlyphHex(font, "y") } + : [GlyphHex(font, "x y")]; + Assert.True( + shows.SequenceEqual(expected), + $"U+{(int)c:X4}: {string.Join(",", shows)} against {string.Join(",", expected)}."); + Assert.DoesNotContain("0000", shows.SelectMany(s => Enumerable.Range(0, s.Length / 4).Select(i => s.Substring(i * 4, 4)))); + } + } + + using var control = EmbeddedDoc(out var controlFont); + var ct = new TableElement { DefaultCellStyle = new TextStyle { FontRef = controlFont, FontSize = 12 } } + .SetColumnWidths(250); + ct.AddRow().AddCell("x\u0001y"); + control.Add(ct); + + var controlShows = HexShows(Content(Save(control))); + + Assert.Equal([GlyphHex(controlFont, "x\u0001y")], controlShows); + Assert.Contains("0000", Enumerable.Range(0, controlShows[0].Length / 4).Select(i => controlShows[0].Substring(i * 4, 4))); + } + + /// + /// The embedded file passes veraPDF at PDF/A-2u and PDF/A-2u preflight finds no glyph 0, after + /// the fixture is asserted to hold the construct: a tab, a line feed and a carriage return line + /// feed in cells, with the second lines drawn. + /// + [Fact] + public void Embedded_theFileIsPdfA2uClean() + { + RequireDejaVu(); + using var doc = EmbeddedDoc(out var font, PdfConformance.PdfA2u); + var t = new TableElement { DefaultCellStyle = new TextStyle { FontRef = font, FontSize = 12 } } + .SetColumnWidths(100, 100); + t.AddRow().AddCell("A\tB").AddCell("line1\nline2"); + t.AddRow().AddCell("cr1\r\ncr2").AddCell("end\ffeed"); + doc.Add(t); + var bytes = Save(doc); + var path = Path.Combine(_tempDir, "cells-a2u.pdf"); + File.WriteAllBytes(path, bytes); + + var shows = HexShows(Content(bytes)); + Assert.Contains(GlyphHex(font, "line2"), shows); + Assert.Contains(GlyphHex(font, "cr2"), shows); + Assert.Contains(GlyphHex(font, "end feed"), shows); + + ExternalTool.TryRun("verapdf", ["--flavour", "2u", path], + out var vexit, out var report, out var verr, out var vtimed, timeoutMs: 120_000); + Assert.False(vtimed); + Assert.True(vexit is 0 or 1, $"veraPDF exited {vexit}\n{report}\n{verr}"); + Assert.True(report.Contains("isCompliant=\"true\"", StringComparison.Ordinal), report); + + var rules = VellumPdf.Conformance.PdfPreflight + .Validate(bytes, VellumPdf.Conformance.PdfConformance.PdfA2U) + .Assertions.Select(a => a.RuleId).ToList(); + Assert.DoesNotContain("ISO19005-2:6.2.11.8-notdef", rules); + + ExternalTool.TryRun("pdftotext", ["-layout", path, "-"], out var texit, out var text, out var terr, out _); + Assert.True(texit == 0, terr); + Assert.Contains("end feed", text, StringComparison.Ordinal); + var lines = text.Split('\n').Select(l => l.Trim()).ToList(); + Assert.Contains(lines, l => l.Contains("line1", StringComparison.Ordinal) && !l.Contains("line2", StringComparison.Ordinal)); + Assert.Contains(lines, l => l.Contains("line2", StringComparison.Ordinal)); + } + + // ── Running bands ──────────────────────────────────────────────────────── + + /// + /// A form feed in a running band's template is a space, as it is in a paragraph, and so is a + /// tab or a line break: the band draws one line, and none of them reaches the font. + /// + [Theory] + [InlineData("H\fX", "H X")] + [InlineData("H\tX", "H X")] + [InlineData("H\nX", "H X")] + [InlineData("H\r\nX", "H X")] + public void ABandDrawsAControlSpaceAsASpace(string template, string drawn) + { + using var doc = ShortPage(); + doc.SetHeader(template, Helvetica(10)); + doc.Add(new Paragraph("body", Helvetica(10))); + + var content = Content(Save(doc)); + + Assert.Contains(drawn, Texts(content)); + Assert.DoesNotContain('\f', content); + Assert.DoesNotContain('\t', content); + } + + /// + /// The band's width is measured on the text it draws, so a template cut to fit is cut at the + /// space a form feed became: only "aaa" fits beside the form feed's neighbour. + /// + [Fact] + public void ABandCutsAtTheSpaceAFormFeedBecame() + { + var style = Helvetica(10); + var width = style.MeasureString("aaa bb") - 0.1; + using var doc = new Document + { + PageSize = new PdfRectangle(0, 0, width + 20, 400), + Margins = new EdgeInsets(10), + }; + doc.SetHeader("aaa\fbbbb", style); + doc.Add(new Paragraph("body", style)); + + var content = Content(Save(doc)); + + Assert.Contains("aaa", Texts(content)); + Assert.Single(doc.BandTruncations); + } + + // ── Rows that cannot be cut ────────────────────────────────────────────── + + /// The diagnostic a cell that reads its breaks as spaces is reported with, or null. + private static LayoutDiagnostic? CellReport(Document doc) => + doc.Diagnostics.SingleOrDefault(d => d.Code == LayoutDiagnosticCode.CellBreakDrawnAsSpace); + + /// + /// A header row whose breaks, honoured, leave no room under it for the row below: 2.3.3 drew + /// the cell on one line. The cell is drawn as one line of spaces and reported as a warning. + /// A header of 46 lines is 560pt and leaves 20pt, which holds the 20pt row below, so its + /// breaks are kept. + /// + [Theory] + [InlineData(46, false)] + [InlineData(47, true)] + [InlineData(48, true)] + [InlineData(100, true)] + public void AHeaderThatWouldLeaveNoRoomForTheRowBelowReadsItsBreaksAsSpaces(int n, bool asSpaces) + { + using var doc = WidePage(); + var t = Wide10(1900); + t.AddRow(isHeader: true).AddCell(Words(n)); + t.AddRow().AddCell("x"); + doc.Add(t); + + var bytes = Save(doc); + var texts = Texts(Content(bytes)); + var report = CellReport(doc); + + Assert.Equal(1, PageCount(bytes)); + if (asSpaces) + { + Assert.Equal([Words(n, " "), "x"], texts); + Assert.NotNull(report); + Assert.Equal(LayoutDiagnosticSeverity.Warning, report.Severity); + Assert.Equal(1, report.Count); + Assert.Contains("row 0, cell 0", report.Message, StringComparison.Ordinal); + Assert.Equal(LayoutElementKind.Table, report.ElementKind); + } + else + { + Assert.Equal([.. Enumerable.Repeat("ab", n), "x"], texts); + Assert.Null(report); + } + } + + /// + /// A header row whose own height, honoured, is more than a page: the same fallback, and a + /// table that 2.3.3 saved still saves with nothing refused. + /// + [Fact] + public void AHeaderTallerThanAPageReadsItsBreaksAsSpaces() + { + using var doc = WidePage(); + var t = Wide10(1900); + t.AddRow(isHeader: true).AddCell(Words(100)); + t.AddRow().AddCell("x"); + doc.Add(t); + + var texts = Texts(Content(Save(doc))); + + Assert.Equal([Words(100, " "), "x"], texts); + Assert.Equal(LayoutDiagnosticSeverity.Warning, CellReport(doc)!.Severity); + } + + /// + /// Rows joined by a RowSpan are never cut, so when their breaks, honoured, make the group taller + /// than a page, the cells that hold them read the breaks as spaces. A group of 46 lines plus a + /// 20pt row is 580pt, which fits; 47 lines does not. + /// + [Theory] + [InlineData(46, false)] + [InlineData(47, true)] + [InlineData(100, true)] + public void ARowSpanGroupThatWouldBeTallerThanAPageReadsItsBreaksAsSpaces(int n, bool asSpaces) + { + using var doc = WidePage(); + var t = Wide10(1500, 400); + t.AddRow().AddCell(new Cell(Words(n)) { RowSpan = 2 }).AddCell("b"); + t.AddRow().AddCell("c"); + doc.Add(t); + + var bytes = Save(doc); + var texts = Texts(Content(bytes)); + + Assert.Equal(1, PageCount(bytes)); + if (asSpaces) + { + Assert.Contains(Words(n, " "), texts); + Assert.NotNull(CellReport(doc)); + } + else + { + Assert.Equal(n, texts.Count(x => x == "ab")); + Assert.Null(CellReport(doc)); + } + } + + /// + /// Two rows that are each short enough, joined by a RowSpan, are too tall together: both + /// cells that hold breaks read them as spaces, and each is reported. 23 lines in each row is + /// 2 x 284 = 568pt, which fits; 24 lines is 592pt. + /// + [Theory] + [InlineData(23, 0)] + [InlineData(24, 2)] + public void ARowSpanGroupOfTwoRowsReadsEachBreakingCellAsOneLine(int n, int reported) + { + using var doc = WidePage(); + var t = Wide10(1000, 900); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell(Words(n)); + t.AddRow().AddCell(Words(n)); + doc.Add(t); + + var bytes = Save(doc); + + Assert.Equal(1, PageCount(bytes)); + Assert.Equal(reported, doc.Diagnostics.Count(d => d.Code == LayoutDiagnosticCode.CellBreakDrawnAsSpace)); + if (reported > 0) + Assert.Equal(2, Texts(Content(bytes)).Count(x => x == Words(n, " "))); + } + + /// + /// A row that can be cut keeps its breaks however tall they make it: 48 lines are 584pt, which + /// no page holds, so the row is cut between its lines and nothing is reported. + /// + [Fact] + public void AnOrdinaryRowKeepsItsBreaksAndIsCut() + { + using var doc = WidePage(); + var t = Wide10(1900); + t.AddRow().AddCell(Words(48)); + doc.Add(t); + + var bytes = Save(doc); + + Assert.Equal(2, PageCount(bytes)); + Assert.Equal(48, Texts(Content(bytes)).Count(x => x == "ab")); + Assert.Empty(doc.Diagnostics); + } + + /// + /// A header that reads its breaks as spaces is drawn the same way on every page, including the + /// pages a cut row continues on: the long header string is shown once per page, each page + /// reports it, and the report's count is the number of pages. + /// + [Fact] + public void AHeaderThatReadsItsBreaksAsSpacesDoesSoOnEveryPage() + { + using var doc = WidePage(); + var t = Wide10(1900); + t.AddRow(isHeader: true).AddCell(Words(60)); + t.AddRow().AddCell(Words(100)); + doc.Add(t); + + var bytes = Save(doc); + var texts = Texts(Content(bytes)); + var pages = PageCount(bytes); + + Assert.True(pages >= 2, "the row was not cut"); + Assert.Equal(pages, texts.Count(x => x == Words(60, " "))); + Assert.Equal(100, texts.Count(x => x == "ab")); + Assert.Equal(pages, CellReport(doc)!.Count); + } + + /// + /// A cell that reads its breaks as spaces is measured and wrapped as a cell with no break is, so + /// the table's rectangles are exactly those the same table had when a line feed was one more + /// character of the line: the four borders below are what 2.3.3 drew for it, though 2.3.3 wrote + /// the line feeds into the string. + /// + [Fact] + public void AFallbackHeaderKeepsTheGeometryOfAnUnbrokenLine() + { + using var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica(10) }; + t.AddRow(isHeader: true).AddCell(Words(60)).AddCell("h"); + t.AddRow().AddCell("x").AddCell("y"); + doc.Add(t); + + var content = Content(Save(doc)); + + Assert.NotNull(CellReport(doc)); + Assert.Equal( + ["10 570 1930.09932 20", "1940.09932 570 49.90068 20", "10 550 1930.09932 20", "1940.09932 550 49.90068 20"], + Borders(content)); + Assert.Equal([Words(60, " "), "h", "x", "y"], Texts(content)); + } + + /// + /// A header whose breaks, honoured, take the room a RowSpan group needs under it: the group has + /// no break of its own to give up, so the header's cell reads its breaks as spaces. The header + /// of 30 lines is 368pt and the group 268pt, which do not fit 580pt together; with the header + /// on one line they do. + /// + [Fact] + public void AHeaderThatTakesTheRoomOfARowSpanGroupReadsItsBreaksAsSpaces() + { + using var doc = WidePage(); + var t = Wide10(30, 1870); + t.AddRow(isHeader: true).AddCell("h").AddCell(Words(30)); + t.AddRow().AddCell(new Cell(Words(20, " ")) { RowSpan = 2 }).AddCell("b"); + t.AddRow().AddCell("c"); + doc.Add(t); + + var bytes = Save(doc); + var texts = Texts(Content(bytes)); + var report = CellReport(doc); + + Assert.Equal(1, PageCount(bytes)); + Assert.Contains(Words(30, " "), texts); + Assert.Equal(20, texts.Count(x => x == "ab")); + Assert.NotNull(report); + Assert.Contains("row 0, cell 1", report.Message, StringComparison.Ordinal); + } + + /// + /// A tab is one space wide where the raw character was measured at its own width, which can + /// wrap a cell one line taller and push a RowSpan group over the page. "ab" and a tab and "ab" + /// fits a 24pt column on one line as one word, and as two words does not; the group of 46 plain + /// lines under it is exactly 580pt with the one line and 592pt with two. The cell is laid out + /// as it was measured before, with the tab drawn as a space, and nothing is reported because it + /// holds no line break. The borders are 2.3.3's. + /// + [Fact] + public void ATabThatWouldTipARowSpanGroupOverThePageIsLaidOutUnbroken() + { + using var doc = WidePage(); + var t = Wide10(36, 36); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("ab\tab"); + t.AddRow().AddCell(Words(46, " ")); + doc.Add(t); + + var bytes = Save(doc); + var content = Content(bytes); + + Assert.Equal(1, PageCount(bytes)); + Assert.Equal(["10 10 36 580", "46 570 36 20", "46 10 36 560"], Borders(content)); + Assert.Contains("ab ab", Texts(content)); + Assert.Empty(doc.Diagnostics); + } + + /// + /// A renderer laid out without the document, through a context built with the public + /// constructor, knows no page: it keeps every break, and a header that is then too tall is + /// the same refusal as before. The document supplies the page and reads them as spaces. + /// + [Fact] + public void WithoutThePageTheBreaksAreKept() + { + var t = Wide10(1900); + t.AddRow(isHeader: true).AddCell(Words(60)); + t.AddRow().AddCell("x"); + + var result = new TableRenderer(t).Layout(new LayoutContext(new LayoutBox(10, 10, 1980, 580))); + + Assert.Equal(LayoutResult.Outcome.Nothing, result.Status); + } + + /// + /// Strict diagnostics saves a table whose cell reads its breaks as spaces: the report is a + /// warning, because nothing is lost. + /// + [Fact] + public void StrictDiagnosticsSavesTheWarning() + { + using var doc = WidePage(); + doc.StrictDiagnostics = true; + var t = Wide10(1900); + t.AddRow(isHeader: true).AddCell(Words(60)); + t.AddRow().AddCell("x"); + doc.Add(t); + + var bytes = Save(doc); + + Assert.Equal(1, PageCount(bytes)); + Assert.Equal(LayoutDiagnosticSeverity.Warning, CellReport(doc)!.Severity); + } + + /// + /// A tab in a header or span-group cell is not a break, so it changes no height and is never + /// reported: only a carriage return or a line feed can make a row taller. + /// + [Fact] + public void ATabAloneIsNeverReported() + { + using var doc = WidePage(); + var t = Wide10(1900); + t.AddRow(isHeader: true).AddCell(Words(60, "\t")); + t.AddRow().AddCell("x"); + doc.Add(t); + + var texts = Texts(Content(Save(doc))); + + Assert.Equal([Words(60, " "), "x"], texts); + Assert.Empty(doc.Diagnostics); + } + + private static void AssertNoControlCharacter(IEnumerable placements) + { + foreach (var p in placements) + Assert.DoesNotContain(p.Text, ch => ch < 0x20); + } +} diff --git a/tests/VellumPdf.Layout.Tests/VellumPdf.Layout.Tests.csproj b/tests/VellumPdf.Layout.Tests/VellumPdf.Layout.Tests.csproj index bb0d992cb..cf6484a6d 100644 --- a/tests/VellumPdf.Layout.Tests/VellumPdf.Layout.Tests.csproj +++ b/tests/VellumPdf.Layout.Tests/VellumPdf.Layout.Tests.csproj @@ -10,6 +10,7 @@ + From 98a2585f20b22adf7515804882a04da12710fa88 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 00:02:40 +0100 Subject: [PATCH 02/48] fix(layout): leave a fallback cell's control characters out of the drawing A cell laid out unbroken was wrapped with its tabs and line breaks at their own width, zero in Helvetica, but drawn with each as a space, so its lines came out wider than measured and crossed borders and the page edge. They are now left out of the drawing, so a line is as wide as it was measured. Also limit the third fallback step to the cells that can change the rows that do not fit, end a pass after the header step so a group is judged by the header's new height, read other Unicode space separators as a space, and decide the fallback once per width instead of once per page. --- src/VellumPdf.Layout/Core/LayoutText.cs | 54 +++- src/VellumPdf.Layout/Document.cs | 4 +- src/VellumPdf.Layout/Elements/Table/Cell.cs | 41 ++- .../Elements/Table/TableElement.cs | 6 +- src/VellumPdf.Layout/LayoutDiagnostic.cs | 2 +- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 25 +- src/VellumPdf.Layout/PublicAPI.Unshipped.txt | 2 +- .../Rendering/Table/TableRenderer.cs | 166 +++++++--- .../VellumPdf.Layout.Tests/PageBreakTests.cs | 4 +- .../TableCellBreakTests.cs | 283 ++++++++++++++---- 10 files changed, 451 insertions(+), 136 deletions(-) diff --git a/src/VellumPdf.Layout/Core/LayoutText.cs b/src/VellumPdf.Layout/Core/LayoutText.cs index 08bb7555c..895214793 100644 --- a/src/VellumPdf.Layout/Core/LayoutText.cs +++ b/src/VellumPdf.Layout/Core/LayoutText.cs @@ -2,20 +2,22 @@ // SPDX-License-Identifier: Apache-2.0 using System.Globalization; +using VellumPdf.Fonts; namespace VellumPdf.Layout.Core; /// /// How a table cell and a running band read the white space in their text, so that a character -/// no font draws never reaches glyph lookup. A paragraph applies the same line-break rule in -/// ; this class is the cell's and the band's copy of it. +/// no font draws never reaches glyph lookup. /// /// /// A character is a control space when holds for it and it is /// not in the Unicode category Space Separator: the C0 and C1 controls tab, line feed, line /// tabulation, form feed, carriage return and next line, and the line and paragraph separators -/// U+2028 and U+2029. The no-break spaces and the other space separators, such as U+2003 EM SPACE, -/// are not control spaces: a font draws them, so they are left as written. +/// U+2028 and U+2029. The Unicode space separators other than the no-break spaces, such as U+2003 +/// EM SPACE, are separator spaces: a cell reads each as U+0020, as +/// reads every white-space character except a line +/// feed and the no-break spaces U+00A0, U+202F and U+2007. A band reads only the control spaces. /// internal static class LayoutText { @@ -63,24 +65,60 @@ internal static string[] SplitHardLines(string text) return [.. lines]; } + /// + /// True for a Unicode space separator that a cell reads as U+0020: every character of the + /// category Space Separator except U+0020 itself and the no-break spaces. + /// + internal static bool IsSeparatorSpace(char c) => + c != ' ' && !NoBreakSpaces.IsNoBreakSpace(c) + && char.GetUnicodeCategory(c) == UnicodeCategory.SpaceSeparator; + + /// + /// Returns with every separator space replaced by U+0020, or the same + /// instance when it holds none. A control space is left as it is. + /// + internal static string SeparatorSpacesToSpaces(string text) => Replace(text, IsSeparatorSpace); + + /// + /// Returns with every control space removed, or the same instance when + /// it holds none. + /// + internal static string RemoveControlSpaces(string text) + { + var at = -1; + for (var i = 0; i < text.Length; i++) + { + if (IsControlSpace(text[i])) { at = i; break; } + } + if (at < 0) return text; + + var sb = new System.Text.StringBuilder(text.Length); + sb.Append(text, 0, at); + for (var i = at + 1; i < text.Length; i++) + if (!IsControlSpace(text[i])) sb.Append(text[i]); + return sb.ToString(); + } + /// /// Returns with every control space replaced by U+0020, or the same /// instance when it holds none. /// - internal static string ControlSpacesToSpaces(string text) + internal static string ControlSpacesToSpaces(string text) => Replace(text, IsControlSpace); + + private static string Replace(string text, Func test) { var at = -1; for (var i = 0; i < text.Length; i++) { - if (IsControlSpace(text[i])) { at = i; break; } + if (test(text[i])) { at = i; break; } } if (at < 0) return text; - return string.Create(text.Length, (text, at), static (span, state) => + return string.Create(text.Length, (text, at, test), static (span, state) => { state.text.AsSpan().CopyTo(span); for (var i = state.at; i < span.Length; i++) - if (IsControlSpace(span[i])) span[i] = ' '; + if (state.test(span[i])) span[i] = ' '; }); } } diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index f6fbd249e..a132b09df 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -119,8 +119,8 @@ public Document() { } /// (mirroring ), /// (a preformatted line split with /// a marker; a warning, which saves), - /// (a table cell's line break drawn as - /// a space; also a warning) + /// (a table cell's tab or line break left + /// out of what is drawn; also a warning) /// and . Every other one saves by /// default; only refuses it, and a later major version refuses /// them all. diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 89924b43a..903e9dc7a 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -22,26 +22,37 @@ public sealed class Cell /// Spaces are the only break points between words, and a word wider than the cell is broken /// between characters. /// A carriage return and line feed pair, a lone carriage return and a lone line feed - /// each end a line, as they do in a . An empty line between - /// two of them, or after the last, is a blank line one leading tall. A column sized - /// automatically is as wide as the widest line, and no narrower than the widest word on any - /// line. Every other white-space control character, which is a tab, a form feed, a line - /// tabulation, a next-line character, U+2028 and U+2029, is drawn as one space, so it - /// reaches no font as a control character. The no-break spaces and the other space - /// separators, such as U+2003, are written as they are. + /// each end a line. An empty line between two of them is a blank line one leading tall, and + /// so is the one after a trailing break: the text a followed by a line feed is two lines here, where a + /// draws one. Runs of spaces are kept as written, where a + /// paragraph collapses them. Every other white-space control character, which is a tab, a form + /// feed, a line tabulation, a next-line character, U+2028 and U+2029, is one space, and so is + /// every Unicode space separator other than the no-break spaces, such as U+2003, so none of + /// them reaches a font. The no-break spaces U+00A0, U+202F and U+2007 are written as they are. + /// A column sized automatically takes its minimum from the widest word and its maximum from the + /// widest line, each line of the cell measured on its own, where 2.3.3 measured the whole + /// text as one line. The width the column is then given is shared out among the columns as it + /// was, and can be more than the maximum or less than the minimum. /// A control character that is not white space, such as U+0001, is written as it is: in a /// standard-14 font as its WinAnsi code, and in an embedded font as whatever glyph the font's /// character map gives it, which is .notdef (glyph 0) when the map has no entry. The save lists /// each such character as , and /// refuses it; see . - /// A cell has no tab stops, so a tab is one space. A line break in a cell of a header - /// row, or of rows joined by a , is drawn as a space when honouring it - /// would make those rows taller than a page, because such rows are never cut between their - /// lines. The cell is then wrapped at spaces alone and sized from its whole text, and each - /// break in it is a space, and the save lists it as - /// , a warning that - /// saves. Every other cell keeps its breaks, and a - /// row of them that is taller than a page is cut between its lines. Do not pass a line + /// A cell has no tab stops, so a tab is one space. A cell of a header row, or of rows + /// joined by a , is laid out unbroken when honouring the line breaks of + /// those rows would make them taller than a page, because such rows are never cut between + /// their lines. It is then wrapped at spaces alone and sized from its whole text, each tab and + /// line break in it measured at the width its font gives it and left out of what is drawn, + /// so the words they separated run together in the drawing and in extracted text, and + /// no line is wider than it was measured. The save lists the cell as + /// , a warning that + /// saves. Which cells are read this way is decided in + /// three steps, each taken only while the rows still do not fit: the cells of the group that + /// hold a carriage return or a line feed, then those of the header rows, then every cell that + /// holds any control white space and sits in the group, in the header rows, or in an + /// automatically sized column one of those cells is in. A cell that holds only a line feed can + /// be read this way by any step. A cell in a row that can be cut between its lines, and in a + /// fixed-width column apart from the rows named, keeps its breaks. Do not pass a line /// break in a header row or a span group that is that tall and expect the lines to be drawn: /// move the text to a row that can be cut, or shorten it. A renderer you lay out without the /// document, through a built with the public constructor, knows no diff --git a/src/VellumPdf.Layout/Elements/Table/TableElement.cs b/src/VellumPdf.Layout/Elements/Table/TableElement.cs index 0cdc06165..50b785d07 100644 --- a/src/VellumPdf.Layout/Elements/Table/TableElement.cs +++ b/src/VellumPdf.Layout/Elements/Table/TableElement.cs @@ -32,9 +32,9 @@ namespace VellumPdf.Layout.Elements.Table; /// empty TD, also in a header row. /// A carriage return or line feed in a cell ends a line, so it makes the row taller. A /// header row, or rows joined by a , whose breaks would make them taller -/// than a page are never cut, so the cells of them that hold a break are wrapped at spaces alone -/// with each break drawn as a space, and the save lists each as -/// ; see . +/// than a page are never cut, so cells of them are wrapped at spaces alone with each tab and +/// break left out of what is drawn, and the save lists each as +/// ; see . /// These are refused, and never cut. /// throws whose message starts with the standard /// too-tall text and ends with a sentence naming the rows, for: header rows that together do not diff --git a/src/VellumPdf.Layout/LayoutDiagnostic.cs b/src/VellumPdf.Layout/LayoutDiagnostic.cs index ec9aa1551..e28092539 100644 --- a/src/VellumPdf.Layout/LayoutDiagnostic.cs +++ b/src/VellumPdf.Layout/LayoutDiagnostic.cs @@ -85,7 +85,7 @@ internal LayoutDiagnostic( { LayoutDiagnosticCode.DiagnosticsDropped => LayoutDiagnosticSeverity.Warning, LayoutDiagnosticCode.PreformattedLineWrapped => LayoutDiagnosticSeverity.Warning, - LayoutDiagnosticCode.CellBreakDrawnAsSpace => LayoutDiagnosticSeverity.Warning, + LayoutDiagnosticCode.CellWhiteSpaceDropped => LayoutDiagnosticSeverity.Warning, _ => LayoutDiagnosticSeverity.Error, }; diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index 1e94674e7..2839f894d 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -117,24 +117,31 @@ public enum LayoutDiagnosticCode TabStopBeyondWidth = 106, /// - /// A table cell holds a line break, and the save drew it as a space because honouring it + /// A table cell holds a tab, a line break or another control white-space character, and the + /// save left it out of what it drew, because honouring the line breaks of the cells around it /// would have made rows that cannot be cut between their lines taller than a page. /// is the number of times the cell was drawn, so a header /// row that repeats on every page counts once per page, and the message names the row and the /// cell, counted from zero in the order they were added. /// /// - /// No text is lost, so this is a warning and strict mode saves. The rows in question are - /// the leading header rows, which repeat on every page and are never cut, and the rows joined - /// by a , which are never cut either. When the - /// breaks of such a row, honoured, would leave it taller than the page, each cell of it that - /// holds a carriage return or a line feed is wrapped at spaces alone and sized from its whole - /// text, as a cell with no line break is, and each break in it is drawn as a space. A row that is - /// cut between its lines, and any other table, keeps its breaks and is not reported. + /// The words such a character separated run together in the cell, in drawing and in + /// extracted text, and nothing else is lost, so this is a warning and strict mode saves. + /// The cell is wrapped at spaces alone and sized from its whole text, each such character + /// measured at the width its font gives it and then not drawn, so no line is wider than it was + /// measured and nothing crosses the cell. The rows in question are the leading header rows, + /// which repeat on every page and are never cut, and the rows joined by a + /// , which are never cut either. A cell is read this + /// way in three steps, each taken only when the rows still do not fit a page: a cell of the + /// group that holds a carriage return or a line feed; then such a cell of the header rows; then + /// a cell that holds any control white space and sits in the group, in the header rows, or in + /// an automatically sized column that one of those cells is in. A cell that holds only a line + /// feed can be read this way by any of the three. A cell no step reaches keeps its breaks and + /// is not reported, in a table that has other cells read this way as in any other. /// Do not pass a header row or a span group whose line breaks do not fit one page: put /// the breaks in rows that can be cut, or shorten the text. /// - CellBreakDrawnAsSpace = 301, + CellWhiteSpaceDropped = 301, /// /// A list item that is a child of a child, or deeper, holds a null text, and the save drew diff --git a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt index a38df0cd6..0b6e1f594 100644 --- a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt +++ b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt @@ -100,5 +100,5 @@ VellumPdf.Layout.Elements.Preformatted.TabWidth.get -> int VellumPdf.Layout.Elements.Preformatted.TabWidth.init -> void VellumPdf.Layout.Elements.Preformatted.Text.get -> string! VellumPdf.Layout.LayoutDiagnosticCode.PreformattedLineWrapped = 104 -> VellumPdf.Layout.LayoutDiagnosticCode -VellumPdf.Layout.LayoutDiagnosticCode.CellBreakDrawnAsSpace = 301 -> VellumPdf.Layout.LayoutDiagnosticCode +VellumPdf.Layout.LayoutDiagnosticCode.CellWhiteSpaceDropped = 301 -> VellumPdf.Layout.LayoutDiagnosticCode VellumPdf.Layout.LayoutElementKind.Preformatted = 11 -> VellumPdf.Layout.LayoutElementKind diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index a5589e4db..f2ff6fdb6 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -53,12 +53,16 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource private RowSlice? _tailSlice; // The cells, as (row, cell) in authoring order, that this table lays out unbroken: wrapped at - // spaces alone and measured with their control characters, and drawn with each of those as a - // space, because honouring their breaks would make rows that cannot be cut taller than a page. - // Layout writes it and gives it to the renderers that draw the pages; null when every break is - // kept. + // spaces alone and measured with their control characters, and drawn without them, because + // honouring their breaks would make rows that cannot be cut taller than a page. Layout writes + // it and gives it to the renderers that draw the pages; null when every break is kept. private HashSet<(int Row, int Cell)>? _oneLine; + // What _oneLine was decided for: the table width and the fresh boxes. A renderer that carries + // the decision to the next page reuses it when it lays out at the same width and boxes, and so + // resolves the grid once, where deciding again would resolve it once per pass on every page. + private (double Width, LayoutBox First, LayoutBox Second)? _decidedFor; + /// The lines each cell of one row wraps into, at one table width. private sealed class RowLines(int row, double width, List?[] cells) { @@ -142,8 +146,9 @@ public TableRenderer(TableElement table, int startRow = 0) /// A carriage return or line feed in a cell ends a line. When honouring the breaks of a /// header row or of rows joined by a would make those rows taller /// than a page, which is known only under a context the document built, the cells that hold - /// them are wrapped at spaces alone and drawn with each break a space, and are reported as - /// . A context built with the public + /// them are wrapped at spaces alone and drawn without their tabs and breaks, and are reported + /// as ; + /// says which cells. A context built with the public /// constructor of keeps every break. /// These are refused with the too-tall exception, extended with a sentence naming the /// rows or the cell, and are never cut: the repeated header rows when they do not fit a page; @@ -209,7 +214,6 @@ public LayoutResult Layout(LayoutContext context) { _resumeLines = null; _resumeFrom = null; - _oneLine = null; // Before the grid resolves: a ColSpan of zero gives a column count of zero, so Resolve // returns no widths and Layout gives up below, and the caller was told the table was too @@ -223,6 +227,12 @@ public LayoutResult Layout(LayoutContext context) LayoutValidation.ValidateLineWidthIsFinite(_table.BorderWidth, "A table"); + // A decision made for this width and these boxes by the renderer that handed the table + // over stands: the cells it read unbroken are the cells this layout reads unbroken. + var key = fresh is { Length: 2 } ? (area.Width, fresh[0], fresh[1]) : ((double, LayoutBox, LayoutBox)?)null; + var decided = key is not null && _decidedFor is { } was && was.Equals(key.Value); + if (!decided) _oneLine = null; + ResolveGrid(area.Width, style); // A line break makes a cell taller than a layout that draws it on one line, and a tab @@ -231,7 +241,7 @@ public LayoutResult Layout(LayoutContext context) // either, so the cells that would make them so are laid out unbroken, and the grid and // the heights are taken again. Each pass adds cells, so this ends; most tables, which // hold no control white space, take no second pass. - if (fresh is not null && AnyControlSpace(rows)) + if (!decided && fresh is not null && AnyControlSpace(rows)) { while (CellsToReadAsOneLine(fresh, style) is { } more) { @@ -240,6 +250,7 @@ public LayoutResult Layout(LayoutContext context) ResolveGrid(area.Width, style); } } + _decidedFor = key; } // The repeatable header is the leading contiguous run of IsHeader rows — see @@ -339,9 +350,10 @@ public LayoutResult Layout(LayoutContext context) _headSlice = head, _tailSlice = tail, _oneLine = _oneLine, + _decidedFor = _decidedFor, }; var overflow = tail is null - ? new TableRenderer(_table, lastFit + 1) { _colWidths = _colWidths, _rowHeights = _rowHeights, _oneLine = _oneLine } + ? new TableRenderer(_table, lastFit + 1) { _colWidths = _colWidths, _rowHeights = _rowHeights, _oneLine = _oneLine, _decidedFor = _decidedFor } : new TableRenderer(_table, tail.Row) { _colWidths = _colWidths, @@ -349,6 +361,7 @@ public LayoutResult Layout(LayoutContext context) _resumeLines = tail.Source, _resumeFrom = tail.Next(), _oneLine = _oneLine, + _decidedFor = _decidedFor, }; return LayoutResult.Partial(_occupied, split, overflow); } @@ -413,15 +426,18 @@ private static bool AnyControlSpace(IReadOnlyList rows) // ── Cells that read their breaks as spaces ── /// - /// The cells that hold a line break and sit in rows that cannot be cut between their lines, - /// when those rows do not fit a fresh page with the breaks honoured, or null when there are - /// none that are not already laid out unbroken. The rows are the repeated header rows and the - /// rows joined by a ; the document would refuse them as too tall. - /// A group of rows is relieved first by its own cells. When it holds none left, the header - /// rows' cells go next, because they take room from every group under them. When those hold - /// none either, every cell that holds a tab or another control white-space character is laid out - /// unbroken too, because the width it takes from a column then no longer differs from a plain - /// text's; the rows then measure as a table with no line break measures them. + /// The cells to lay out unbroken in the next pass, or null when there are none that are not + /// already laid out unbroken. The rows that cannot be cut between their lines are the repeated + /// header rows and the rows joined by a ; the document would refuse + /// them as too tall. A row of either kind that does not fit a fresh page is relieved in steps, + /// and each step that adds a cell ends the pass, because every height has to be taken again + /// before the next step is judged. A group is relieved by its own cells that hold a line break + /// first. When it has none left, the header rows' cells that hold one go next, because they + /// take room from every group under them. When those have none either, the cells that hold a + /// tab or another control white-space character and can change the rows' height go last: the + /// cells of the header rows and of the rows themselves, and the cells of every other row in an + /// automatically sized column that one of those cells is in, because such a column is as wide + /// as its widest cell. A cell that no step reaches keeps its breaks. /// private HashSet<(int Row, int Cell)>? CellsToReadAsOneLine(LayoutBox[] fresh, TextStyle style) { @@ -433,10 +449,9 @@ private static bool AnyControlSpace(IReadOnlyList rows) HashSet<(int Row, int Cell)>? found = null; - // True when a cell was added that the table did not already lay out unbroken. A cell - // qualifies when it holds a line break, or, with anyControlSpace, any control white space, - // which changes a column's width as well. - bool Collect(int first, int last, bool anyControlSpace = false) + // True when a cell was added that the table did not already lay out unbroken. The cells of + // rows first to last that hold a line break qualify. + bool CollectBreaks(int first, int last) { var added = false; for (var r = first; r <= last && r < rows.Count; r++) @@ -444,33 +459,92 @@ bool Collect(int first, int last, bool anyControlSpace = false) var cells = rows[r].Cells; for (var c = 0; c < cells.Count; c++) { - var text = cells[c].Content; - if (!HonoursBreaks(r, c)) continue; - if (!(anyControlSpace ? LayoutText.HasControlSpace(text) : LayoutText.HasLineBreak(text))) continue; + if (!HonoursBreaks(r, c) || !LayoutText.HasLineBreak(cells[c].Content)) continue; added |= (found ??= []).Add((r, c)); } } return added; } + // The cells that hold any control white space, in rows first to last or in the header rows, + // or in an automatically sized column that one of those cells is in. + bool CollectControlSpace(int first, int last) + { + var reach = new bool[_colWidths.Length]; + void Reach(int from, int to) + { + for (var r = from; r <= to && r < rows.Count; r++) + { + var col = 0; + foreach (var cell in rows[r].Cells) + { + for (var k = 0; k < cell.ColSpan && col + k < reach.Length; k++) reach[col + k] = true; + col += cell.ColSpan; + if (col >= reach.Length) break; + } + } + } + Reach(first, last); + if (header.Count > 0) Reach(0, header[^1]); + + var added = false; + for (var r = 0; r < rows.Count; r++) + { + var inside = (r >= first && r <= last) || (header.Count > 0 && r <= header[^1]); + var cells = rows[r].Cells; + var col = 0; + for (var c = 0; c < cells.Count && col < reach.Length; c++) + { + var span = cells[c].ColSpan; + if (HonoursBreaks(r, c) && LayoutText.HasControlSpace(cells[c].Content) && (inside || SharesAutoColumn(col, span, reach))) + added |= (found ??= []).Add((r, c)); + col += span; + } + } + return added; + } + // The header rows are too tall when they do not fit a page, and when they leave a row below // them no room for one line of one of its cells. if (header.Count > 0 && (!FitsFresh(fresh, 0, headerHeight) || LeavesNoRoomForALine(fresh, headerHeight, lastHeaderRow, style)) - && !Collect(0, header[^1])) - Collect(0, rows.Count - 1, anyControlSpace: true); + && (CollectBreaks(0, header[^1]) || CollectControlSpace(0, header[^1]))) + return found; foreach (var (first, last) in SpanGroups(lastHeaderRow)) { var height = 0.0; for (var i = first; i <= last; i++) height += _rowHeights[i]; if (FitsFresh(fresh, headerHeight, height)) continue; - if (!Collect(first, last) && !Collect(0, header.Count > 0 ? header[^1] : -1)) - Collect(0, rows.Count - 1, anyControlSpace: true); + if (CollectBreaks(first, last)) continue; + + // The header's own heights are taken again before another group is judged by them. + if (header.Count > 0 && CollectBreaks(0, header[^1])) return found; + CollectControlSpace(first, last); } return found; } + /// + /// True when a column of that a cell at for + /// columns is in is automatically sized and is one that a relieved row + /// reaches. + /// + private bool SharesAutoColumn(int col, int span, bool[] reach) + { + for (var k = 0; k < span && col + k < reach.Length; k++) + if (reach[col + k] && IsAutoColumn(col + k)) return true; + return false; + } + + /// True when column takes its width from its content. + private bool IsAutoColumn(int i) + { + var widths = _table.ColWidths; + if (widths.Count == 0 || i >= widths.Count) return true; + return !double.IsFinite(widths[i]) || widths[i] <= 0; + } + /// /// True when a row from on has a cell that cannot hold one line /// under the header rows. @@ -1033,17 +1107,18 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, lineCount = wrappedLines.Count; } - // A cell whose breaks the table read as spaces is reported where it is first drawn: once per - // page for a repeated header row, and from its first slice for a cut row. - if (!HonoursBreaks(rowIndex, cellIndex) && LayoutText.HasLineBreak(cell.Content) + // A cell the table laid out unbroken is reported where it is first drawn: once per page for a + // repeated header row, and from its first slice for a cut row. Only a cell that holds a + // control character loses anything by it, which is the separation its words had. + if (!HonoursBreaks(rowIndex, cellIndex) && LayoutText.HasControlSpace(cell.Content) && (slice is null || slice.First[cellIndex] == 0)) { ctx.Diagnostics?.Report( - LayoutDiagnosticCode.CellBreakDrawnAsSpace, + LayoutDiagnosticCode.CellWhiteSpaceDropped, ((long)rowIndex << 32) | (uint)cellIndex, static subject => string.Create( System.Globalization.CultureInfo.InvariantCulture, - $"Table row {subject >> 32}, cell {subject & 0xFFFFFFFF} holds a line break that is drawn as a space, because honouring it would make the repeated header rows or rows joined by a RowSpan taller than a page."), + $"Table row {subject >> 32}, cell {subject & 0xFFFFFFFF} holds a tab, a line break or another control white-space character that is left out of what is drawn, because honouring the line breaks would make rows that cannot be cut taller than a page. The words it separated run together."), perElement: true); } @@ -1282,11 +1357,13 @@ private static List WrapLine(string text, TextStyle style, double maxWid /// /// The lines a cell's text is drawn in: each hard line of the text, wrapped by /// . A hard line ends at a carriage return and line feed pair, a lone - /// carriage return or a lone line feed; an empty hard line is a blank line, as in a paragraph. - /// Any other tab, form feed or similar control white space is a space. A null text, and text - /// with nothing in it, is one empty line. With false the text is - /// wrapped at spaces alone, measuring each control white-space character at its own width, and - /// the lines are drawn with each of them as a space. + /// carriage return or a lone line feed. An empty hard line is a blank line, and so is the one + /// after a trailing break, which a paragraph drops. Runs of spaces are kept as written, where a + /// paragraph collapses them. Every other white-space character except the no-break spaces is a + /// space. A null text, and text with nothing in it, is one empty line. With + /// false the text is wrapped at spaces alone, measuring each + /// control white-space character at its own width, and the lines are drawn without them, so a + /// line is never wider than it was measured. /// private static List WordWrapLines(string text, TextStyle style, double maxWidth, bool honourBreaks) { @@ -1297,7 +1374,7 @@ private static List WordWrapLines(string text, TextStyle style, double m { var wrapped = WrapLine(hardLines[0], style, maxWidth); for (var i = 0; i < wrapped.Count; i++) - wrapped[i] = LayoutText.ControlSpacesToSpaces(wrapped[i]); + wrapped[i] = LayoutText.RemoveControlSpaces(wrapped[i]); return wrapped; } @@ -1311,16 +1388,17 @@ private static List WordWrapLines(string text, TextStyle style, double m /// /// The lines a cell's text is measured in. When is true, the - /// hard lines of the text with their control white space turned into spaces. Otherwise the - /// text itself as the one line it is measured as, control characters and all. + /// hard lines of the text with their white space turned into spaces. Otherwise the text as the + /// one line it is measured as, with its control characters at their own width and its Unicode + /// space separators as spaces. /// internal static string[] CellLines(string text, bool honourBreaks) { - if (!honourBreaks) return [text]; + if (!honourBreaks) return [LayoutText.SeparatorSpacesToSpaces(text)]; var lines = LayoutText.SplitHardLines(text); for (var i = 0; i < lines.Length; i++) - lines[i] = LayoutText.ControlSpacesToSpaces(lines[i]); + lines[i] = LayoutText.SeparatorSpacesToSpaces(LayoutText.ControlSpacesToSpaces(lines[i])); return lines; } diff --git a/tests/VellumPdf.Layout.Tests/PageBreakTests.cs b/tests/VellumPdf.Layout.Tests/PageBreakTests.cs index 1ea5ab216..cc01e672a 100644 --- a/tests/VellumPdf.Layout.Tests/PageBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/PageBreakTests.cs @@ -600,7 +600,7 @@ public void ATaggedDocumentWithARectoBlank_hasNoStructureElementOnTheBlankPage() // ── Text that is not a break ───────────────────────────────────────────── [Fact] - public void AFormFeedInText_neverStartsAPage_andEveryElementDrawsItAsASpace() + public void AFormFeedInText_neverStartsAPage_andAParagraphHeadingListItemCellAndBandDrawItAsASpace() { var table = new TableElement(); table.AddRow().AddCell("cell\fx"); @@ -618,7 +618,7 @@ public void AFormFeedInText_neverStartsAPage_andEveryElementDrawsItAsASpace() Assert.Single(pages); // A paragraph, a heading, a list item, a table cell and a running band all draw the - // character as a space. + // character as a space. Preformatted is not among them: its constructor refuses U+000C. Assert.Contains("para z", pages[0].Texts); Assert.Contains("head w", pages[0].Texts); Assert.Contains("item y", pages[0].Texts); diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index 2377333e8..8b791b5d6 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -16,8 +16,8 @@ namespace VellumPdf.Layout.Tests; /// /// A tab, a line break or a form feed in a table cell or a running band no longer reaches glyph -/// lookup (#611, #613 item 34). A cell breaks its lines as a paragraph does, and every other -/// control white-space character is a space. +/// lookup (#611, #613 item 34). A carriage return, a line feed and a pair of them each end a +/// line in a cell, and every other white-space character except the no-break spaces is a space. /// /// The fixtures with a short page are 300x400pt with 10pt margins and two 100pt columns, in /// Helvetica 12pt: a line is 14.4pt and the default padding adds 8pt, so a cell of n lines is @@ -169,8 +169,8 @@ public void Standard14_everyLineBreakFormIsOneBreak(string text) } /// - /// A trailing break leaves a blank last line, and two breaks in a row a blank line between, - /// as in a paragraph: "a\n" is two lines tall and "a\n\nb" three. + /// A trailing break leaves a blank last line, and two breaks in a row a blank line between: + /// "a\n" is two lines tall and "a\n\nb" three. A paragraph drops the trailing one. /// [Theory] [InlineData("a\n", 36.8, new[] { "a" })] @@ -209,11 +209,13 @@ public void Standard14_aFormFeedIsOneSpace() } /// - /// A cell and a paragraph read the same text the same way: the same lines for a text that holds - /// a tab, a form feed and each form of line break. + /// A cell and a paragraph draw the same lines for one text that holds a tab, a form feed and + /// each form of line break. They differ on a trailing break, which a cell keeps as a blank + /// line, and on a run of spaces, which a paragraph collapses; the tests above and below pin + /// the cell's side of both. /// [Fact] - public void ACellAndAParagraphBreakTheSameTextIntoTheSameLines() + public void ACellAndAParagraphDrawOneMixedTextAsTheSameLines() { const string text = "x\tb\fc\r\nd\re\nf"; @@ -233,22 +235,25 @@ public void ACellAndAParagraphBreakTheSameTextIntoTheSameLines() } /// - /// A space separator that a font draws, such as U+2003, is left as written, so a cell that held - /// one before this change is drawn as it was: Helvetica has no glyph for it and the canvas - /// writes a question mark, and the cell is still one line. The no-break spaces keep their - /// meaning. + /// A space separator other than the no-break spaces is one space, as a paragraph reads it: + /// U+2003, U+3000, U+2009 and U+1680 are each one space and none is a question mark with the + /// not-encodable diagnostic. The no-break spaces keep their meaning, and a run of spaces is + /// kept as written. /// [Fact] - public void Standard14_aSpaceSeparatorIsLeftAlone() + public void Standard14_aSpaceSeparatorIsOneSpace_andTheNoBreakSpacesAreKept() { using var doc = ShortPage(); var t = Table12(); - t.AddRow().AddCell("a\u2003b").AddCell("c\u00A0d"); + t.AddRow().AddCell("a\u2003b\u3000c\u2009d\u1680e").AddCell("f\u00A0g\u202Fh\u2007i"); + t.AddRow().AddCell("j k").AddCell("l"); doc.Add(t); var content = Content(Save(doc)); - Assert.Equal(["a?b", "c\u00A0d"], Texts(content)); + // The Standard 14 encoding has no U+202F or U+2007 and reads each back as U+00A0. + Assert.Equal(["a b c d e", "f\u00A0g\u00A0h\u00A0i", "j k", "l"], Texts(content)); + Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.UnencodableCharacter); Assert.Equal(22.4, Heights(content)[0], 4); } @@ -303,6 +308,25 @@ public void AnAutoColumn_isSizedFromItsWidestLine() Assert.Equal(140, widths[0], 6); } + /// + /// The minimum an automatic column is squeezed to is the widest word of any line, not of the + /// whole text. On a page too narrow for both columns, two columns whose widest word is the + /// same "bbbbbbbb" get the same width, though one cell holds a shorter first line. + /// + [Fact] + public void AnAutoColumn_hasItsMinimumFromTheWordsOfEachLine() + { + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 120, 400), Margins = new EdgeInsets(10) }; + var t = new TableElement { DefaultCellStyle = Helvetica(12) }; + t.AddRow().AddCell("aa\nbbbbbbbb").AddCell("bbbbbbbb"); + doc.Add(t); + + var widths = Widths(Content(Save(doc))); + + Assert.Equal(2, widths.Length); + Assert.Equal(widths[0], widths[1], 6); + } + // ── Null text ──────────────────────────────────────────────────────────── /// A null cell text with explicit widths still saves and draws nothing, as before. @@ -404,8 +428,8 @@ public void Embedded_aTabAndALineBreakAreNotGlyphZero() /// /// A white-space character, between two letters in an embedded font, never produces glyph 0 - /// unless it is a space separator the font has no glyph for, which is written as it always was. - /// A control character that is not white space is not touched: U+0001 still reaches glyph 0. + /// and is written as the paragraph rule writes it: a space for every one but a line feed, a + /// carriage return and the no-break spaces, which are written as they are. A control character that is not white space is not touched: U+0001 still reaches glyph 0. /// [Fact] public void Embedded_noControlWhiteSpaceIsGlyphZero_andOtherControlsStillAre() @@ -422,9 +446,9 @@ public void Embedded_noControlWhiteSpaceIsGlyphZero_andOtherControlsStillAre() var shows = HexShows(Content(Save(doc))); - if (char.GetUnicodeCategory(c) == UnicodeCategory.SpaceSeparator) + if (c is '\u00A0' or '\u202F' or '\u2007') { - // Written as the font maps it, exactly as before this change. + // A no-break space is written as the font maps it. Assert.Equal([GlyphHex(font, "x" + c + "y")], shows); } else @@ -544,13 +568,13 @@ public void ABandCutsAtTheSpaceAFormFeedBecame() // ── Rows that cannot be cut ────────────────────────────────────────────── - /// The diagnostic a cell that reads its breaks as spaces is reported with, or null. + /// The diagnostic a cell that is laid out unbroken is reported with, or null. private static LayoutDiagnostic? CellReport(Document doc) => - doc.Diagnostics.SingleOrDefault(d => d.Code == LayoutDiagnosticCode.CellBreakDrawnAsSpace); + doc.Diagnostics.SingleOrDefault(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped); /// /// A header row whose breaks, honoured, leave no room under it for the row below: 2.3.3 drew - /// the cell on one line. The cell is drawn as one line of spaces and reported as a warning. + /// the cell on one line. The cell is drawn as one line, without its breaks, and reported as a warning. /// A header of 46 lines is 560pt and leaves 20pt, which holds the 20pt row below, so its /// breaks are kept. /// @@ -559,7 +583,7 @@ public void ABandCutsAtTheSpaceAFormFeedBecame() [InlineData(47, true)] [InlineData(48, true)] [InlineData(100, true)] - public void AHeaderThatWouldLeaveNoRoomForTheRowBelowReadsItsBreaksAsSpaces(int n, bool asSpaces) + public void AHeaderThatWouldLeaveNoRoomForTheRowBelowIsLaidOutUnbroken(int n, bool asSpaces) { using var doc = WidePage(); var t = Wide10(1900); @@ -574,7 +598,7 @@ public void AHeaderThatWouldLeaveNoRoomForTheRowBelowReadsItsBreaksAsSpaces(int Assert.Equal(1, PageCount(bytes)); if (asSpaces) { - Assert.Equal([Words(n, " "), "x"], texts); + Assert.Equal([Words(n, ""), "x"], texts); Assert.NotNull(report); Assert.Equal(LayoutDiagnosticSeverity.Warning, report.Severity); Assert.Equal(1, report.Count); @@ -593,7 +617,7 @@ public void AHeaderThatWouldLeaveNoRoomForTheRowBelowReadsItsBreaksAsSpaces(int /// table that 2.3.3 saved still saves with nothing refused. /// [Fact] - public void AHeaderTallerThanAPageReadsItsBreaksAsSpaces() + public void AHeaderTallerThanAPageIsLaidOutUnbroken() { using var doc = WidePage(); var t = Wide10(1900); @@ -603,20 +627,20 @@ public void AHeaderTallerThanAPageReadsItsBreaksAsSpaces() var texts = Texts(Content(Save(doc))); - Assert.Equal([Words(100, " "), "x"], texts); + Assert.Equal([Words(100, ""), "x"], texts); Assert.Equal(LayoutDiagnosticSeverity.Warning, CellReport(doc)!.Severity); } /// /// Rows joined by a RowSpan are never cut, so when their breaks, honoured, make the group taller - /// than a page, the cells that hold them read the breaks as spaces. A group of 46 lines plus a + /// than a page, the cells that hold them are laid out unbroken. A group of 46 lines plus a /// 20pt row is 580pt, which fits; 47 lines does not. /// [Theory] [InlineData(46, false)] [InlineData(47, true)] [InlineData(100, true)] - public void ARowSpanGroupThatWouldBeTallerThanAPageReadsItsBreaksAsSpaces(int n, bool asSpaces) + public void ARowSpanGroupThatWouldBeTallerThanAPageIsLaidOutUnbroken(int n, bool asSpaces) { using var doc = WidePage(); var t = Wide10(1500, 400); @@ -630,7 +654,7 @@ public void ARowSpanGroupThatWouldBeTallerThanAPageReadsItsBreaksAsSpaces(int n, Assert.Equal(1, PageCount(bytes)); if (asSpaces) { - Assert.Contains(Words(n, " "), texts); + Assert.Contains(Words(n, ""), texts); Assert.NotNull(CellReport(doc)); } else @@ -642,13 +666,13 @@ public void ARowSpanGroupThatWouldBeTallerThanAPageReadsItsBreaksAsSpaces(int n, /// /// Two rows that are each short enough, joined by a RowSpan, are too tall together: both - /// cells that hold breaks read them as spaces, and each is reported. 23 lines in each row is + /// cells that hold breaks are laid out unbroken, and each is reported. 23 lines in each row is /// 2 x 284 = 568pt, which fits; 24 lines is 592pt. /// [Theory] [InlineData(23, 0)] [InlineData(24, 2)] - public void ARowSpanGroupOfTwoRowsReadsEachBreakingCellAsOneLine(int n, int reported) + public void ARowSpanGroupOfTwoRowsLaysEachBreakingCellOutUnbroken(int n, int reported) { using var doc = WidePage(); var t = Wide10(1000, 900); @@ -659,9 +683,9 @@ public void ARowSpanGroupOfTwoRowsReadsEachBreakingCellAsOneLine(int n, int repo var bytes = Save(doc); Assert.Equal(1, PageCount(bytes)); - Assert.Equal(reported, doc.Diagnostics.Count(d => d.Code == LayoutDiagnosticCode.CellBreakDrawnAsSpace)); + Assert.Equal(reported, doc.Diagnostics.Count(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped)); if (reported > 0) - Assert.Equal(2, Texts(Content(bytes)).Count(x => x == Words(n, " "))); + Assert.Equal(2, Texts(Content(bytes)).Count(x => x == Words(n, ""))); } /// @@ -684,12 +708,12 @@ public void AnOrdinaryRowKeepsItsBreaksAndIsCut() } /// - /// A header that reads its breaks as spaces is drawn the same way on every page, including the + /// A header laid out unbroken is drawn the same way on every page, including the /// pages a cut row continues on: the long header string is shown once per page, each page /// reports it, and the report's count is the number of pages. /// [Fact] - public void AHeaderThatReadsItsBreaksAsSpacesDoesSoOnEveryPage() + public void AHeaderLaidOutUnbrokenIsDrawnSoOnEveryPage() { using var doc = WidePage(); var t = Wide10(1900); @@ -702,13 +726,13 @@ public void AHeaderThatReadsItsBreaksAsSpacesDoesSoOnEveryPage() var pages = PageCount(bytes); Assert.True(pages >= 2, "the row was not cut"); - Assert.Equal(pages, texts.Count(x => x == Words(60, " "))); + Assert.Equal(pages, texts.Count(x => x == Words(60, ""))); Assert.Equal(100, texts.Count(x => x == "ab")); Assert.Equal(pages, CellReport(doc)!.Count); } /// - /// A cell that reads its breaks as spaces is measured and wrapped as a cell with no break is, so + /// A cell laid out unbroken is measured and wrapped as a cell with no break is, so /// the table's rectangles are exactly those the same table had when a line feed was one more /// character of the line: the four borders below are what 2.3.3 drew for it, though 2.3.3 wrote /// the line feeds into the string. @@ -728,17 +752,17 @@ public void AFallbackHeaderKeepsTheGeometryOfAnUnbrokenLine() Assert.Equal( ["10 570 1930.09932 20", "1940.09932 570 49.90068 20", "10 550 1930.09932 20", "1940.09932 550 49.90068 20"], Borders(content)); - Assert.Equal([Words(60, " "), "h", "x", "y"], Texts(content)); + Assert.Equal([Words(60, ""), "h", "x", "y"], Texts(content)); } /// /// A header whose breaks, honoured, take the room a RowSpan group needs under it: the group has - /// no break of its own to give up, so the header's cell reads its breaks as spaces. The header + /// no break of its own to give up, so the header cell is laid out unbroken. The header /// of 30 lines is 368pt and the group 268pt, which do not fit 580pt together; with the header /// on one line they do. /// [Fact] - public void AHeaderThatTakesTheRoomOfARowSpanGroupReadsItsBreaksAsSpaces() + public void AHeaderThatTakesTheRoomOfARowSpanGroupIsLaidOutUnbroken() { using var doc = WidePage(); var t = Wide10(30, 1870); @@ -752,7 +776,7 @@ public void AHeaderThatTakesTheRoomOfARowSpanGroupReadsItsBreaksAsSpaces() var report = CellReport(doc); Assert.Equal(1, PageCount(bytes)); - Assert.Contains(Words(30, " "), texts); + Assert.Contains(Words(30, ""), texts); Assert.Equal(20, texts.Count(x => x == "ab")); Assert.NotNull(report); Assert.Contains("row 0, cell 1", report.Message, StringComparison.Ordinal); @@ -761,10 +785,10 @@ public void AHeaderThatTakesTheRoomOfARowSpanGroupReadsItsBreaksAsSpaces() /// /// A tab is one space wide where the raw character was measured at its own width, which can /// wrap a cell one line taller and push a RowSpan group over the page. "ab" and a tab and "ab" - /// fits a 24pt column on one line as one word, and as two words does not; the group of 46 plain + /// fits a 36pt column on one line as one word, and as two words does not; the group of 46 plain /// lines under it is exactly 580pt with the one line and 592pt with two. The cell is laid out - /// as it was measured before, with the tab drawn as a space, and nothing is reported because it - /// holds no line break. The borders are 2.3.3's. + /// as it was measured before, with the tab left out of the drawing and the report naming the + /// cell. The borders are 2.3.3's. /// [Fact] public void ATabThatWouldTipARowSpanGroupOverThePageIsLaidOutUnbroken() @@ -780,14 +804,14 @@ public void ATabThatWouldTipARowSpanGroupOverThePageIsLaidOutUnbroken() Assert.Equal(1, PageCount(bytes)); Assert.Equal(["10 10 36 580", "46 570 36 20", "46 10 36 560"], Borders(content)); - Assert.Contains("ab ab", Texts(content)); - Assert.Empty(doc.Diagnostics); + Assert.Contains("abab", Texts(content)); + Assert.Contains("row 0, cell 1", CellReport(doc)!.Message, StringComparison.Ordinal); } /// /// A renderer laid out without the document, through a context built with the public /// constructor, knows no page: it keeps every break, and a header that is then too tall is - /// the same refusal as before. The document supplies the page and reads them as spaces. + /// the same refusal as before. The document supplies the page and lays the cell out unbroken. /// [Fact] public void WithoutThePageTheBreaksAreKept() @@ -802,8 +826,8 @@ public void WithoutThePageTheBreaksAreKept() } /// - /// Strict diagnostics saves a table whose cell reads its breaks as spaces: the report is a - /// warning, because nothing is lost. + /// Strict diagnostics saves a table whose cell is laid out unbroken: the report is a warning, + /// because the text stays and only the separation of its words is lost. /// [Fact] public void StrictDiagnosticsSavesTheWarning() @@ -822,11 +846,11 @@ public void StrictDiagnosticsSavesTheWarning() } /// - /// A tab in a header or span-group cell is not a break, so it changes no height and is never - /// reported: only a carriage return or a line feed can make a row taller. + /// A tab in a header cell that fits a page does not send the table to the fallback: the tab is + /// one space and nothing is reported. /// [Fact] - public void ATabAloneIsNeverReported() + public void ATabInAHeaderThatFitsIsOneSpaceAndIsNotReported() { using var doc = WidePage(); var t = Wide10(1900); @@ -840,6 +864,163 @@ public void ATabAloneIsNeverReported() Assert.Empty(doc.Diagnostics); } + // ── The fallback draws no wider than it measured ───────────────────────── + + private static double WidthOf(string text, double size) => + new FontReference(Standard14.Helvetica).MeasureString(text, size); + + /// + /// A cell laid out unbroken is wrapped by its width with each control character at its own + /// width, which is zero in Helvetica. Drawn with each one as a space it would be wider than it + /// was measured and cross its border or the page edge: 60 two-letter lines joined by a line + /// feed drew 102.86pt in an 88pt box. With the characters left out, no line of the cell is + /// wider than the box it was wrapped to, and every letter is still drawn, in order. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AFallbackCellIsDrawnNoWiderThanItWasMeasured(bool fixedColumns) + { + using var doc = fixedColumns + ? WidePage() + : new Document { PageSize = new PdfRectangle(0, 0, 400, 600), Margins = new EdgeInsets(10) }; + var t = fixedColumns + ? Wide10(100, 100) + : new TableElement { DefaultCellStyle = Helvetica(10) }; + t.AddRow(isHeader: true).AddCell(Words(60)).AddCell("h"); + t.AddRow().AddCell("x").AddCell("y"); + doc.Add(t); + + var content = Content(Save(doc)); + var placements = Placements(content); + var header = placements.Where(p => p.Text.All(c => c is 'a' or 'b')).ToList(); + var right = fixedColumns ? 10 + 100 - 4 : 400 - 10; + + Assert.NotNull(CellReport(doc)); + Assert.Equal(Words(60, ""), string.Concat(header.Select(p => p.Text))); + Assert.True(header.Count > 1, "the cell was not wrapped"); + foreach (var p in header) + Assert.True(p.X + WidthOf(p.Text, 10) <= right + 0.001, $"\"{p.Text}\" at x={p.X} ends past {right}."); + } + + /// + /// A header that is too tall because of its line breaks gives up those breaks and nothing else: + /// a RowSpan group below it that does not fit with the tall header, and fits with the short + /// one, is not read as a reason to lay out the cells of every other row unbroken. The ordinary + /// row "x" and "y" keeps its two lines, and only the header cell is reported. + /// + [Fact] + public void AFallbackHeaderLeavesAnUnrelatedRowItsBreaks() + { + using var doc = WidePage(); + var t = Wide10(1000, 900); + t.AddRow(isHeader: true).AddCell(Words(60)).AddCell("h"); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("b"); + t.AddRow().AddCell("c"); + t.AddRow().AddCell("x\ny"); + doc.Add(t); + + var bytes = Save(doc); + var texts = Texts(Content(bytes)); + var reports = doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped).ToList(); + + Assert.Equal(1, PageCount(bytes)); + Assert.Contains(Words(60, ""), texts); + Assert.Contains("x", texts); + Assert.Contains("y", texts); + var report = Assert.Single(reports); + Assert.Contains("row 0, cell 0", report.Message, StringComparison.Ordinal); + } + + /// + /// A row that can be cut between its lines keeps them when a tab tips a group over the page + /// elsewhere. The columns are fixed, so the row's cell cannot change the group's height: the + /// tab cell of the group is laid out unbroken and is the only cell reported, and "x" and "y" + /// are two lines. + /// + [Fact] + public void ARowThatCanBeCutKeepsItsBreaksWhenATabTipsAGroup() + { + using var doc = WidePage(); + var t = Wide10(36, 36); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("ab\tab"); + t.AddRow().AddCell(Words(46, " ")); + t.AddRow().AddCell("x\ny"); + doc.Add(t); + + var texts = Texts(Content(Save(doc))); + var report = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped); + + Assert.Contains("abab", texts); + Assert.Contains("x", texts); + Assert.Contains("y", texts); + Assert.Contains("row 0, cell 1", report.Message, StringComparison.Ordinal); + } + + /// + /// When a header's line breaks take the room a group needs, the header gives up its breaks + /// and no more: a tab in another header cell stays one space and is not reported. + /// + [Fact] + public void AHeaderThatTakesTheRoomOfAGroupGivesUpOnlyItsBreaks() + { + using var doc = WidePage(); + var t = Wide10(30, 1800, 70); + t.AddRow(isHeader: true).AddCell("h").AddCell(Words(30)).AddCell("x\ty"); + t.AddRow().AddCell(new Cell(Words(20, " ")) { RowSpan = 2 }).AddCell("b"); + t.AddRow().AddCell("c"); + doc.Add(t); + + var texts = Texts(Content(Save(doc))); + var report = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped); + + Assert.Contains(Words(30, ""), texts); + Assert.Contains("x y", texts); + Assert.Contains("row 0, cell 1", report.Message, StringComparison.Ordinal); + } + + /// + /// Three rows chained by RowSpans, each one's span reaching into the next, are one group: 3 x + /// 200pt is 600pt, which is more than a page, though each pair is 400pt. All three cells that + /// hold breaks are laid out unbroken and reported, and the table saves. + /// + [Fact] + public void ARowSpanChainIsOneGroup() + { + using var doc = WidePage(); + var t = Wide10(1000, 900); + t.AddRow().AddCell(new Cell(Words(16)) { RowSpan = 2 }).AddCell("b"); + t.AddRow().AddCell(new Cell(Words(16)) { RowSpan = 2 }); + t.AddRow().AddCell(Words(16)); + doc.Add(t); + + var bytes = Save(doc); + + Assert.Equal(1, PageCount(bytes)); + Assert.Equal(3, doc.Diagnostics.Count(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped)); + } + + /// + /// The report is kept per table: two tables whose first header cell is laid out unbroken give + /// two reports, though both name row 0, cell 0. + /// + [Fact] + public void TwoTablesReportTheirOwnFallbackCells() + { + using var doc = WidePage(); + for (var i = 0; i < 2; i++) + { + var t = Wide10(1900); + t.AddRow(isHeader: true).AddCell(Words(60)); + t.AddRow().AddCell("x"); + doc.Add(t); + } + + Save(doc); + + Assert.Equal(2, doc.Diagnostics.Count(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped)); + } + private static void AssertNoControlCharacter(IEnumerable placements) { foreach (var p in placements) From aa783461e2f25a95ca31bcd22a7ec12906b7b506 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 00:32:19 +0100 Subject: [PATCH 03/48] test(layout): pin the fallback's geometry, steps and report counts Cover the fallback drawing no wider than it measured, a header step that ends its pass, a tab that tips a group without reaching a fixed column's rows, a header that gives up only its breaks, a RowSpan chain read as one group, a report per table, one report for a cut row, and a minimum column width taken from each line's words. --- src/VellumPdf.Layout/Elements/Table/Cell.cs | 4 +-- .../TableCellBreakTests.cs | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 903e9dc7a..1150f20f1 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -23,8 +23,8 @@ public sealed class Cell /// between characters. /// A carriage return and line feed pair, a lone carriage return and a lone line feed /// each end a line. An empty line between two of them is a blank line one leading tall, and - /// so is the one after a trailing break: the text a followed by a line feed is two lines here, where a - /// draws one. Runs of spaces are kept as written, where a + /// so is the one after a trailing break: the text a followed by a line feed is two lines + /// here, where a draws one. Runs of spaces are kept as written, where a /// paragraph collapses them. Every other white-space control character, which is a tab, a form /// feed, a line tabulation, a next-line character, U+2028 and U+2029, is one space, and so is /// every Unicode space separator other than the no-break spaces, such as U+2003, so none of diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index 8b791b5d6..08d9c276a 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -1000,6 +1000,32 @@ public void ARowSpanChainIsOneGroup() Assert.Equal(3, doc.Diagnostics.Count(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped)); } + /// + /// A cell that is laid out unbroken is reported where it is first drawn, so a cut row whose + /// cell is one of them is reported once, not once per page it spans. Row 2 is cut across + /// pages, and its two cells, which are not in the RowSpan group in the last row, are laid out + /// unbroken because their columns are automatic and the group's cell is in them. + /// + [Fact] + public void ACutRowWithAFallbackCellIsReportedOnce() + { + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 300, 200), Margins = new EdgeInsets(10) }; + var seventy = string.Join(" ", Enumerable.Repeat("wd", 70)) + "\tx"; + var t = new TableElement { DefaultCellStyle = Helvetica(12) }; + t.AddRow().AddCell(new Cell("q") { ColSpan = 2 }).AddCell("wd wd wd wd wd"); + t.AddRow().AddCell(Words(40).Replace("ab", "wd")).AddCell("q"); + t.AddRow().AddCell("t\t").AddCell(seventy); + t.AddRow().AddCell(seventy).AddCell(new Cell("aaaa") { RowSpan = 2, ColSpan = 2 }); + doc.Add(t); + + var bytes = Save(doc); + var cut = doc.Diagnostics.Single(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped + && d.Message.Contains("row 2, cell 1", StringComparison.Ordinal)); + + Assert.True(PageCount(bytes) > 2, "the row was not cut"); + Assert.Equal(1, cut.Count); + } + /// /// The report is kept per table: two tables whose first header cell is laid out unbroken give /// two reports, though both name row 0, cell 0. From 6b8ac658430befc40719b7df2e1d139316f89e34 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 00:37:35 +0100 Subject: [PATCH 04/48] test(layout): reach the header step's pass with automatic columns --- tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index 08d9c276a..b823bfd72 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -907,13 +907,17 @@ public void AFallbackCellIsDrawnNoWiderThanItWasMeasured(bool fixedColumns) /// A header that is too tall because of its line breaks gives up those breaks and nothing else: /// a RowSpan group below it that does not fit with the tall header, and fits with the short /// one, is not read as a reason to lay out the cells of every other row unbroken. The ordinary - /// row "x" and "y" keeps its two lines, and only the header cell is reported. + /// row "x" and "y" keeps its two lines, and only the header cell is reported. With automatic + /// columns the row shares a column with the group, so a pass that went on to judge the group + /// by the header's old height would reach it. /// - [Fact] - public void AFallbackHeaderLeavesAnUnrelatedRowItsBreaks() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AFallbackHeaderLeavesAnUnrelatedRowItsBreaks(bool autoColumns) { using var doc = WidePage(); - var t = Wide10(1000, 900); + var t = autoColumns ? new TableElement { DefaultCellStyle = Helvetica(10) } : Wide10(1000, 900); t.AddRow(isHeader: true).AddCell(Words(60)).AddCell("h"); t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("b"); t.AddRow().AddCell("c"); From 2a221067687a1f5c289a5424b0a6e3fde6d88e37 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 00:41:17 +0100 Subject: [PATCH 05/48] docs(changelog): state the cell white-space rule and its measured output changes --- CHANGELOG.md | 95 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 66 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77b46334c..bbfed061f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,11 +8,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added -- **`LayoutDiagnosticCode.CellBreakDrawnAsSpace` (301).** A table cell of a header row, or of rows - joined by a `RowSpan`, holds a line break that was drawn as a space because honouring it would - have made those rows taller than a page. A warning: no text is lost, and `StrictDiagnostics` - saves. `Count` is the number of times the cell was drawn, so a repeated header row counts once - per page. See the entry for #611 under Fixed. +- **`LayoutDiagnosticCode.CellWhiteSpaceDropped` (301).** A table cell was laid out as one + unbroken line, and its tabs and line breaks were left out of what is drawn, because honouring the + line breaks of the cells around it would have made a header row or rows joined by a `RowSpan` + taller than a page. A warning, so `StrictDiagnostics` saves: the text stays, and the words those + characters separated run together in the drawing and in extracted text. `Count` is the number of + times the cell was drawn, so a repeated header row counts once per page. See the entry for #611 + under Fixed. - **`Preformatted`, a block that keeps every space and tab (#591).** `Document.Add(Preformatted)` draws text whose spacing is its meaning: command blocks, configuration, ASCII tables. The default @@ -493,32 +495,67 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). lookup (#611, #613).** A cell split its text on spaces only, so a tab was written as glyph 0 in an embedded font (the ToUnicode map held `<0000> <0009>`, and veraPDF failed PDF/A-2u clause 6.2.11.8) and as a raw 0x09 byte in a Standard 14 font, and a line feed was one line holding glyph - 0, or a string-escaped `\n`. A cell now reads its text as a paragraph does. A carriage return and - line feed pair, a lone carriage return and a lone line feed each end a line, and an empty line - between two of them, or after the last, is a blank line. Every other white-space control - character (a tab, a form feed, a line tabulation, a next-line character, U+2028 and U+2029) is - drawn as one space. A column sized automatically is as wide as the widest line. The no-break - spaces and the other space separators, such as U+2003, are written as before. - A running band draws the same characters as spaces, so the form feed of #613 item 34 is a space - there too, and a band's text is measured and cut as drawn. - **Deliberate output changes:** `AB` in a cell is `(A B)` in Standard 14 and glyph 3 between - the two letters in an embedded font, with no `<0000>` entry in the ToUnicode map. `line1line2` - is two show strings, the second one leading lower, in a row 14.4 + 14.4 + 8 pt tall at 12 pt, - where it was one. A cell with none of these characters, in a table with none of them, saves to - the same bytes as before. A table whose cell holds a line break gets taller rows and different - automatic column widths, and a paragraph is unchanged. + 0, or a string-escaped `\n`. A cell now reads its text by one rule. A carriage return and line + feed pair, a lone carriage return and a lone line feed each end a line. An empty line between two + of them is a blank line, and so is the one after a trailing break: `a` is two lines in a cell + where a paragraph draws one. Runs of spaces are kept as written, where a paragraph collapses them. + Every other white-space character except the no-break spaces U+00A0, U+202F and U+2007 is one + space, which is the word separation `ParagraphRenderer` applies: a tab, a form feed, a line + tabulation, a next-line character, U+2028, U+2029, and the Unicode space separators such as + U+2003, U+3000, U+2009 and U+1680. An automatically sized column takes its minimum width from the + widest word and its maximum from the widest line, each line measured by itself where 2.3.3 + measured the whole text. The width the column is given is shared out as before, and can be more + than the maximum or less than the minimum. + A running band draws a tab, a line break or a form feed as one space, so the form feed of #613 + item 34 is a space there too, and a band's text is measured and cut as drawn. A band reads only + those control characters: a Unicode space separator in a band is written as before. + **Deliberate output changes:** + - `AB` in a cell is `(A B)` in Standard 14 and glyph 3 between the two letters in an + embedded font, with no `<0000>` entry in the ToUnicode map. + - `line1line2` is two show strings, the second one leading lower, in a row 14.4 + 14.4 + 8 pt + tall at 12 pt, where it was one. A table whose cell holds a line break gets taller rows and + different automatic column widths. A cell with none of the characters above, in a table with + none of them or of a Unicode space separator, saves to the same bytes as before. + - A Unicode space separator other than the no-break spaces in a cell, such as U+2003, is one + space. Standard 14 fonts drew `?` for it and listed `UnencodableCharacter`; an embedded font + drew whatever glyph its map held. Of 20,000 random tables whose texts hold no control + character, 9,408 change, and the pool's one text with a separator is the U+2003 one. Because + the character's width changes, so can the wrapping: of the 40,000 tables measured, two that + saved before (one in each pool) now throw the too-tall `InvalidOperationException`, and both + save again with the rule switched off. + - A band template measured a tab, a line feed, a carriage return or a form feed at its font's + width for that character, zero in Helvetica, and now measures each as one space. A band that + fit can therefore be cut: `A` followed by 120 tabs and `B` in Helvetica 10 on a 300 pt page + saved with no truncation, and now draws 1 of its 122 characters and reports `BandTruncated`, + which `StrictDiagnostics` refuses. + - A table that 2.3.3 refused as too tall can now save: 13 of 40,000 random tables (ten of the + 20,000 with control characters, three of the 20,000 without). All 13 are refusals that name a + `RowSpan` group. Columns are now measured per line and a space separator is measured as a + space, and both change the wrapping; I did not isolate which of the two shortens each group. + `qpdf --check` exits 0 for all 13. + - A cell with a very large number of lines can be refused where 2.3.3 saved it, because 2.3.3 + drew its line feeds inside one line. One cell of 2,500,000 two-letter words joined by LF, on a + 2000 x 600 pt page in a 1900 pt column, saved in 314 pages on 2.3.3 and now stops at the limit + of 50,000 page continuations with the `InvalidOperationException` that names it. The same cell + of 2,300,000 words saves in 48,937 pages, and one of 2,400,000 is refused. - **A header row, or rows joined by a `RowSpan`, whose breaks would make them taller than a page keep the one-line layout.** Those rows are never cut between their lines, so honouring the - breaks would turn a table that saved into a too-tall refusal. A cell of them that holds a - carriage return or line feed is wrapped at spaces alone and sized from its whole text, as - 2.3.3 did, with each break drawn as a space, and the save lists the cell as the new - `LayoutDiagnosticCode.CellBreakDrawnAsSpace` (301, a warning, so `StrictDiagnostics` still - saves). A header row of 46 two-letter lines, 560pt tall, keeps its lines on a 580pt page - beside a 20pt row; one of 47 does not. Every other row keeps its breaks and is cut between - its lines when it is taller than a page. When a header or a group is still too tall, the - header's cells go the same way, and then every cell that holds a tab or a form feed, so a table - that 2.3.3 saved keeps its 2.3.3 row heights and is not refused. A renderer laid out through a - context built with the public constructor knows no page and keeps every break. + breaks would turn a table that saved into a too-tall refusal. A cell of them is then wrapped at + spaces alone and sized from its whole text, as 2.3.3 did, with each tab and break measured at + the width its font gives it and then left out of what is drawn, so no line is wider than it was + measured. A header of 60 two-letter lines stays inside its cell in a 100pt column and in + automatic columns on a 400pt page, and `pdftotext -raw` returns all 120 letters in order. The + words those characters separated run together, in the drawing and in extracted text. The save lists the cell as the new `LayoutDiagnosticCode.CellWhiteSpaceDropped` + (301, a warning, so `StrictDiagnostics` still saves). A header row of 46 two-letter lines, + 560pt tall, keeps its lines on a 580pt page beside a 20pt row; one of 47 does not. Which cells + fall back is decided in steps, each taken only while the rows still do not fit a page, and + each ending its pass so the heights are taken again before the next step is judged: the cells + of the group that hold a carriage return or line feed; then those of the header rows; then + the cells that hold any control white-space character and sit in the group, in the header rows, + or in an automatically sized column that one of those cells is in. A cell that holds only a line + feed can fall back at any of the three steps. A cell no step reaches keeps its breaks and is cut + between its lines when its row is taller than a page. A renderer laid out through a context + built with the public constructor knows no page and keeps every break. - **`/FontBBox` of an embedded font is the font's own bounding box (#596).** The descriptor of every embedded TrueType and OpenType font held `[0, hhea descender, 1000 * 1000 / unitsPerEm, hhea ascender]`: a zero for xMin and a constant for xMax, so DejaVu Sans, Liberation Sans and Liberation From 4e295a97248c5bd89951a9089816d329bc033834 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 01:53:11 +0100 Subject: [PATCH 06/48] fix(layout): keep other Unicode spaces in a cell and judge groups one at a time Drop the reading of Unicode space separators as spaces: two tables that saved are refused with it, and a paragraph's rule for them is a change for a later major. A group step that adds a cell now ends its pass, so the next group is judged by heights taken after the change. The text a page label prints for {page} is read as the template's own text is. The cached decision is keyed on the width and the boxes' heights, not their x, so mirrored margins reuse it. --- src/VellumPdf.Layout/Core/LayoutText.cs | 21 +-- src/VellumPdf.Layout/Elements/BandTemplate.cs | 8 +- src/VellumPdf.Layout/Elements/RunningBand.cs | 6 +- src/VellumPdf.Layout/Elements/Table/Cell.cs | 38 ++--- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 26 +-- .../Rendering/Table/TableRenderer.cs | 41 ++--- .../TableCellBreakTests.cs | 151 ++++++++++++++++-- 7 files changed, 205 insertions(+), 86 deletions(-) diff --git a/src/VellumPdf.Layout/Core/LayoutText.cs b/src/VellumPdf.Layout/Core/LayoutText.cs index 895214793..3622efbe1 100644 --- a/src/VellumPdf.Layout/Core/LayoutText.cs +++ b/src/VellumPdf.Layout/Core/LayoutText.cs @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 using System.Globalization; -using VellumPdf.Fonts; namespace VellumPdf.Layout.Core; @@ -14,10 +13,8 @@ namespace VellumPdf.Layout.Core; /// A character is a control space when holds for it and it is /// not in the Unicode category Space Separator: the C0 and C1 controls tab, line feed, line /// tabulation, form feed, carriage return and next line, and the line and paragraph separators -/// U+2028 and U+2029. The Unicode space separators other than the no-break spaces, such as U+2003 -/// EM SPACE, are separator spaces: a cell reads each as U+0020, as -/// reads every white-space character except a line -/// feed and the no-break spaces U+00A0, U+202F and U+2007. A band reads only the control spaces. +/// U+2028 and U+2029. The no-break spaces and the other space separators, such as U+2003 EM SPACE, +/// are not control spaces: a font draws them, so they are left as written. /// internal static class LayoutText { @@ -65,20 +62,6 @@ internal static string[] SplitHardLines(string text) return [.. lines]; } - /// - /// True for a Unicode space separator that a cell reads as U+0020: every character of the - /// category Space Separator except U+0020 itself and the no-break spaces. - /// - internal static bool IsSeparatorSpace(char c) => - c != ' ' && !NoBreakSpaces.IsNoBreakSpace(c) - && char.GetUnicodeCategory(c) == UnicodeCategory.SpaceSeparator; - - /// - /// Returns with every separator space replaced by U+0020, or the same - /// instance when it holds none. A control space is left as it is. - /// - internal static string SeparatorSpacesToSpaces(string text) => Replace(text, IsSeparatorSpace); - /// /// Returns with every control space removed, or the same instance when /// it holds none. diff --git a/src/VellumPdf.Layout/Elements/BandTemplate.cs b/src/VellumPdf.Layout/Elements/BandTemplate.cs index e88cdf762..48cdbba42 100644 --- a/src/VellumPdf.Layout/Elements/BandTemplate.cs +++ b/src/VellumPdf.Layout/Elements/BandTemplate.cs @@ -171,8 +171,12 @@ internal sealed class BandText /// internal void Reset(int pageNumber, int totalPages, string? pageLabel = null) { - _values[(int)BandToken.Page] = - pageLabel ?? pageNumber.ToString(System.Globalization.CultureInfo.InvariantCulture); + // The label is caller text, so a tab, a line break or a form feed in it is a space, as it is + // in the template's own text; the replacement keeps the length, so what is measured is what + // is drawn. + _values[(int)BandToken.Page] = pageLabel is null + ? pageNumber.ToString(System.Globalization.CultureInfo.InvariantCulture) + : LayoutText.ControlSpacesToSpaces(pageLabel); _values[(int)BandToken.Pages] = totalPages.ToString(System.Globalization.CultureInfo.InvariantCulture); long length = Template.LiteralLength; diff --git a/src/VellumPdf.Layout/Elements/RunningBand.cs b/src/VellumPdf.Layout/Elements/RunningBand.cs index a595b097a..5caf16622 100644 --- a/src/VellumPdf.Layout/Elements/RunningBand.cs +++ b/src/VellumPdf.Layout/Elements/RunningBand.cs @@ -29,8 +29,10 @@ public sealed class RunningBand /// Text template — may contain {page} and/or {pages}. /// /// A band is one line: a tab, a line break, a form feed or any other white-space control - /// character in the template is drawn as one space each, and is measured as one, so no control - /// character reaches the font from it. + /// character in the template is drawn as one space each, and is measured as one, so no + /// white-space control character reaches the font from it. The same holds for the text a + /// prints for {page}. A control character that is not white + /// space, such as U+0001, is written as it is. /// Not checked when it is set: the constructor stores a null template, and the save throws /// where the band is first drawn. A template that does not /// fit the content box is truncated, and refused only in strict mode; diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 1150f20f1..40faf580b 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -24,15 +24,15 @@ public sealed class Cell /// A carriage return and line feed pair, a lone carriage return and a lone line feed /// each end a line. An empty line between two of them is a blank line one leading tall, and /// so is the one after a trailing break: the text a followed by a line feed is two lines - /// here, where a draws one. Runs of spaces are kept as written, where a - /// paragraph collapses them. Every other white-space control character, which is a tab, a form - /// feed, a line tabulation, a next-line character, U+2028 and U+2029, is one space, and so is - /// every Unicode space separator other than the no-break spaces, such as U+2003, so none of - /// them reaches a font. The no-break spaces U+00A0, U+202F and U+2007 are written as they are. - /// A column sized automatically takes its minimum from the widest word and its maximum from the - /// widest line, each line of the cell measured on its own, where 2.3.3 measured the whole - /// text as one line. The width the column is then given is shared out among the columns as it - /// was, and can be more than the maximum or less than the minimum. + /// here, where a draws one. Runs of spaces are kept as + /// written, where a paragraph collapses them. Every other white-space control character, which + /// is a tab, a form feed, a line tabulation, a next-line character, U+2028 and U+2029, is one + /// space, so it reaches no font as a control character. The no-break spaces are written as they + /// are, as in a paragraph. The other space separators, such as U+2003, are written as they are + /// too, where a paragraph reads them as spaces. A column sized automatically takes its minimum + /// from the widest word and its maximum from the widest line, each line of the cell measured on + /// its own, where 2.3.3 measured the whole text as one line. The width the column is then given is shared out among + /// the columns as it was, and can be more than the maximum or less than the minimum. /// A control character that is not white space, such as U+0001, is written as it is: in a /// standard-14 font as its WinAnsi code, and in an embedded font as whatever glyph the font's /// character map gives it, which is .notdef (glyph 0) when the map has no entry. The save lists @@ -42,17 +42,19 @@ public sealed class Cell /// joined by a , is laid out unbroken when honouring the line breaks of /// those rows would make them taller than a page, because such rows are never cut between /// their lines. It is then wrapped at spaces alone and sized from its whole text, each tab and - /// line break in it measured at the width its font gives it and left out of what is drawn, - /// so the words they separated run together in the drawing and in extracted text, and - /// no line is wider than it was measured. The save lists the cell as + /// line break in it measured at the width its font gives it and left out of what is drawn. The + /// words they separated run together in the drawing and in extracted text, and no line is + /// wider than it was measured, though a glyph wider than its column can still extend past it, + /// as in any cell. The save lists the cell as /// , a warning that - /// saves. Which cells are read this way is decided in - /// three steps, each taken only while the rows still do not fit: the cells of the group that + /// saves. Which cells are laid out this way is decided + /// in three steps, each taken only while the rows still do not fit: the cells of the group that /// hold a carriage return or a line feed, then those of the header rows, then every cell that - /// holds any control white space and sits in the group, in the header rows, or in an - /// automatically sized column one of those cells is in. A cell that holds only a line feed can - /// be read this way by any step. A cell in a row that can be cut between its lines, and in a - /// fixed-width column apart from the rows named, keeps its breaks. Do not pass a line + /// holds any control white space and sits in the group's rows, in the header rows, or in an + /// automatically sized column that a cell of those rows is in. A cell that holds only a line + /// feed can be laid out this way by any step. A cell outside those rows and columns keeps its + /// breaks, and a row that can be cut between its lines is cut when it is taller than a page, + /// which a header row or a span group never is: those are refused. Do not pass a line /// break in a header row or a span group that is that tall and expect the lines to be drawn: /// move the text to a row that can be cut, or shorten it. A renderer you lay out without the /// document, through a built with the public constructor, knows no diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index 2839f894d..ce3eacabd 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -120,24 +120,26 @@ public enum LayoutDiagnosticCode /// A table cell holds a tab, a line break or another control white-space character, and the /// save left it out of what it drew, because honouring the line breaks of the cells around it /// would have made rows that cannot be cut between their lines taller than a page. - /// is the number of times the cell was drawn, so a header - /// row that repeats on every page counts once per page, and the message names the row and the - /// cell, counted from zero in the order they were added. + /// is the number of pages on which the cell was drawn from + /// its first line, so a header row that repeats on every page counts once per page, and any + /// other cell counts once, however many pages a cut row spans. The message names the row and + /// the cell, counted from zero in the order they were added. /// /// /// The words such a character separated run together in the cell, in drawing and in /// extracted text, and nothing else is lost, so this is a warning and strict mode saves. /// The cell is wrapped at spaces alone and sized from its whole text, each such character /// measured at the width its font gives it and then not drawn, so no line is wider than it was - /// measured and nothing crosses the cell. The rows in question are the leading header rows, - /// which repeat on every page and are never cut, and the rows joined by a - /// , which are never cut either. A cell is read this - /// way in three steps, each taken only when the rows still do not fit a page: a cell of the - /// group that holds a carriage return or a line feed; then such a cell of the header rows; then - /// a cell that holds any control white space and sits in the group, in the header rows, or in - /// an automatically sized column that one of those cells is in. A cell that holds only a line - /// feed can be read this way by any of the three. A cell no step reaches keeps its breaks and - /// is not reported, in a table that has other cells read this way as in any other. + /// measured. A glyph wider than its column can still extend past it, as in any cell. The rows + /// in question are the leading header rows, which repeat on every page and are never cut, and + /// the rows joined by a , which are never cut either. + /// A cell is laid out this way in three steps, each taken only when the rows still do not fit a + /// page: a cell of the group that holds a carriage return or a line feed; then such a cell of + /// the header rows; then a cell that holds any control white space and sits in the rows of the + /// group or the header, or in an automatically sized column that a cell of those rows is in. A + /// cell that holds only a line feed can be laid out this way by any of the three. A cell no + /// step reaches keeps its breaks and is not reported, in a table that has other such cells as + /// in any other. /// Do not pass a header row or a span group whose line breaks do not fit one page: put /// the breaks in rows that can be cut, or shorten the text. /// diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index ce157c99b..33650231a 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -62,10 +62,12 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IPlacementSourc // it and gives it to the renderers that draw the pages; null when every break is kept. private HashSet<(int Row, int Cell)>? _oneLine; - // What _oneLine was decided for: the table width and the fresh boxes. A renderer that carries - // the decision to the next page reuses it when it lays out at the same width and boxes, and so - // resolves the grid once, where deciding again would resolve it once per pass on every page. - private (double Width, LayoutBox First, LayoutBox Second)? _decidedFor; + // What _oneLine was decided for: the table width and the vertical extent of the two fresh boxes. + // A renderer that carries the decision to the next page reuses it when it lays out at the same + // width and heights, and so resolves the grid once, where deciding again would resolve it once + // per pass on every page. The boxes' x is left out of the key: the decision never reads it, and + // mirrored margins move it on every other page. + private (double Width, double Top0, double Bottom0, double Top1, double Bottom1)? _decidedFor; /// The lines each cell of one row wraps into, at one table width. private sealed class RowLines(int row, double width, List?[] cells) @@ -249,7 +251,9 @@ public LayoutResult Layout(LayoutContext context) // A decision made for this width and these boxes by the renderer that handed the table // over stands: the cells it read unbroken are the cells this layout reads unbroken. - var key = fresh is { Length: 2 } ? (area.Width, fresh[0], fresh[1]) : ((double, LayoutBox, LayoutBox)?)null; + var key = fresh is { Length: 2 } + ? (area.Width, fresh[0].Y, fresh[0].Bottom, fresh[1].Y, fresh[1].Bottom) + : ((double, double, double, double, double)?)null; var decided = key is not null && _decidedFor is { } was && was.Equals(key.Value); if (!decided) _oneLine = null; @@ -537,11 +541,11 @@ void Reach(int from, int to) var height = 0.0; for (var i = first; i <= last; i++) height += _rowHeights[i]; if (FitsFresh(fresh, headerHeight, height)) continue; - if (CollectBreaks(first, last)) continue; - - // The header's own heights are taken again before another group is judged by them. + // Every step that adds a cell ends the pass: the next group is judged by heights that + // this step changes, a column's width among them. + if (CollectBreaks(first, last)) return found; if (header.Count > 0 && CollectBreaks(0, header[^1])) return found; - CollectControlSpace(first, last); + if (CollectControlSpace(first, last)) return found; } return found; @@ -1381,11 +1385,11 @@ private static List WrapLine(string text, TextStyle style, double maxWid /// . A hard line ends at a carriage return and line feed pair, a lone /// carriage return or a lone line feed. An empty hard line is a blank line, and so is the one /// after a trailing break, which a paragraph drops. Runs of spaces are kept as written, where a - /// paragraph collapses them. Every other white-space character except the no-break spaces is a - /// space. A null text, and text with nothing in it, is one empty line. With - /// false the text is wrapped at spaces alone, measuring each - /// control white-space character at its own width, and the lines are drawn without them, so a - /// line is never wider than it was measured. + /// paragraph collapses them. Every other white-space control character is a space; the no-break + /// spaces and the other space separators are written as they are. A null text, and text with + /// nothing in it, is one empty line. With false the text is + /// wrapped at spaces alone, measuring each control white-space character at its own width, and + /// the lines are drawn without them, so a line is never wider than it was measured. /// private static List WordWrapLines(string text, TextStyle style, double maxWidth, bool honourBreaks) { @@ -1410,17 +1414,16 @@ private static List WordWrapLines(string text, TextStyle style, double m /// /// The lines a cell's text is measured in. When is true, the - /// hard lines of the text with their white space turned into spaces. Otherwise the text as the - /// one line it is measured as, with its control characters at their own width and its Unicode - /// space separators as spaces. + /// hard lines of the text with their control white space turned into spaces. Otherwise the text + /// itself as the one line it is measured as, control characters and all. /// internal static string[] CellLines(string text, bool honourBreaks) { - if (!honourBreaks) return [LayoutText.SeparatorSpacesToSpaces(text)]; + if (!honourBreaks) return [text]; var lines = LayoutText.SplitHardLines(text); for (var i = 0; i < lines.Length; i++) - lines[i] = LayoutText.SeparatorSpacesToSpaces(LayoutText.ControlSpacesToSpaces(lines[i])); + lines[i] = LayoutText.ControlSpacesToSpaces(lines[i]); return lines; } diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index b823bfd72..d3169f740 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -17,7 +17,7 @@ namespace VellumPdf.Layout.Tests; /// /// A tab, a line break or a form feed in a table cell or a running band no longer reaches glyph /// lookup (#611, #613 item 34). A carriage return, a line feed and a pair of them each end a -/// line in a cell, and every other white-space character except the no-break spaces is a space. +/// line in a cell, and every other white-space control character is a space. /// /// The fixtures with a short page are 300x400pt with 10pt margins and two 100pt columns, in /// Helvetica 12pt: a line is 14.4pt and the default padding adds 8pt, so a cell of n lines is @@ -235,25 +235,23 @@ public void ACellAndAParagraphDrawOneMixedTextAsTheSameLines() } /// - /// A space separator other than the no-break spaces is one space, as a paragraph reads it: - /// U+2003, U+3000, U+2009 and U+1680 are each one space and none is a question mark with the - /// not-encodable diagnostic. The no-break spaces keep their meaning, and a run of spaces is - /// kept as written. + /// A space separator that a font draws, such as U+2003, is left as written, so a cell that held + /// one is drawn as it was: Helvetica has no glyph for it and the canvas writes a question + /// mark, and the cell is still one line. The no-break spaces keep their meaning, and a run of + /// spaces is kept as written. /// [Fact] - public void Standard14_aSpaceSeparatorIsOneSpace_andTheNoBreakSpacesAreKept() + public void Standard14_aSpaceSeparatorIsLeftAlone() { using var doc = ShortPage(); var t = Table12(); - t.AddRow().AddCell("a\u2003b\u3000c\u2009d\u1680e").AddCell("f\u00A0g\u202Fh\u2007i"); + t.AddRow().AddCell("a\u2003b").AddCell("c\u00A0d"); t.AddRow().AddCell("j k").AddCell("l"); doc.Add(t); var content = Content(Save(doc)); - // The Standard 14 encoding has no U+202F or U+2007 and reads each back as U+00A0. - Assert.Equal(["a b c d e", "f\u00A0g\u00A0h\u00A0i", "j k", "l"], Texts(content)); - Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.UnencodableCharacter); + Assert.Equal(["a?b", "c\u00A0d", "j k", "l"], Texts(content)); Assert.Equal(22.4, Heights(content)[0], 4); } @@ -428,8 +426,8 @@ public void Embedded_aTabAndALineBreakAreNotGlyphZero() /// /// A white-space character, between two letters in an embedded font, never produces glyph 0 - /// and is written as the paragraph rule writes it: a space for every one but a line feed, a - /// carriage return and the no-break spaces, which are written as they are. A control character that is not white space is not touched: U+0001 still reaches glyph 0. + /// unless it is a space separator the font has no glyph for, which is written as it always was. + /// A control character that is not white space is not touched: U+0001 still reaches glyph 0. /// [Fact] public void Embedded_noControlWhiteSpaceIsGlyphZero_andOtherControlsStillAre() @@ -446,9 +444,9 @@ public void Embedded_noControlWhiteSpaceIsGlyphZero_andOtherControlsStillAre() var shows = HexShows(Content(Save(doc))); - if (c is '\u00A0' or '\u202F' or '\u2007') + if (char.GetUnicodeCategory(c) == UnicodeCategory.SpaceSeparator) { - // A no-break space is written as the font maps it. + // Written as the font maps it, exactly as before this change. Assert.Equal([GlyphHex(font, "x" + c + "y")], shows); } else @@ -566,6 +564,55 @@ public void ABandCutsAtTheSpaceAFormFeedBecame() Assert.Single(doc.BandTruncations); } + /// + /// The text a page label prints reaches a band's {page} as a value, not as template text, + /// so it is read the same way: a tab and a line break in the label prefix are spaces, in the + /// drawing and in the width the band is cut to. + /// + [Fact] + public void ABandDrawsAControlSpaceInAPageLabelAsASpace() + { + using var doc = ShortPage(); + doc.PageLabel = new PageLabelRange(PdfPageLabelStyle.Decimal, "A\tB\n", 1); + doc.SetFooter("p {page} of {pages}", Helvetica(10)); + doc.Add(new Paragraph("body", Helvetica(10))); + + var content = Content(Save(doc)); + + Assert.Contains("p A B 1 of 1", Texts(content)); + AssertNoControlCharacter(Placements(content)); + } + + /// + /// The same label in an embedded font under PDF/A-2u: no glyph 0, so veraPDF finds no + /// clause 6.2.11.8 failure and the preflight no notdef assertion. + /// + [Fact] + public void ABandWithAControlSpaceInAPageLabelIsPdfA2uClean() + { + RequireDejaVu(); + using var doc = EmbeddedDoc(out var font, PdfConformance.PdfA2u); + doc.PageLabel = new PageLabelRange(PdfPageLabelStyle.Decimal, "A\tB\n", 1); + doc.SetFooter("p {page} of {pages}", new TextStyle { FontRef = font, FontSize = 10 }); + doc.Add(new Paragraph("body", new TextStyle { FontRef = font, FontSize = 10 })); + var bytes = Save(doc); + var path = Path.Combine(_tempDir, "label-a2u.pdf"); + File.WriteAllBytes(path, bytes); + + Assert.Contains(GlyphHex(font, "p A B 1 of 1"), HexShows(Content(bytes))); + + ExternalTool.TryRun("verapdf", ["--flavour", "2u", path], + out var vexit, out var report, out var verr, out var vtimed, timeoutMs: 120_000); + Assert.False(vtimed); + Assert.True(vexit is 0 or 1, $"veraPDF exited {vexit}\n{report}\n{verr}"); + Assert.True(report.Contains("isCompliant=\"true\"", StringComparison.Ordinal), report); + + var rules = VellumPdf.Conformance.PdfPreflight + .Validate(bytes, VellumPdf.Conformance.PdfConformance.PdfA2U) + .Assertions.Select(a => a.RuleId).ToList(); + Assert.DoesNotContain("ISO19005-2:6.2.11.8-notdef", rules); + } + // ── Rows that cannot be cut ────────────────────────────────────────────── /// The diagnostic a cell that is laid out unbroken is reported with, or null. @@ -983,6 +1030,78 @@ public void AHeaderThatTakesTheRoomOfAGroupGivesUpOnlyItsBreaks() Assert.Contains("row 0, cell 1", report.Message, StringComparison.Ordinal); } + /// + /// A group that does not fit and is relieved changes the width of an automatic column, so the + /// next group is judged after the table is measured again, not by the heights taken before. + /// Group A, 30 lines tall, gives up its breaks; group B, 12 lines of three words, fits once + /// the column it shares with the long text below has been measured again, and keeps its + /// breaks. Only the cell of group A is reported. + /// + [Fact] + public void ARelievedGroupIsMeasuredAgainBeforeTheNextGroupIsJudged() + { + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 600, 300), Margins = new EdgeInsets(10) }; + var t = new TableElement { DefaultCellStyle = Helvetica(10) }; + t.AddRow().AddCell(new Cell(Words(30)) { RowSpan = 2 }).AddCell("x"); + t.AddRow().AddCell("y"); + t.AddRow().AddCell(new Cell(Words(12).Replace("ab", "word word word")) { RowSpan = 2 }).AddCell("z"); + t.AddRow().AddCell("y"); + t.AddRow().AddCell("o").AddCell(string.Join(" ", Enumerable.Repeat("lorem ipsum dolor sit amet", 16))); + doc.Add(t); + + var texts = Texts(Content(Save(doc))); + var report = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped); + + Assert.Contains("row 0, cell 0", report.Message, StringComparison.Ordinal); + Assert.Equal(12, texts.Count(x => x == "word word word")); + } + + /// + /// Header rows that a tab tips over the page, with no line break among them, are laid out + /// unbroken at the third step: "ab", a tab and "ab" fit a 36pt column as one word and as two + /// words wrap one line taller, and the second header row is 44 plain lines. The two rows are + /// 556pt with the one line and 568pt with two, and the 20pt row below fits under the first and + /// not under the second. + /// + [Fact] + public void AHeaderThatATabTipsIsLaidOutUnbroken() + { + using var doc = WidePage(); + var t = Wide10(36, 36); + t.AddRow(isHeader: true).AddCell("ab\tab"); + t.AddRow(isHeader: true).AddCell(Words(44, " ")); + t.AddRow().AddCell("x"); + doc.Add(t); + + var bytes = Save(doc); + var report = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped); + + Assert.Equal(1, PageCount(bytes)); + Assert.Contains("abab", Texts(Content(bytes))); + Assert.Contains("row 0, cell 0", report.Message, StringComparison.Ordinal); + } + + /// + /// A line separator, U+2028, is a space and not a break, so it is not the first step: a group + /// that its cell does not tip is left as written, and only the cell with the line feeds is laid + /// out unbroken. + /// + [Fact] + public void AControlSpaceThatIsNotABreakIsNotTheFirstStep() + { + using var doc = WidePage(); + var t = Wide10(1000, 900); + t.AddRow().AddCell(new Cell(Words(60)) { RowSpan = 2 }).AddCell("a\u2028b"); + t.AddRow().AddCell("c"); + doc.Add(t); + + var texts = Texts(Content(Save(doc))); + var report = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped); + + Assert.Contains("row 0, cell 0", report.Message, StringComparison.Ordinal); + Assert.Contains("a b", texts); + } + /// /// Three rows chained by RowSpans, each one's span reaching into the next, are one group: 3 x /// 200pt is 600pt, which is more than a page, though each pair is 400pt. All three cells that @@ -1028,6 +1147,10 @@ public void ACutRowWithAFallbackCellIsReportedOnce() Assert.True(PageCount(bytes) > 2, "the row was not cut"); Assert.Equal(1, cut.Count); + + // The slices of the cut row are wrapped from the same unbroken text: the tab before the + // last "x" is left out, not a space. + Assert.Contains(Texts(Content(bytes)), x => x.EndsWith("wdx", StringComparison.Ordinal)); } /// From 18e895e21df5848327981afb60b8f2c5c3524e97 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 02:08:22 +0100 Subject: [PATCH 07/48] docs(changelog): restate the cell rule, counts and the page limit State what Count counts, scope the claim that nothing crosses a cell, describe the random tables accurately and give the exact page boundary: 2,350,047 words save and 2,350,048 are refused. --- CHANGELOG.md | 92 +++++++++---------- .../TableCellBreakTests.cs | 6 +- 2 files changed, 49 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 200d13d95..cd68bc89f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,13 +25,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - A custom `IRenderer` is offered the content area of the page it lands on, so when `Left` and `Right` differ its `Area.X` differs between pages. One that keeps an X from an earlier `Layout` call must not reuse it. -- **`LayoutDiagnosticCode.CellWhiteSpaceDropped` (301).** A table cell was laid out as one - unbroken line, and its tabs and line breaks were left out of what is drawn, because honouring the - line breaks of the cells around it would have made a header row or rows joined by a `RowSpan` - taller than a page. A warning, so `StrictDiagnostics` saves: the text stays, and the words those - characters separated run together in the drawing and in extracted text. `Count` is the number of - times the cell was drawn, so a repeated header row counts once per page. See the entry for #611 - under Fixed. +- **`LayoutDiagnosticCode.CellWhiteSpaceDropped` (301).** A table cell was wrapped at spaces alone + and sized from its whole text, and its tabs and line breaks were left out of what is drawn, + because honouring the line breaks of the cells around it would have made a header row or rows + joined by a `RowSpan` taller than a page. A warning, so `StrictDiagnostics` saves: the text stays, + and the words those characters separated run together in the drawing and in extracted text. + `Count` is the number of pages on which the cell was drawn from its first line, so a repeated + header row counts once per page and any other cell counts once, however many pages a cut row + spans. See the entry for #611 under Fixed. - **`Preformatted`, a block that keeps every space and tab (#591).** `Document.Add(Preformatted)` draws text whose spacing is its meaning: command blocks, configuration, ASCII tables. The default @@ -544,63 +545,62 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). feed pair, a lone carriage return and a lone line feed each end a line. An empty line between two of them is a blank line, and so is the one after a trailing break: `a` is two lines in a cell where a paragraph draws one. Runs of spaces are kept as written, where a paragraph collapses them. - Every other white-space character except the no-break spaces U+00A0, U+202F and U+2007 is one - space, which is the word separation `ParagraphRenderer` applies: a tab, a form feed, a line - tabulation, a next-line character, U+2028, U+2029, and the Unicode space separators such as - U+2003, U+3000, U+2009 and U+1680. An automatically sized column takes its minimum width from the - widest word and its maximum from the widest line, each line measured by itself where 2.3.3 - measured the whole text. The width the column is given is shared out as before, and can be more - than the maximum or less than the minimum. - A running band draws a tab, a line break or a form feed as one space, so the form feed of #613 - item 34 is a space there too, and a band's text is measured and cut as drawn. A band reads only - those control characters: a Unicode space separator in a band is written as before. + Every other white-space control character (a tab, a form feed, a line tabulation, a next-line + character, U+2028 and U+2029) is one space. The no-break spaces and the other Unicode space + separators, such as U+2003, are written as before, where a paragraph reads the separators as + spaces. An automatically sized column takes its minimum width from the widest word and its + maximum from the widest line, each line measured by itself where 2.3.3 measured the whole text. + The width the column is given is shared out as before, and can be more than the maximum or less + than the minimum. + A running band draws a tab, a line break or a form feed as one space, in its template and in the + text a page label prints for `{page}`, so the form feed of #613 item 34 is a space there too, and + a band's text is measured and cut as drawn. **Deliberate output changes:** - - `AB` in a cell is `(A B)` in Standard 14 and glyph 3 between the two letters in an - embedded font, with no `<0000>` entry in the ToUnicode map. + - `AB` in a cell is `(A B)` in Standard 14 and a space glyph between the two letters in an + embedded font (glyph 3 in DejaVu Sans), with no `<0000>` entry in the ToUnicode map. - `line1line2` is two show strings, the second one leading lower, in a row 14.4 + 14.4 + 8 pt tall at 12 pt, where it was one. A table whose cell holds a line break gets taller rows and - different automatic column widths. A cell with none of the characters above, in a table with - none of them or of a Unicode space separator, saves to the same bytes as before. - - A Unicode space separator other than the no-break spaces in a cell, such as U+2003, is one - space. Standard 14 fonts drew `?` for it and listed `UnencodableCharacter`; an embedded font - drew whatever glyph its map held. Of 20,000 random tables whose texts hold no control - character, 9,408 change, and the pool's one text with a separator is the U+2003 one. Because - the character's width changes, so can the wrapping: of the 40,000 tables measured, two that - saved before (one in each pool) now throw the too-tall `InvalidOperationException`, and both - save again with the rule switched off. + different automatic column widths. A table that holds none of tab, carriage return, line feed, + form feed, line tabulation, next-line character, U+2028 and U+2029 saves to the same bytes as + before: 20,000 random tables whose texts include U+0001, U+007F, no-break spaces and U+2003 + saved to identical bytes on the build before this change, and so did the first 3,331 of 4,000 + set in DejaVu Sans. - A band template measured a tab, a line feed, a carriage return or a form feed at its font's width for that character, zero in Helvetica, and now measures each as one space. A band that fit can therefore be cut: `A` followed by 120 tabs and `B` in Helvetica 10 on a 300 pt page saved with no truncation, and now draws 1 of its 122 characters and reports `BandTruncated`, which `StrictDiagnostics` refuses. - - A table that 2.3.3 refused as too tall can now save: 13 of 40,000 random tables (ten of the - 20,000 with control characters, three of the 20,000 without). All 13 are refusals that name a - `RowSpan` group. Columns are now measured per line and a space separator is measured as a - space, and both change the wrapping; I did not isolate which of the two shortens each group. - `qpdf --check` exits 0 for all 13. + - A table that 2.3.3 refused as too tall can now save: 6 of 20,000 random tables with control + characters (none of 20,000 without). Each is a refusal that names a `RowSpan` group, in a + table whose automatic columns are now measured per line. `qpdf --check` exits 0 for all six, + and no line crosses its cell border. - A cell with a very large number of lines can be refused where 2.3.3 saved it, because 2.3.3 drew its line feeds inside one line. One cell of 2,500,000 two-letter words joined by LF, on a 2000 x 600 pt page in a 1900 pt column, saved in 314 pages on 2.3.3 and now stops at the limit of 50,000 page continuations with the `InvalidOperationException` that names it. The same cell - of 2,300,000 words saves in 48,937 pages, and one of 2,400,000 is refused. + of 2,350,047 words saves, in 50,001 pages, and one of 2,350,048 is refused. - **A header row, or rows joined by a `RowSpan`, whose breaks would make them taller than a page keep the one-line layout.** Those rows are never cut between their lines, so honouring the breaks would turn a table that saved into a too-tall refusal. A cell of them is then wrapped at spaces alone and sized from its whole text, as 2.3.3 did, with each tab and break measured at the width its font gives it and then left out of what is drawn, so no line is wider than it was measured. A header of 60 two-letter lines stays inside its cell in a 100pt column and in - automatic columns on a 400pt page, and `pdftotext -raw` returns all 120 letters in order. The - words those characters separated run together, in the drawing and in extracted text. The save lists the cell as the new `LayoutDiagnosticCode.CellWhiteSpaceDropped` - (301, a warning, so `StrictDiagnostics` still saves). A header row of 46 two-letter lines, - 560pt tall, keeps its lines on a 580pt page beside a 20pt row; one of 47 does not. Which cells - fall back is decided in steps, each taken only while the rows still do not fit a page, and - each ending its pass so the heights are taken again before the next step is judged: the cells - of the group that hold a carriage return or line feed; then those of the header rows; then - the cells that hold any control white-space character and sit in the group, in the header rows, - or in an automatically sized column that one of those cells is in. A cell that holds only a line - feed can fall back at any of the three steps. A cell no step reaches keeps its breaks and is cut - between its lines when its row is taller than a page. A renderer laid out through a context - built with the public constructor knows no page and keeps every break. + automatic columns on a 400pt page, and `pdftotext -raw` returns all 120 letters in order. A + glyph wider than its column still extends past it, as in any cell: a column 10pt wide draws a + `W` 5.44pt past its border. The words the dropped characters separated run together, in the + drawing and in extracted text. The save lists the cell as the new + `LayoutDiagnosticCode.CellWhiteSpaceDropped` (301, a warning, so `StrictDiagnostics` still + saves). A header row of 46 two-letter lines, 560pt tall, keeps its lines on a 580pt page above + a 20pt row; one of 47 does not. Which cells fall back is decided in steps, each taken only + while the rows still do not fit a page, and each ending its pass so the heights are taken + again before the next step is judged: the cells of the group that hold a carriage return or + line feed; then those of the header rows; then the cells that hold any control white-space + character and sit in the rows of the group or the header, or in an automatically sized column + that a cell of those rows is in. A cell that holds only a line feed can fall back at any of + the three steps. A cell no step reaches keeps its breaks. A row that can be cut is cut between + its lines when it is taller than a page; a header row or a span group is never cut, and is + refused when it does not fit. A renderer laid out through a context built with the public + constructor knows no page and keeps every break. - **`/FontBBox` of an embedded font is the font's own bounding box (#596).** The descriptor of every embedded TrueType and OpenType font held `[0, hhea descender, 1000 * 1000 / unitsPerEm, hhea ascender]`: a zero for xMin and a constant for xMax, so DejaVu Sans, Liberation Sans and Liberation diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index d3169f740..5d6b81703 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -1148,9 +1148,9 @@ public void ACutRowWithAFallbackCellIsReportedOnce() Assert.True(PageCount(bytes) > 2, "the row was not cut"); Assert.Equal(1, cut.Count); - // The slices of the cut row are wrapped from the same unbroken text: the tab before the - // last "x" is left out, not a space. - Assert.Contains(Texts(Content(bytes)), x => x.EndsWith("wdx", StringComparison.Ordinal)); + // The slices of the cut row are wrapped from the same unbroken text as the cell in row 3 + // that is not cut: in both the tab before the last "x" is left out, not a space. + Assert.Equal(2, Texts(Content(bytes)).Count(x => x.EndsWith("wdx", StringComparison.Ordinal))); } /// From 31ac17373277b7b27f29d5c0993d16d24d57e535 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 03:17:18 +0100 Subject: [PATCH 08/48] perf(layout): judge span groups in fixed columns in one pass A group that gave up its breaks ended the pass, so a table with many such groups took one full measurement per group. A step that adds only cells of the group's own rows in fixed-width columns changes no height another group reads, so the pass goes on. A step that touches a header row or an automatic column still ends it. Also pins the header's no-room rule for a later row, a fallback cell after a ColSpan, the all-header table, and U+0085, U+2028, U+2029 in a band template, and says in the runtime message that the rows were left no room, not that they were taller than a page. --- .../Rendering/Table/TableRenderer.cs | 93 ++++++++--- .../TableCellBreakTests.cs | 155 +++++++++++++++++- 2 files changed, 215 insertions(+), 33 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 33650231a..70e24c36c 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -58,11 +58,12 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IPlacementSourc // The cells, as (row, cell) in authoring order, that this table lays out unbroken: wrapped at // spaces alone and measured with their control characters, and drawn without them, because - // honouring their breaks would make rows that cannot be cut taller than a page. Layout writes + // honouring their breaks would leave rows that cannot be cut no room on a page. Layout writes // it and gives it to the renderers that draw the pages; null when every break is kept. private HashSet<(int Row, int Cell)>? _oneLine; - // What _oneLine was decided for: the table width and the vertical extent of the two fresh boxes. + // What _oneLine was decided for: the table width and the vertical extent of the two fresh + // boxes. // A renderer that carries the decision to the next page reuses it when it lays out at the same // width and heights, and so resolves the grid once, where deciding again would resolve it once // per pass on every page. The boxes' x is left out of the key: the decision never reads it, and @@ -166,12 +167,12 @@ void IPlacementSource.ReportPlacements(PlacementSink sink) /// the saved lines are dropped and the row is laid out again from its first line, which /// under a context without the box is not cut. /// A carriage return or line feed in a cell ends a line. When honouring the breaks of a - /// header row or of rows joined by a would make those rows taller - /// than a page, which is known only under a context the document built, the cells that hold - /// them are wrapped at spaces alone and drawn without their tabs and breaks, and are reported - /// as ; - /// says which cells. A context built with the public - /// constructor of keeps every break. + /// repeated header row or of rows joined by a would leave those rows + /// no room on a page, which is known only under a context the document built, the cells that + /// hold them are wrapped at spaces alone and drawn without their tabs and breaks, and are + /// reported as ; + /// says when a row has no room and which cells. A context built + /// with the public constructor of keeps every break. /// These are refused with the too-tall exception, extended with a sentence naming the /// rows or the cell, and are never cut: the repeated header rows when they do not fit a page; /// a row that declares a above one, or lies under one; a row with a @@ -261,8 +262,8 @@ public LayoutResult Layout(LayoutContext context) // A line break makes a cell taller than a layout that draws it on one line, and a tab // is one space wide where the raw character was measured at its own width. Rows that - // cannot be cut between their lines must not become too tall for a page because of - // either, so the cells that would make them so are laid out unbroken, and the grid and + // cannot be cut between their lines must not be left without room on a page because of + // either, so the cells that would leave them so are laid out unbroken, and the grid and // the heights are taken again. Each pass adds cells, so this ends; most tables, which // hold no control white space, take no second pass. if (!decided && fresh is not null && AnyControlSpace(rows)) @@ -455,9 +456,14 @@ private static bool AnyControlSpace(IReadOnlyList rows) /// The cells to lay out unbroken in the next pass, or null when there are none that are not /// already laid out unbroken. The rows that cannot be cut between their lines are the repeated /// header rows and the rows joined by a ; the document would refuse - /// them as too tall. A row of either kind that does not fit a fresh page is relieved in steps, - /// and each step that adds a cell ends the pass, because every height has to be taken again - /// before the next step is judged. A group is relieved by its own cells that hold a line break + /// them as too tall. A row of either kind that has no room on a fresh page is relieved in + /// steps: the header rows have none when they do not fit a page or leave a row below them less + /// than one line of one of its cells, and a group has none when it is taller than what a page + /// leaves under the header rows. A step that adds a cell in a header row, or in an + /// automatically sized column, ends the pass, because every height has to be taken again + /// before the next group is judged. A step that adds only cells of the group's own rows in + /// fixed-width columns does not: no other group's height reads them, so one pass judges every + /// such group. A group is relieved by its own cells that hold a line break /// first. When it has none left, the header rows' cells that hold one go next, because they /// take room from every group under them. When those have none either, the cells that hold a /// tab or another control white-space character and can change the rows' height go last: the @@ -475,6 +481,21 @@ private static bool AnyControlSpace(IReadOnlyList rows) HashSet<(int Row, int Cell)>? found = null; + // The rows of the group being judged, and whether a cell was added that another group's + // height can depend on: one in a row outside the group, which is a header row, or one in an + // automatically sized column, whose width every row that has a cell in an automatic column + // can follow. A cell added in a row of the group and in fixed-width columns only changes + // that group's rows, so the groups after it are judged on the heights already taken. + var own = (First: -1, Last: -1); + var shared = false; + + void Note(int r, int col, int span) + { + if (r < own.First || r > own.Last) { shared = true; return; } + for (var k = 0; k < span && col + k < _colWidths.Length; k++) + if (IsAutoColumn(col + k)) { shared = true; return; } + } + // True when a cell was added that the table did not already lay out unbroken. The cells of // rows first to last that hold a line break qualify. bool CollectBreaks(int first, int last) @@ -483,10 +504,16 @@ bool CollectBreaks(int first, int last) for (var r = first; r <= last && r < rows.Count; r++) { var cells = rows[r].Cells; + var col = 0; for (var c = 0; c < cells.Count; c++) { - if (!HonoursBreaks(r, c) || !LayoutText.HasLineBreak(cells[c].Content)) continue; - added |= (found ??= []).Add((r, c)); + var span = cells[c].ColSpan; + if (HonoursBreaks(r, c) && LayoutText.HasLineBreak(cells[c].Content) && (found ??= []).Add((r, c))) + { + added = true; + Note(r, col, span); + } + col += span; } } return added; @@ -522,8 +549,12 @@ void Reach(int from, int to) for (var c = 0; c < cells.Count && col < reach.Length; c++) { var span = cells[c].ColSpan; - if (HonoursBreaks(r, c) && LayoutText.HasControlSpace(cells[c].Content) && (inside || SharesAutoColumn(col, span, reach))) - added |= (found ??= []).Add((r, c)); + if (HonoursBreaks(r, c) && LayoutText.HasControlSpace(cells[c].Content) && (inside || SharesAutoColumn(col, span, reach)) + && (found ??= []).Add((r, c))) + { + added = true; + Note(r, col, span); + } col += span; } } @@ -541,11 +572,25 @@ void Reach(int from, int to) var height = 0.0; for (var i = first; i <= last; i++) height += _rowHeights[i]; if (FitsFresh(fresh, headerHeight, height)) continue; - // Every step that adds a cell ends the pass: the next group is judged by heights that - // this step changes, a column's width among them. - if (CollectBreaks(first, last)) return found; + // A step that adds a cell the other groups' heights can depend on ends the pass: the + // next group is judged by heights that this step changes, a column's width among them. + // A step that stays in this group's rows and in fixed-width columns changes nothing + // the next group reads, so the pass goes on and one pass judges every such group. + own = (first, last); + shared = false; + if (CollectBreaks(first, last)) + { + if (shared) return found; + continue; + } + own = (-1, -1); if (header.Count > 0 && CollectBreaks(0, header[^1])) return found; - if (CollectControlSpace(first, last)) return found; + own = (first, last); + if (CollectControlSpace(first, last)) + { + if (shared) return found; + continue; + } } return found; @@ -1133,8 +1178,8 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, lineCount = wrappedLines.Count; } - // A cell the table laid out unbroken is reported where it is first drawn: once per page for a - // repeated header row, and from its first slice for a cut row. Only a cell that holds a + // A cell the table laid out unbroken is reported where it is first drawn: once per page for + // a repeated header row, and from its first slice for a cut row. Only a cell that holds a // control character loses anything by it, which is the separation its words had. if (!HonoursBreaks(rowIndex, cellIndex) && LayoutText.HasControlSpace(cell.Content) && (slice is null || slice.First[cellIndex] == 0)) @@ -1144,7 +1189,7 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, ((long)rowIndex << 32) | (uint)cellIndex, static subject => string.Create( System.Globalization.CultureInfo.InvariantCulture, - $"Table row {subject >> 32}, cell {subject & 0xFFFFFFFF} holds a tab, a line break or another control white-space character that is left out of what is drawn, because honouring the line breaks would make rows that cannot be cut taller than a page. The words it separated run together."), + $"Table row {subject >> 32}, cell {subject & 0xFFFFFFFF} holds a tab, a line break or another control white-space character that is left out of what is drawn, because honouring the line breaks would leave rows that cannot be cut no room on a page. The words it separated run together."), perElement: true); } diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index 5d6b81703..35cac956a 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -528,6 +528,9 @@ public void Embedded_theFileIsPdfA2uClean() [InlineData("H\tX", "H X")] [InlineData("H\nX", "H X")] [InlineData("H\r\nX", "H X")] + [InlineData("H\u0085X", "H X")] + [InlineData("H\u2028X", "H X")] + [InlineData("H\u2029X", "H X")] public void ABandDrawsAControlSpaceAsASpace(string template, string drawn) { using var doc = ShortPage(); @@ -1035,13 +1038,17 @@ public void AHeaderThatTakesTheRoomOfAGroupGivesUpOnlyItsBreaks() /// next group is judged after the table is measured again, not by the heights taken before. /// Group A, 30 lines tall, gives up its breaks; group B, 12 lines of three words, fits once /// the column it shares with the long text below has been measured again, and keeps its - /// breaks. Only the cell of group A is reported. + /// breaks. Only the cell of group A is reported. A column given the width 0 is an automatic + /// column, so setting both widths to 0 reads the same. /// - [Fact] - public void ARelievedGroupIsMeasuredAgainBeforeTheNextGroupIsJudged() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ARelievedGroupIsMeasuredAgainBeforeTheNextGroupIsJudged(bool zeroWidths) { using var doc = new Document { PageSize = new PdfRectangle(0, 0, 600, 300), Margins = new EdgeInsets(10) }; var t = new TableElement { DefaultCellStyle = Helvetica(10) }; + if (zeroWidths) t.SetColumnWidths(0, 0); t.AddRow().AddCell(new Cell(Words(30)) { RowSpan = 2 }).AddCell("x"); t.AddRow().AddCell("y"); t.AddRow().AddCell(new Cell(Words(12).Replace("ab", "word word word")) { RowSpan = 2 }).AddCell("z"); @@ -1061,15 +1068,18 @@ public void ARelievedGroupIsMeasuredAgainBeforeTheNextGroupIsJudged() /// unbroken at the third step: "ab", a tab and "ab" fit a 36pt column as one word and as two /// words wrap one line taller, and the second header row is 44 plain lines. The two rows are /// 556pt with the one line and 568pt with two, and the 20pt row below fits under the first and - /// not under the second. + /// not under the second. The tab is in the first header row or in the last one: the last row + /// of the header is one of the rows that step reaches. /// - [Fact] - public void AHeaderThatATabTipsIsLaidOutUnbroken() + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AHeaderThatATabTipsIsLaidOutUnbroken(bool tabInFirstRow) { using var doc = WidePage(); var t = Wide10(36, 36); - t.AddRow(isHeader: true).AddCell("ab\tab"); - t.AddRow(isHeader: true).AddCell(Words(44, " ")); + t.AddRow(isHeader: true).AddCell(tabInFirstRow ? "ab\tab" : Words(44, " ")); + t.AddRow(isHeader: true).AddCell(tabInFirstRow ? Words(44, " ") : "ab\tab"); t.AddRow().AddCell("x"); doc.Add(t); @@ -1078,7 +1088,7 @@ public void AHeaderThatATabTipsIsLaidOutUnbroken() Assert.Equal(1, PageCount(bytes)); Assert.Contains("abab", Texts(Content(bytes))); - Assert.Contains("row 0, cell 0", report.Message, StringComparison.Ordinal); + Assert.Contains(tabInFirstRow ? "row 0, cell 0" : "row 1, cell 0", report.Message, StringComparison.Ordinal); } /// @@ -1102,6 +1112,133 @@ public void AControlSpaceThatIsNotABreakIsNotTheFirstStep() Assert.Contains("a b", texts); } + /// + /// A row below the header can be the one with no room for a line: the first row under the + /// header holds a cell with no padding, which fits the 20pt a header of 46 lines leaves, and + /// the second holds a cell with 10pt of padding above and below, which does not. The header + /// gives up its breaks, and the table saves on one page. + /// + [Fact] + public void AHeaderIsRelievedWhenALaterRowHasNoRoomForALine() + { + using var doc = WidePage(); + var t = Wide10(1900); + t.AddRow(isHeader: true).AddCell(Words(46)); + t.AddRow().AddCell(new Cell("x") { Padding = new EdgeInsets(0) }); + t.AddRow().AddCell(new Cell("y") { Padding = new EdgeInsets(10) }); + doc.Add(t); + + var bytes = Save(doc); + + Assert.Equal(1, PageCount(bytes)); + Assert.Contains(Words(46, ""), Texts(Content(bytes))); + Assert.Contains("row 0, cell 0", CellReport(doc)!.Message, StringComparison.Ordinal); + } + + /// + /// A table of nothing but header rows repeats none of them, so a row of 48 lines, 584pt on a + /// 580pt page, is an ordinary row: it is cut between its lines over two pages and nothing is + /// laid out unbroken. + /// + [Fact] + public void ATableOfNothingButHeaderRowsIsCutLikeAnyOther() + { + using var doc = WidePage(); + var t = Wide10(1900); + t.AddRow(isHeader: true).AddCell(Words(48)); + doc.Add(t); + + var bytes = Save(doc); + + Assert.Equal(2, PageCount(bytes)); + Assert.Equal(48, Texts(Content(bytes)).Count(x => x == "ab")); + Assert.Null(CellReport(doc)); + } + + /// + /// A cell that holds the line breaks is found by its place among the row's cells, not by the + /// column it starts in: here it is the second cell of its row and starts in the third column, + /// after a cell that spans two. It is laid out unbroken, measured and drawn alike, so the rows + /// are one line tall and the table saves on one page. + /// + [Fact] + public void AFallbackCellAfterAColSpanIsMeasuredAsItIsDrawn() + { + using var doc = WidePage(); + var t = Wide10(400, 400, 1100); + t.AddRow().AddCell(new Cell("a") { ColSpan = 2 }).AddCell(new Cell(Words(60)) { RowSpan = 2 }); + t.AddRow().AddCell(new Cell("c") { ColSpan = 2 }); + doc.Add(t); + + var bytes = Save(doc); + var content = Content(bytes); + + Assert.Equal(1, PageCount(bytes)); + Assert.Equal(3, Borders(content).Length); + Assert.All(Heights(content), h => Assert.True(h < 60, $"a border {h}pt tall")); + Assert.Contains(Words(60, ""), Texts(content)); + Assert.Contains("row 0, cell 1", CellReport(doc)!.Message, StringComparison.Ordinal); + } + + /// + /// Every group that has no room is judged and relieved, and one that has room keeps its + /// breaks: the first and the third group are 60 lines tall and the second 10. The columns are + /// fixed, so no group's height depends on another's. + /// + [Fact] + public void EveryGroupWithNoRoomInFixedColumnsIsRelievedAndAFittingOneIsNot() + { + using var doc = WidePage(); + var t = Wide10(1500, 400); + foreach (var lines in new[] { 60, 10, 60 }) + { + t.AddRow().AddCell(new Cell(Words(lines)) { RowSpan = 2 }).AddCell("x"); + t.AddRow().AddCell("y"); + } + doc.Add(t); + + var texts = Texts(Content(Save(doc))); + var reports = doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped).ToList(); + + Assert.Equal(2, reports.Count); + Assert.Contains(reports, r => r.Message.Contains("row 0, cell 0", StringComparison.Ordinal)); + Assert.Contains(reports, r => r.Message.Contains("row 4, cell 0", StringComparison.Ordinal)); + Assert.Equal(10, texts.Count(x => x == "ab")); + } + + /// + /// Giving up the breaks of the groups in fixed columns costs a fixed number of measurements + /// of the table, not one per group. The allocations of a table of 400 groups that each give up + /// their breaks stay within a small multiple of those of the same table with the lines + /// separated by spaces, which has nothing to give up. Allocations are counted, not time, + /// because the same run on a loaded machine takes several times as long. + /// + [Fact] + public void TheCostOfGivingUpBreaksInFixedColumnsDoesNotGrowWithEachGroup() + { + static long Allocated(int groups, string separator) + { + using var doc = WidePage(); + var t = Wide10(1500, 400); + for (var i = 0; i < groups; i++) + { + t.AddRow().AddCell(new Cell(Words(60, separator)) { RowSpan = 2 }).AddCell("x"); + t.AddRow().AddCell("y"); + } + doc.Add(t); + var before = GC.GetAllocatedBytesForCurrentThread(); + Save(doc); + return GC.GetAllocatedBytesForCurrentThread() - before; + } + + Allocated(10, "\n"); + Allocated(10, " "); + var withBreaks = Allocated(400, "\n"); + var withSpaces = Allocated(400, " "); + + Assert.True(withBreaks < 5 * withSpaces, $"{withBreaks} bytes against {withSpaces} without breaks"); + } + /// /// Three rows chained by RowSpans, each one's span reaching into the next, are one group: 3 x /// 200pt is 600pt, which is more than a page, though each pair is 400pt. All three cells that From 5026fff1e7b7a88ae636f53d50831cfb4e7e41f9 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 03:21:27 +0100 Subject: [PATCH 09/48] test(layout): pin the third step's cost and its reach into a header A tab-tipped group in fixed columns must also be judged in one pass, and a tab in the last header row must reach the group's third step. --- .../TableCellBreakTests.cs | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index 35cac956a..c78373bb3 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -1091,6 +1091,30 @@ public void AHeaderThatATabTipsIsLaidOutUnbroken(bool tabInFirstRow) Assert.Contains(tabInFirstRow ? "row 0, cell 0" : "row 1, cell 0", report.Message, StringComparison.Ordinal); } + /// + /// A tab in the last header row that tips a RowSpan group over the page, while the header fits + /// and leaves its rows room: the group's third step reaches the header rows, the last one + /// included. The header cell is one line, 20pt, as one word and two, 32pt, as two; under it + /// the group is 556pt, which is 576pt with the one line and 588pt with two. + /// + [Fact] + public void ATabInTheLastHeaderRowThatTipsAGroupIsLaidOutUnbroken() + { + using var doc = WidePage(); + var t = Wide10(36, 36); + t.AddRow(isHeader: true).AddCell("ab ab"); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("b"); + t.AddRow().AddCell(Words(44, " ")); + doc.Add(t); + + var bytes = Save(doc); + var report = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped); + + Assert.Equal(1, PageCount(bytes)); + Assert.Contains("abab", Texts(Content(bytes))); + Assert.Contains("row 0, cell 0", report.Message, StringComparison.Ordinal); + } + /// /// A line separator, U+2028, is a space and not a break, so it is not the first step: a group /// that its cell does not tip is left as written, and only the cell with the line feeds is laid @@ -1239,6 +1263,37 @@ static long Allocated(int groups, string separator) Assert.True(withBreaks < 5 * withSpaces, $"{withBreaks} bytes against {withSpaces} without breaks"); } + /// + /// The same holds when a tab tips the groups over the page, the third step: each group is a + /// span cell, a tab cell that wraps one line taller as two words than as one, and 46 plain + /// lines. The tab cell gives up its tab in every group, in one pass. + /// + [Fact] + public void TheCostOfGivingUpTabsInFixedColumnsDoesNotGrowWithEachGroup() + { + static long Allocated(int groups, string tabCell) + { + using var doc = WidePage(); + var t = Wide10(36, 36); + for (var i = 0; i < groups; i++) + { + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell(tabCell); + t.AddRow().AddCell(Words(46, " ")); + } + doc.Add(t); + var before = GC.GetAllocatedBytesForCurrentThread(); + Save(doc); + return GC.GetAllocatedBytesForCurrentThread() - before; + } + + Allocated(10, "ab ab"); + Allocated(10, "abab"); + var withTabs = Allocated(400, "ab ab"); + var withoutTabs = Allocated(400, "abab"); + + Assert.True(withTabs < 5 * withoutTabs, $"{withTabs} bytes against {withoutTabs} without tabs"); + } + /// /// Three rows chained by RowSpans, each one's span reaching into the next, are one group: 3 x /// 200pt is 600pt, which is more than a page, though each pair is 400pt. All three cells that From 6f350c908d31aa4dcb3cb44234572719f37525a3 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 03:26:58 +0100 Subject: [PATCH 10/48] test(layout): assert the cost pins relieve every group they count A header that gives up its tab also changes the heights the next group is judged by, which one more case pins. --- .../TableCellBreakTests.cs | 43 ++++++++++++++++--- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index c78373bb3..2015abf41 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -1115,6 +1115,31 @@ public void ATabInTheLastHeaderRowThatTipsAGroupIsLaidOutUnbroken() Assert.Contains("row 0, cell 0", report.Message, StringComparison.Ordinal); } + /// + /// A header that gives up its tab changes the room every group under it has, so the groups + /// after it are judged on the new header. The tab in the header tips the first group over the + /// page, and the header is 20pt once it is given up. The second group, 576pt with that header + /// and 588pt with the tab as a space, holds line feeds and keeps them: only the header cell is + /// reported. + /// + [Fact] + public void AGroupAfterARelievedHeaderIsJudgedByTheHeaderThatRemains() + { + using var doc = WidePage(); + var t = Wide10(36, 36); + t.AddRow(isHeader: true).AddCell("ab ab"); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("b"); + t.AddRow().AddCell(Words(44, " ")); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("b"); + t.AddRow().AddCell(Words(44)); + doc.Add(t); + + Save(doc); + var report = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped); + + Assert.Contains("row 0, cell 0", report.Message, StringComparison.Ordinal); + } + /// /// A line separator, U+2028, is a space and not a break, so it is not the first step: a group /// that its cell does not tip is left as written, and only the cell with the line feeds is laid @@ -1240,7 +1265,7 @@ public void EveryGroupWithNoRoomInFixedColumnsIsRelievedAndAFittingOneIsNot() [Fact] public void TheCostOfGivingUpBreaksInFixedColumnsDoesNotGrowWithEachGroup() { - static long Allocated(int groups, string separator) + static (long Bytes, int Reported) Allocated(int groups, string separator) { using var doc = WidePage(); var t = Wide10(1500, 400); @@ -1252,7 +1277,8 @@ static long Allocated(int groups, string separator) doc.Add(t); var before = GC.GetAllocatedBytesForCurrentThread(); Save(doc); - return GC.GetAllocatedBytesForCurrentThread() - before; + var bytes = GC.GetAllocatedBytesForCurrentThread() - before; + return (bytes, doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped).Sum(d => d.Count)); } Allocated(10, "\n"); @@ -1260,7 +1286,9 @@ static long Allocated(int groups, string separator) var withBreaks = Allocated(400, "\n"); var withSpaces = Allocated(400, " "); - Assert.True(withBreaks < 5 * withSpaces, $"{withBreaks} bytes against {withSpaces} without breaks"); + Assert.Equal(400, withBreaks.Reported); + Assert.Equal(0, withSpaces.Reported); + Assert.True(withBreaks.Bytes < 5 * withSpaces.Bytes, $"{withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); } /// @@ -1271,7 +1299,7 @@ static long Allocated(int groups, string separator) [Fact] public void TheCostOfGivingUpTabsInFixedColumnsDoesNotGrowWithEachGroup() { - static long Allocated(int groups, string tabCell) + static (long Bytes, int Reported) Allocated(int groups, string tabCell) { using var doc = WidePage(); var t = Wide10(36, 36); @@ -1283,7 +1311,8 @@ static long Allocated(int groups, string tabCell) doc.Add(t); var before = GC.GetAllocatedBytesForCurrentThread(); Save(doc); - return GC.GetAllocatedBytesForCurrentThread() - before; + var bytes = GC.GetAllocatedBytesForCurrentThread() - before; + return (bytes, doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped).Sum(d => d.Count)); } Allocated(10, "ab ab"); @@ -1291,7 +1320,9 @@ static long Allocated(int groups, string tabCell) var withTabs = Allocated(400, "ab ab"); var withoutTabs = Allocated(400, "abab"); - Assert.True(withTabs < 5 * withoutTabs, $"{withTabs} bytes against {withoutTabs} without tabs"); + Assert.Equal(400, withTabs.Reported); + Assert.Equal(0, withoutTabs.Reported); + Assert.True(withTabs.Bytes < 5 * withoutTabs.Bytes, $"{withTabs.Bytes} bytes against {withoutTabs.Bytes} without tabs"); } /// From dcbfc88dd300917b063776d7fb6b8fe190f401c9 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 03:37:39 +0100 Subject: [PATCH 11/48] test(layout): tighten the cost pins to the measured gap The tab pin allocates 1.03 times its baseline when groups are judged together and 1.93 times that when each ends the pass; a bound of five missed it. --- tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index 2015abf41..391d3571b 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -1258,7 +1258,7 @@ public void EveryGroupWithNoRoomInFixedColumnsIsRelievedAndAFittingOneIsNot() /// /// Giving up the breaks of the groups in fixed columns costs a fixed number of measurements /// of the table, not one per group. The allocations of a table of 400 groups that each give up - /// their breaks stay within a small multiple of those of the same table with the lines + /// their breaks stay under one and a half times those of the same table with the lines /// separated by spaces, which has nothing to give up. Allocations are counted, not time, /// because the same run on a loaded machine takes several times as long. /// @@ -1288,7 +1288,7 @@ public void TheCostOfGivingUpBreaksInFixedColumnsDoesNotGrowWithEachGroup() Assert.Equal(400, withBreaks.Reported); Assert.Equal(0, withSpaces.Reported); - Assert.True(withBreaks.Bytes < 5 * withSpaces.Bytes, $"{withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); + Assert.True(withBreaks.Bytes < 1.5 * withSpaces.Bytes, $"{withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); } /// @@ -1322,7 +1322,7 @@ public void TheCostOfGivingUpTabsInFixedColumnsDoesNotGrowWithEachGroup() Assert.Equal(400, withTabs.Reported); Assert.Equal(0, withoutTabs.Reported); - Assert.True(withTabs.Bytes < 5 * withoutTabs.Bytes, $"{withTabs.Bytes} bytes against {withoutTabs.Bytes} without tabs"); + Assert.True(withTabs.Bytes < 1.5 * withoutTabs.Bytes, $"{withTabs.Bytes} bytes against {withoutTabs.Bytes} without tabs"); } /// From fda4f49bdaee4ef83dc2708071dfd607531e42b5 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 03:37:44 +0100 Subject: [PATCH 12/48] docs(layout): say a header or group has no room, not that it is tall A header falls back when it leaves the row below no room for a line, and a group when it exceeds what a page leaves under the header, so 'taller than a page' was false for both. A table of nothing but header rows repeats none. Corrects the qpdf and cell-border claim for the six refused-then-saved tables, the CR LF band sentence, and states that RunningBand.Resolve returns control characters as given. --- CHANGELOG.md | 39 ++++++++------ src/VellumPdf.Layout/Document.cs | 4 +- src/VellumPdf.Layout/Elements/BandTemplate.cs | 4 +- src/VellumPdf.Layout/Elements/RunningBand.cs | 4 ++ src/VellumPdf.Layout/Elements/Table/Cell.cs | 51 +++++++++++-------- .../Elements/Table/TableElement.cs | 13 +++-- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 23 +++++---- .../Rendering/Table/TableGridResolver.cs | 3 +- 8 files changed, 85 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ba2dc04cf..d5978800d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,9 +27,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). call must not reuse it. - **`LayoutDiagnosticCode.CellWhiteSpaceDropped` (301).** A table cell was wrapped at spaces alone and sized from its whole text, and its tabs and line breaks were left out of what is drawn, - because honouring the line breaks of the cells around it would have made a header row or rows - joined by a `RowSpan` taller than a page. A warning, so `StrictDiagnostics` saves: the text stays, - and the words those characters separated run together in the drawing and in extracted text. + because honouring the line breaks of the cells around it would have left a repeated header row + or rows joined by a `RowSpan` no room on a page. A warning, so `StrictDiagnostics` saves: the + text stays, and the words those characters separated run together in the drawing and in + extracted text. `Count` is the number of pages on which the cell was drawn from its first line, so a repeated header row counts once per page and any other cell counts once, however many pages a cut row spans. See the entry for #611 under Fixed. @@ -552,9 +553,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). maximum from the widest line, each line measured by itself where 2.3.3 measured the whole text. The width the column is given is shared out as before, and can be more than the maximum or less than the minimum. - A running band draws a tab, a line break or a form feed as one space, in its template and in the - text a page label prints for `{page}`, so the form feed of #613 item 34 is a space there too, and - a band's text is measured and cut as drawn. + A running band draws each tab, line feed, carriage return and form feed as one space, in its + template and in the text a page label prints for `{page}`, so a CR LF pair is two spaces, the + form feed of #613 item 34 is a space there too, and a band's text is measured and cut as drawn. **Deliberate output changes:** - `AB` in a cell is `(A B)` in Standard 14 and a space glyph between the two letters in an embedded font (glyph 3 in DejaVu Sans), with no `<0000>` entry in the ToUnicode map. @@ -572,16 +573,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). which `StrictDiagnostics` refuses. - A table that 2.3.3 refused as too tall can now save: 6 of 20,000 random tables with control characters (none of 20,000 without). Each is a refusal that names a `RowSpan` group, in a - table whose automatic columns are now measured per line. `qpdf --check` exits 0 for all six, - and no line crosses its cell border. + table whose automatic columns are now measured per line. `qpdf --check` exits 0 for all six. + Three of the six draw text outside the row it belongs to. That comes from a mismatch that + 2.3.3 has too and this change does not alter: a row's height is measured with its cells in + consecutive columns, and the drawing skips a column that a span from an earlier row occupies. + Tables whose texts hold no tab, line break or form feed show it on 2.3.3 as well. - A cell with a very large number of lines can be refused where 2.3.3 saved it, because 2.3.3 drew its line feeds inside one line. One cell of 2,500,000 two-letter words joined by LF, on a 2000 x 600 pt page in a 1900 pt column, saved in 314 pages on 2.3.3 and now stops at the limit of 50,000 page continuations with the `InvalidOperationException` that names it. The same cell of 2,350,047 words saves, in 50,001 pages, and one of 2,350,048 is refused. - - **A header row, or rows joined by a `RowSpan`, whose breaks would make them taller than a page - keep the one-line layout.** Those rows are never cut between their lines, so honouring the - breaks would turn a table that saved into a too-tall refusal. A cell of them is then wrapped at + - **A repeated header row, or rows joined by a `RowSpan`, whose breaks would leave them no room + on a page keep the one-line layout.** Those rows are never cut between their lines, so + honouring the breaks would turn a table that saved into a too-tall refusal. The header rows + have no room when they do not fit a page, or when they leave a row below them less than one + line of one of its cells; a span group has none when it is taller than what a page leaves + under the repeated header rows. A cell of them is then wrapped at spaces alone and sized from its whole text, as 2.3.3 did, with each tab and break measured at the width its font gives it and then left out of what is drawn, so no line is wider than it was measured. A header of 60 two-letter lines stays inside its cell in a 100pt column and in @@ -591,16 +598,18 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). drawing and in extracted text. The save lists the cell as the new `LayoutDiagnosticCode.CellWhiteSpaceDropped` (301, a warning, so `StrictDiagnostics` still saves). A header row of 46 two-letter lines, 560pt tall, keeps its lines on a 580pt page above - a 20pt row; one of 47 does not. Which cells fall back is decided in steps, each taken only + a 20pt row, where a line fits in the 20pt left; one of 47 is 572pt, fits the page alone, but + leaves the row 8pt, so it falls back. Which cells fall back is decided in steps, each taken only while the rows still do not fit a page, and each ending its pass so the heights are taken again before the next step is judged: the cells of the group that hold a carriage return or line feed; then those of the header rows; then the cells that hold any control white-space character and sit in the rows of the group or the header, or in an automatically sized column that a cell of those rows is in. A cell that holds only a line feed can fall back at any of the three steps. A cell no step reaches keeps its breaks. A row that can be cut is cut between - its lines when it is taller than a page; a header row or a span group is never cut, and is - refused when it does not fit. A renderer laid out through a context built with the public - constructor knows no page and keeps every break. + its lines when it is taller than a page; a repeated header row or a span group is never cut, + and is refused when it does not fit. A table whose rows are all headers repeats none of + them, so its rows are ordinary rows and are cut. A renderer laid out through a context built + with the public constructor knows no page and keeps every break. - **`/FontBBox` of an embedded font is the font's own bounding box (#596).** The descriptor of every embedded TrueType and OpenType font held `[0, hhea descender, 1000 * 1000 / unitsPerEm, hhea ascender]`: a zero for xMin and a constant for xMax, so DejaVu Sans, Liberation Sans and Liberation diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index 1708e51b1..62ce9211b 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -119,8 +119,8 @@ public Document() { } /// (mirroring ), /// (a preformatted line split with /// a marker; a warning, which saves), - /// (a table cell's tab or line break left - /// out of what is drawn; also a warning) + /// (a table cell's tab or line break + /// left out of what is drawn; also a warning) /// and . Every other one saves by /// default; only refuses it, and a later major version refuses /// them all. diff --git a/src/VellumPdf.Layout/Elements/BandTemplate.cs b/src/VellumPdf.Layout/Elements/BandTemplate.cs index 48cdbba42..4bff62f6c 100644 --- a/src/VellumPdf.Layout/Elements/BandTemplate.cs +++ b/src/VellumPdf.Layout/Elements/BandTemplate.cs @@ -171,8 +171,8 @@ internal sealed class BandText /// internal void Reset(int pageNumber, int totalPages, string? pageLabel = null) { - // The label is caller text, so a tab, a line break or a form feed in it is a space, as it is - // in the template's own text; the replacement keeps the length, so what is measured is what + // The label is caller text, so a tab, a line break or a form feed in it is a space, as it + // is in the template's own text; the replacement keeps the length, so what is measured is what // is drawn. _values[(int)BandToken.Page] = pageLabel is null ? pageNumber.ToString(System.Globalization.CultureInfo.InvariantCulture) diff --git a/src/VellumPdf.Layout/Elements/RunningBand.cs b/src/VellumPdf.Layout/Elements/RunningBand.cs index 5caf16622..75f68348e 100644 --- a/src/VellumPdf.Layout/Elements/RunningBand.cs +++ b/src/VellumPdf.Layout/Elements/RunningBand.cs @@ -236,6 +236,10 @@ public RunningBand(string template, TextStyle? style = null, HorizontalAlignment /// given, and a substituted number is never scanned again. A null template is refused here with /// ; the save refuses it the same way where the band is /// first drawn. + /// The string returned is not always what a save draws. A tab, a line break, a + /// form feed or another white-space control character in the template, and in a page label, is + /// returned as written, where a save draws each as one space; see . + /// A caller that compares this string with the text of a drawn band sees that difference. /// This builds the whole text, so its cost is the template's length. A save does not call /// it: the save resolves a template as it draws, and its cost per page follows the characters /// that fit the content width, as describes. diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 40faf580b..1f244652d 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -31,34 +31,41 @@ public sealed class Cell /// are, as in a paragraph. The other space separators, such as U+2003, are written as they are /// too, where a paragraph reads them as spaces. A column sized automatically takes its minimum /// from the widest word and its maximum from the widest line, each line of the cell measured on - /// its own, where 2.3.3 measured the whole text as one line. The width the column is then given is shared out among - /// the columns as it was, and can be more than the maximum or less than the minimum. + /// its own, where 2.3.3 measured the whole text as one line. The width the column is then + /// given is shared out among the columns as it was, and can be more than the maximum or less + /// than the minimum. /// A control character that is not white space, such as U+0001, is written as it is: in a /// standard-14 font as its WinAnsi code, and in an embedded font as whatever glyph the font's /// character map gives it, which is .notdef (glyph 0) when the map has no entry. The save lists /// each such character as , and - /// refuses it; see . - /// A cell has no tab stops, so a tab is one space. A cell of a header row, or of rows - /// joined by a , is laid out unbroken when honouring the line breaks of - /// those rows would make them taller than a page, because such rows are never cut between - /// their lines. It is then wrapped at spaces alone and sized from its whole text, each tab and - /// line break in it measured at the width its font gives it and left out of what is drawn. The - /// words they separated run together in the drawing and in extracted text, and no line is - /// wider than it was measured, though a glyph wider than its column can still extend past it, - /// as in any cell. The save lists the cell as + /// refuses it; see + /// . + /// A cell has no tab stops, so a tab is one space. A cell of a repeated header row, or + /// of rows joined by a , is laid out unbroken when honouring the line + /// breaks of those rows would leave them no room on a page, because such rows are never cut + /// between their lines. The header rows have no room when they do not fit a page, or when they + /// leave a row below them less than one line of one of its cells. A span group has no room when + /// it is taller than what a page leaves under the repeated header rows. The cell is then + /// wrapped at spaces alone and sized from its whole text, each tab and line break in it + /// measured at the width its font gives it and left out of what is drawn. The words they + /// separated run together in the drawing and in extracted text, and no line is wider than it + /// was measured, though a glyph wider than its column can still extend past it, as in any + /// cell. The save lists the cell as /// , a warning that /// saves. Which cells are laid out this way is decided - /// in three steps, each taken only while the rows still do not fit: the cells of the group that - /// hold a carriage return or a line feed, then those of the header rows, then every cell that - /// holds any control white space and sits in the group's rows, in the header rows, or in an - /// automatically sized column that a cell of those rows is in. A cell that holds only a line - /// feed can be laid out this way by any step. A cell outside those rows and columns keeps its - /// breaks, and a row that can be cut between its lines is cut when it is taller than a page, - /// which a header row or a span group never is: those are refused. Do not pass a line - /// break in a header row or a span group that is that tall and expect the lines to be drawn: - /// move the text to a row that can be cut, or shorten it. A renderer you lay out without the - /// document, through a built with the public constructor, knows no - /// page and keeps every break. + /// in three steps, each taken only while the rows still have no room: the cells of the group + /// that hold a carriage return or a line feed, then those of the header rows, then every cell + /// that holds any control white space and sits in the group's rows, in the header rows, or in + /// an automatically sized column that a cell of those rows is in. A cell that holds only a + /// line feed can be laid out this way by any step. A cell outside those rows and columns keeps + /// its breaks, and a row that can be cut between its lines is cut when it is taller than a + /// page, which a repeated header row or a span group never is: those are refused. A table + /// whose rows are all headers repeats none of them, so its rows are ordinary rows and are cut + /// like any other. Do not pass a line break in a repeated header row or a span group + /// that has no room and expect the lines to be drawn: move the text to a row that can be cut, + /// or shorten it. A renderer you lay out without the document, through a + /// built with the public constructor, knows no page and keeps + /// every break. /// /// public string Content { get; } diff --git a/src/VellumPdf.Layout/Elements/Table/TableElement.cs b/src/VellumPdf.Layout/Elements/Table/TableElement.cs index 540422b3d..488720834 100644 --- a/src/VellumPdf.Layout/Elements/Table/TableElement.cs +++ b/src/VellumPdf.Layout/Elements/Table/TableElement.cs @@ -31,10 +31,15 @@ namespace VellumPdf.Layout.Elements.Table; /// page is a TD, or a TH in a header row, and a cell with no line on the page is an /// empty TD, also in a header row. /// A carriage return or line feed in a cell ends a line, so it makes the row taller. A -/// header row, or rows joined by a , whose breaks would make them taller -/// than a page are never cut, so cells of them are wrapped at spaces alone with each tab and -/// break left out of what is drawn, and the save lists each as -/// ; see . +/// repeated header row, or rows joined by a , whose breaks would leave +/// them no room on a page are never cut, so cells of them are wrapped at spaces alone with each +/// tab and break left out of what is drawn, and the save lists each as +/// ; see . +/// Groups that give up cells in fixed-width columns only are judged together, in one measurement +/// of the table. A header that gives up a cell, and a group that gives up a cell in an +/// automatically sized column, each cost another measurement of the whole table, because they +/// change the heights of other rows, so a table with many of those takes time that grows with +/// the square of their number. /// These are refused, and never cut. /// throws whose message starts with the standard /// too-tall text and ends with a sentence naming the rows, for: header rows that together do not diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index ce3eacabd..681269bfa 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -119,7 +119,7 @@ public enum LayoutDiagnosticCode /// /// A table cell holds a tab, a line break or another control white-space character, and the /// save left it out of what it drew, because honouring the line breaks of the cells around it - /// would have made rows that cannot be cut between their lines taller than a page. + /// would have left rows that cannot be cut between their lines no room on a page. /// is the number of pages on which the cell was drawn from /// its first line, so a header row that repeats on every page counts once per page, and any /// other cell counts once, however many pages a cut row spans. The message names the row and @@ -131,16 +131,19 @@ public enum LayoutDiagnosticCode /// The cell is wrapped at spaces alone and sized from its whole text, each such character /// measured at the width its font gives it and then not drawn, so no line is wider than it was /// measured. A glyph wider than its column can still extend past it, as in any cell. The rows - /// in question are the leading header rows, which repeat on every page and are never cut, and + /// in question are the leading header rows that repeat on every page and are never cut, and /// the rows joined by a , which are never cut either. - /// A cell is laid out this way in three steps, each taken only when the rows still do not fit a - /// page: a cell of the group that holds a carriage return or a line feed; then such a cell of - /// the header rows; then a cell that holds any control white space and sits in the rows of the - /// group or the header, or in an automatically sized column that a cell of those rows is in. A - /// cell that holds only a line feed can be laid out this way by any of the three. A cell no - /// step reaches keeps its breaks and is not reported, in a table that has other such cells as - /// in any other. - /// Do not pass a header row or a span group whose line breaks do not fit one page: put + /// The header rows have no room when they do not fit a page, or when they leave a row below + /// them less than one line of one of its cells. A span group has no room when it is taller + /// than what a page leaves under the repeated header rows. A cell is laid out this way in + /// three steps, each taken only while the rows still have no room: a cell of the group that + /// holds a carriage return or a line feed; then such a cell of the header rows; then a cell + /// that holds any control white space and sits in the rows of the group or the header, or in + /// an automatically sized column that a cell of those rows is in. A cell that holds only a + /// line feed can be laid out this way by any of the three. A cell no step reaches keeps its + /// breaks and is not reported, in a table that has other such cells as in any other. A table + /// whose rows are all headers repeats none of them, so none of its cells is in question. + /// Do not pass a repeated header row or a span group that has no room on a page: put /// the breaks in rows that can be cut, or shorten the text. /// CellWhiteSpaceDropped = 301, diff --git a/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs b/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs index 458691745..08af5c39a 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs @@ -304,7 +304,8 @@ private static void ScaleToFit(double[] widths, double available) throw new ArgumentNullException("content", "A table cell has a null text and a column is sized automatically."); // The widest word and the widest line of the lines the cell is measured in. A cell - // of one line, which is every cell that holds no line break, measures as it always has. + // of one line, which is every cell that holds no line break, measures as it always + // has. var lines = TableRenderer.CellLines(cell.Content, honourBreaks: OneLineCells?.Contains((r, c)) != true); var longest = 0.0; var widest = 0.0; From f41dae588876988f9f10864ba1ad21742a10f05e Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 05:49:33 +0100 Subject: [PATCH 13/48] fix(layout): judge a table group again after its own step A group that gave up a cell in a fixed-width column let the pass go on to the next group, which was then judged against a header that a later pass relieved. With that header the next group would have had room, so its breaks were dropped for nothing. Only this group's rows are measured again now, and the group is judged once more before the next one. Each group that gives up a cell in an automatic column still ends the pass, and each pass measures the whole table, so a table with many such groups took time and allocation that grew with the square of their number. After 8 measurements the groups not yet judged are judged together. A table that needs at most 8 is decided as before; beyond that a later group can give up cells it would have kept. Tests pin the groups the cap leaves alone, the boundary at 7 and 8 measurements, the allocation of 400 groups in automatic columns, and the decision key, the column reach of a spanning cell, a column past the width array and a RowSpan inside the header. --- .../Rendering/Table/TableRenderer.cs | 166 +++++++------ .../TableCellBreakTests.cs | 235 ++++++++++++++++++ 2 files changed, 325 insertions(+), 76 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 70e24c36c..dcefc48aa 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -57,11 +57,19 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IPlacementSourc private RowSlice? _tailSlice; // The cells, as (row, cell) in authoring order, that this table lays out unbroken: wrapped at - // spaces alone and measured with their control characters, and drawn without them, because - // honouring their breaks would leave rows that cannot be cut no room on a page. Layout writes - // it and gives it to the renderers that draw the pages; null when every break is kept. + // spaces alone and measured with their control characters, and drawn without them. Cell.Content + // says why. Layout writes it and gives it to the renderers that draw the pages; null when every + // break is kept. private HashSet<(int Row, int Cell)>? _oneLine; + /// + /// The number of passes over the table's heights that each stop at the first step changing + /// another group's height. Pass 9 and later judge every group they reach together, which + /// bounds the cost of a table with many groups that give up a cell in an automatically sized + /// column. + /// + internal const int MaxPassesBeforeBatching = 8; + // What _oneLine was decided for: the table width and the vertical extent of the two fresh // boxes. // A renderer that carries the decision to the next page reuses it when it lays out at the same @@ -166,13 +174,11 @@ void IPlacementSource.ReportPlacements(PlacementSink sink) /// cut keeps cutting under such a context only at the width it was cut at. At another width /// the saved lines are dropped and the row is laid out again from its first line, which /// under a context without the box is not cut. - /// A carriage return or line feed in a cell ends a line. When honouring the breaks of a - /// repeated header row or of rows joined by a would leave those rows - /// no room on a page, which is known only under a context the document built, the cells that - /// hold them are wrapped at spaces alone and drawn without their tabs and breaks, and are - /// reported as ; - /// says when a row has no room and which cells. A context built - /// with the public constructor of keeps every break. + /// A carriage return or line feed in a cell ends a line. A repeated header row, or rows + /// joined by a , can lose the breaks of some cells, and the save + /// reports each as ; + /// says when and which. A context built with the public + /// constructor of keeps every break. /// These are refused with the too-tall exception, extended with a sentence naming the /// rows or the cell, and are never cut: the repeated header rows when they do not fit a page; /// a row that declares a above one, or lies under one; a row with a @@ -260,15 +266,18 @@ public LayoutResult Layout(LayoutContext context) ResolveGrid(area.Width, style); - // A line break makes a cell taller than a layout that draws it on one line, and a tab - // is one space wide where the raw character was measured at its own width. Rows that - // cannot be cut between their lines must not be left without room on a page because of - // either, so the cells that would leave them so are laid out unbroken, and the grid and - // the heights are taken again. Each pass adds cells, so this ends; most tables, which - // hold no control white space, take no second pass. + // Rows that cannot be cut between their lines must not be left without room on a page + // by reading a cell's line breaks, or its other control white space as spaces; + // Cell.Content says when, and which cells give them up. The cells that would leave + // them so are laid out unbroken, and the grid and the heights are taken again. Each + // pass adds cells, so this ends; most tables, which hold no control white space, take + // no second pass. Each pass costs one measurement of the whole table, so after + // MaxPassesBeforeBatching of them a pass no longer stops at the first step that + // changes other groups' heights. if (!decided && fresh is not null && AnyControlSpace(rows)) { - while (CellsToReadAsOneLine(fresh, style) is { } more) + var passes = 0; + while (CellsToReadAsOneLine(fresh, style, ++passes > MaxPassesBeforeBatching) is { } more) { _oneLine ??= []; _oneLine.UnionWith(more); @@ -413,28 +422,29 @@ private void ResolveGrid(double areaWidth, TextStyle style) _rowHeights = new double[rows.Count]; for (var r = 0; r < rows.Count; r++) + _rowHeights[r] = MeasureRow(r, style); + } + + private double MeasureRow(int r, TextStyle style) + { + var row = _table.Rows[r]; + var maxH = 0.0; + var col = 0; + var cellIndex = -1; + foreach (var cell in row.Cells) { - var row = rows[r]; - var maxH = 0.0; - var col = 0; - var cellIndex = -1; - foreach (var cell in row.Cells) - { - cellIndex++; - if (col >= _colWidths.Length) break; - var cs = cell.Style ?? style; - // The authoring index, not col: the two diverge as soon as an earlier cell spans - // more than one column, and naming the column points at a cell nobody wrote. - LayoutValidation.ValidateFontSize(cs, $"Table row {r}, cell {cellIndex}"); - var colW = ColSpanWidth(col, cell.ColSpan); - var innerW = colW - cell.Padding.Horizontal; - var lines = WordWrapCount(cell.Content, cs, Math.Max(1, innerW), HonoursBreaks(r, cellIndex)); - var cellH = lines * cs.EffectiveLeading + cell.Padding.Vertical; - maxH = Math.Max(maxH, cellH); - col += cell.ColSpan; - } - _rowHeights[r] = maxH; + cellIndex++; + if (col >= _colWidths.Length) break; + var cs = cell.Style ?? style; + LayoutValidation.ValidateFontSize(cs, $"Table row {r}, cell {cellIndex}"); + var colW = ColSpanWidth(col, cell.ColSpan); + var innerW = colW - cell.Padding.Horizontal; + var lines = WordWrapCount(cell.Content, cs, Math.Max(1, innerW), HonoursBreaks(r, cellIndex)); + var cellH = lines * cs.EffectiveLeading + cell.Padding.Vertical; + maxH = Math.Max(maxH, cellH); + col += cell.ColSpan; } + return maxH; } /// @@ -454,24 +464,14 @@ private static bool AnyControlSpace(IReadOnlyList rows) /// /// The cells to lay out unbroken in the next pass, or null when there are none that are not - /// already laid out unbroken. The rows that cannot be cut between their lines are the repeated - /// header rows and the rows joined by a ; the document would refuse - /// them as too tall. A row of either kind that has no room on a fresh page is relieved in - /// steps: the header rows have none when they do not fit a page or leave a row below them less - /// than one line of one of its cells, and a group has none when it is taller than what a page - /// leaves under the header rows. A step that adds a cell in a header row, or in an - /// automatically sized column, ends the pass, because every height has to be taken again - /// before the next group is judged. A step that adds only cells of the group's own rows in - /// fixed-width columns does not: no other group's height reads them, so one pass judges every - /// such group. A group is relieved by its own cells that hold a line break - /// first. When it has none left, the header rows' cells that hold one go next, because they - /// take room from every group under them. When those have none either, the cells that hold a - /// tab or another control white-space character and can change the rows' height go last: the - /// cells of the header rows and of the rows themselves, and the cells of every other row in an - /// automatically sized column that one of those cells is in, because such a column is as wide - /// as its widest cell. A cell that no step reaches keeps its breaks. + /// already laid out unbroken. Which cells, and why, says. This + /// method judges the header rows first and then each group in + /// order, and a group again after its own breaks are given up in fixed-width columns. A step + /// that adds a cell in a header row, or in an automatically sized column, ends the pass, + /// because every height has to be taken again before the next group is judged; with + /// set it ends that group's judging instead. /// - private HashSet<(int Row, int Cell)>? CellsToReadAsOneLine(LayoutBox[] fresh, TextStyle style) + private HashSet<(int Row, int Cell)>? CellsToReadAsOneLine(LayoutBox[] fresh, TextStyle style, bool batch) { var rows = _table.Rows; var header = FindHeaderRowIndices(rows); @@ -561,7 +561,7 @@ void Reach(int from, int to) return added; } - // The header rows are too tall when they do not fit a page, and when they leave a row below + // The header rows have no room when they do not fit a page, and when they leave a row below // them no room for one line of one of its cells. if (header.Count > 0 && (!FitsFresh(fresh, 0, headerHeight) || LeavesNoRoomForALine(fresh, headerHeight, lastHeaderRow, style)) && (CollectBreaks(0, header[^1]) || CollectControlSpace(0, header[^1]))) @@ -569,27 +569,41 @@ void Reach(int from, int to) foreach (var (first, last) in SpanGroups(lastHeaderRow)) { - var height = 0.0; - for (var i = first; i <= last; i++) height += _rowHeights[i]; - if (FitsFresh(fresh, headerHeight, height)) continue; - // A step that adds a cell the other groups' heights can depend on ends the pass: the - // next group is judged by heights that this step changes, a column's width among them. - // A step that stays in this group's rows and in fixed-width columns changes nothing - // the next group reads, so the pass goes on and one pass judges every such group. - own = (first, last); - shared = false; - if (CollectBreaks(first, last)) - { - if (shared) return found; - continue; - } - own = (-1, -1); - if (header.Count > 0 && CollectBreaks(0, header[^1])) return found; - own = (first, last); - if (CollectControlSpace(first, last)) + // A group is judged again after its own breaks are given up, on its rows' new heights: + // the steps after that one read them. The last step takes every cell it can reach in + // one go, so judging the group again after it would find nothing more to take. + while (true) { - if (shared) return found; - continue; + var height = 0.0; + for (var i = first; i <= last; i++) height += _rowHeights[i]; + if (FitsFresh(fresh, headerHeight, height)) break; + + // A step that adds a cell the other groups' heights can depend on ends the pass, + // because the next group would be judged by heights that the step changes, a + // column's width among them. After the bound on such passes (see the caller) it + // ends this group's judging instead, and the groups after it are judged together. + // A step that stays in this group's rows and in fixed-width columns changes no + // other group's height, so the next group is judged in the same pass. + own = (first, last); + shared = false; + if (CollectBreaks(first, last)) + { + if (shared) + { + if (!batch) return found; + break; + } + + // Only this group's rows are measured again, in the columns they have. + (_oneLine ??= []).UnionWith(found!); + for (var r = first; r <= last; r++) _rowHeights[r] = MeasureRow(r, style); + continue; + } + own = (-1, -1); + if (header.Count > 0 && CollectBreaks(0, header[^1])) return found; + own = (first, last); + if (CollectControlSpace(first, last) && shared && !batch) return found; + break; } } @@ -1189,7 +1203,7 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, ((long)rowIndex << 32) | (uint)cellIndex, static subject => string.Create( System.Globalization.CultureInfo.InvariantCulture, - $"Table row {subject >> 32}, cell {subject & 0xFFFFFFFF} holds a tab, a line break or another control white-space character that is left out of what is drawn, because honouring the line breaks would leave rows that cannot be cut no room on a page. The words it separated run together."), + $"Table row {subject >> 32}, cell {subject & 0xFFFFFFFF} holds a tab, a line break or another control white-space character that is left out of what is drawn, because reading its line breaks, or its other control white space as spaces, would leave a row that cannot be cut no room on a page. The words it separated run together."), perElement: true); } diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index 391d3571b..5feec3dff 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -622,6 +622,16 @@ public void ABandWithAControlSpaceInAPageLabelIsPdfA2uClean() private static LayoutDiagnostic? CellReport(Document doc) => doc.Diagnostics.SingleOrDefault(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped); + /// The cells reported as laid out unbroken, as "row r, cell c", in row order. + private static string[] Dropped(Document doc) => + [ + .. doc.Diagnostics + .Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped) + .Select(d => Regex.Match(d.Message, @"row \d+, cell \d+").Value) + .OrderBy(m => int.Parse(Regex.Match(m, @"\d+").Value, CultureInfo.InvariantCulture)) + .ThenBy(m => m, StringComparer.Ordinal), + ]; + /// /// A header row whose breaks, honoured, leave no room under it for the row below: 2.3.3 drew /// the cell on one line. The cell is drawn as one line, without its breaks, and reported as a warning. @@ -1255,6 +1265,160 @@ public void EveryGroupWithNoRoomInFixedColumnsIsRelievedAndAFittingOneIsNot() Assert.Equal(10, texts.Count(x => x == "ab")); } + /// + /// A group that gives up a cell in a fixed column is judged again before the next group, on + /// its own rows' new heights, and a step that then relieves the header changes what the next + /// group sees. The header is 30 lines, 368pt, and leaves 212pt; the first group is a two-line + /// span cell beside a cell too tall for 212pt, which no cell of the group can shorten, so the + /// header is relieved next. With the header on one line the second group, 20 lines and 248pt, + /// has room, so only the header and the first group's cell are reported. + /// + [Fact] + public void AGroupIsJudgedAgainAfterItsOwnStepBeforeTheNextOneIsJudged() + { + using var doc = WidePage(); + var t = Wide10(950, 950); + t.AddRow(isHeader: true).AddCell(Words(30)); + t.AddRow().AddCell(new Cell("p\nq") { RowSpan = 2 }).AddCell(Words(1300, " ")); + t.AddRow().AddCell("y"); + t.AddRow().AddCell(new Cell(Words(20)) { RowSpan = 2 }); + t.AddRow().AddCell("y"); + doc.Add(t); + + var texts = Texts(Content(Save(doc))); + + Assert.Equal(["row 0, cell 0", "row 1, cell 0"], Dropped(doc)); + Assert.Equal(20, texts.Count(x => x == "ab")); + } + + /// + /// A group cell that spans a fixed column and an automatically sized one changes the width of + /// the automatic column when it gives up its breaks, so the group after it is judged on heights + /// taken again: its own cell is not reported, because the column it shares is now wide enough. + /// + [Fact] + public void AGroupCellSpanningAnAutoColumnEndsThePassEvenWhenItStartsInAFixedOne() + { + using var doc = WidePage(); + var t = Wide10(1500, 0); + t.AddRow().AddCell(new Cell(Words(100)) { RowSpan = 2, ColSpan = 2 }); + t.AddRow().AddCell("y"); + t.AddRow().AddCell(new Cell("k\nk") { RowSpan = 2 }).AddCell(Words(1600, " ")); + t.AddRow().AddCell("z"); + doc.Add(t); + + Save(doc); + + Assert.Equal(["row 0, cell 0"], Dropped(doc)); + } + + /// + /// A column past the end of the width array is sized automatically, so a group cell in it ends + /// the pass: the group after it is judged on the column it has now. + /// + [Fact] + public void AColumnPastTheWidthArrayIsAnAutoColumn() + { + using var doc = WidePage(); + var t = Wide10(1500); + t.AddRow().AddCell(new Cell("x") { RowSpan = 2 }).AddCell(Words(60)); + t.AddRow().AddCell("y"); + t.AddRow().AddCell(new Cell("k\nk") { RowSpan = 2 }).AddCell(Words(1600, " ")); + t.AddRow().AddCell("z"); + doc.Add(t); + + Save(doc); + + Assert.Equal(["row 0, cell 1"], Dropped(doc)); + } + + /// + /// A RowSpan in a repeated header row does not make a group of the header rows, which are + /// judged by their own height. The two header rows are 376pt together and fit a page with the + /// 20pt row below, so nothing is given up; counted as a group on top of the header height they + /// would be 752pt. + /// + [Fact] + public void ARowSpanInsideTheHeaderIsNotAGroup() + { + using var doc = WidePage(); + var t = Wide10(900, 900); + t.AddRow(isHeader: true).AddCell(new Cell("h") { RowSpan = 2 }).AddCell(Words(15)); + t.AddRow(isHeader: true).AddCell(Words(15)); + t.AddRow().AddCell("x"); + doc.Add(t); + + var texts = Texts(Content(Save(doc))); + + Assert.Empty(Dropped(doc)); + Assert.Equal(30, texts.Count(x => x == "ab")); + } + + /// + /// The third step reaches an automatically sized column that only a header cell is in. The + /// header is one 20pt line, and the group is 20pt and 536pt, which fits a page under it until + /// the tab in "ab", tab, "ab" wraps the 36pt column one line taller. The tab in the last + /// column of the row after the group, a column no cell of the group is in and a header cell + /// is, goes unbroken with it. + /// + [Fact] + public void TheThirdStepReachesAnAutoColumnThatOnlyTheHeaderIsIn() + { + using var doc = WidePage(); + var t = Wide10(36, 36, 0); + t.AddRow(isHeader: true).AddCell("h").AddCell("h").AddCell("h"); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("ab\tab"); + t.AddRow().AddCell(Words(44, " ")); + t.AddRow().AddCell("o").AddCell("o").AddCell("a\tb"); + doc.Add(t); + + Save(doc); + + Assert.Equal(["row 1, cell 1", "row 3, cell 2"], Dropped(doc)); + } + + /// + /// A decision made for one fresh page does not stand for a taller one. The header, 47 lines, + /// leaves the row under it no room in a 580pt page and is laid out unbroken, and the renderer + /// that carries the table to the next page, laid out where a fresh page is 700pt tall, honours + /// its breaks: the header is 572pt. + /// + [Fact] + public void ADecisionIsNotReusedForAFreshPageOfAnotherHeight() + { + var t = Wide10(1900); + t.AddRow(isHeader: true).AddCell(Words(47)); + for (var i = 0; i < 3; i++) t.AddRow().AddCell("x"); + var small = new LayoutBox(10, 10, 1980, 580); + var tall = new LayoutBox(10, 10, 1980, 700); + + var first = new TableRenderer(t).Layout(new LayoutContext(new LayoutBox(10, 10, 1980, 60)) { FreshPageArea = small }); + var second = first.OverflowRenderer!.Layout(new LayoutContext(tall) { FreshPageArea = tall }); + + Assert.Equal(LayoutResult.Outcome.Partial, first.Status); + Assert.Equal(60.0, first.OccupiedArea!.Value.Height, 0.001); + Assert.Equal(LayoutResult.Outcome.Full, second.Status); + Assert.Equal(592.0, second.OccupiedArea!.Value.Height, 0.001); + } + + /// + /// The same decision is reused when the next page is the same size: the overflow renderer + /// draws the header it was handed, a line of 20pt, without deciding again. + /// + [Fact] + public void ADecisionIsReusedForAFreshPageOfTheSameHeight() + { + var t = Wide10(1900); + t.AddRow(isHeader: true).AddCell(Words(47)); + for (var i = 0; i < 3; i++) t.AddRow().AddCell("x"); + var small = new LayoutBox(10, 10, 1980, 580); + + var first = new TableRenderer(t).Layout(new LayoutContext(new LayoutBox(10, 10, 1980, 60)) { FreshPageArea = small }); + var second = first.OverflowRenderer!.Layout(new LayoutContext(small) { FreshPageArea = small }); + + Assert.Equal(40.0, second.OccupiedArea!.Value.Height, 0.001); + } + /// /// Giving up the breaks of the groups in fixed columns costs a fixed number of measurements /// of the table, not one per group. The allocations of a table of 400 groups that each give up @@ -1291,6 +1455,77 @@ public void TheCostOfGivingUpBreaksInFixedColumnsDoesNotGrowWithEachGroup() Assert.True(withBreaks.Bytes < 1.5 * withSpaces.Bytes, $"{withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); } + /// + /// A group that gives up a cell in an automatically sized column measures the whole table again, + /// so the measurements of such groups are bounded: after eight, the groups not yet judged are + /// judged together. The allocations of 400 such groups stay under a fixed multiple of those of + /// the same table with the lines separated by spaces, which has nothing to give up. Without the + /// bound the multiple grows with the number of groups. Allocations are counted, not time. + /// + [Fact] + public void TheCostOfGivingUpBreaksInAutoColumnsIsBounded() + { + static (long Bytes, int Reported) Allocated(int groups, string separator) + { + using var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica(10) }; + for (var i = 0; i < groups; i++) + { + t.AddRow().AddCell(new Cell(Words(60, separator)) { RowSpan = 2 }).AddCell("x"); + t.AddRow().AddCell("y"); + } + doc.Add(t); + var before = GC.GetAllocatedBytesForCurrentThread(); + Save(doc); + var bytes = GC.GetAllocatedBytesForCurrentThread() - before; + return (bytes, doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped).Sum(d => d.Count)); + } + + Allocated(10, "\n"); + Allocated(10, " "); + var withBreaks = Allocated(400, "\n"); + var withSpaces = Allocated(400, " "); + + Assert.Equal(400, withBreaks.Reported); + Assert.Equal(0, withSpaces.Reported); + Assert.True(withBreaks.Bytes < 2.0 * withSpaces.Bytes, $"{withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); + } + + /// + /// The bound on measurements is eight, and what it changes is what the documentation says. Each + /// filler group gives up a cell in an automatic column and so ends a pass. The groups after the + /// fillers are one that gives up its cell, and one that keeps its breaks when it is judged on + /// the heights the first one leaves. With seven fillers before them that holds; with eight the + /// two are judged together, on the heights before the first was relieved, and the second gives up + /// its cell too. + /// + [Theory] + [InlineData(7, false)] + [InlineData(8, true)] + public void AfterEightMeasurementsLaterGroupsAreJudgedTogether(int fillers, bool laterGroupGivesUp) + { + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 600, 300), Margins = new EdgeInsets(10) }; + var t = new TableElement { DefaultCellStyle = Helvetica(10) }; + for (var i = 0; i < fillers; i++) + { + t.AddRow().AddCell("x").AddCell("x").AddCell(new Cell(string.Join("\n", Enumerable.Repeat("i", 40))) { RowSpan = 2 }); + t.AddRow().AddCell("y"); + } + t.AddRow().AddCell(new Cell(Words(30)) { RowSpan = 2 }).AddCell("x"); + t.AddRow().AddCell("y"); + t.AddRow().AddCell(new Cell(Words(12).Replace("ab", "word word word")) { RowSpan = 2 }).AddCell("z"); + t.AddRow().AddCell("y"); + t.AddRow().AddCell("o").AddCell(string.Join(" ", Enumerable.Repeat("lorem ipsum dolor sit amet", 16))); + doc.Add(t); + + Save(doc); + + var dropped = Dropped(doc); + Assert.Equal(fillers + 1 + (laterGroupGivesUp ? 1 : 0), dropped.Length); + Assert.Contains($"row {2 * fillers}, cell 0", dropped); + Assert.Equal(laterGroupGivesUp, dropped.Contains($"row {2 * fillers + 2}, cell 0")); + } + /// /// The same holds when a tab tips the groups over the page, the third step: each group is a /// span cell, a tab cell that wraps one line taller as two words than as one, and 46 plain From b9b36c7f8d2e9bc768a8e3a7bc3f5ff79a1a2157 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 05:49:45 +0100 Subject: [PATCH 14/48] docs(layout): state the cell fallback rule once, and its real cause The rule for which table cells are laid out unbroken was copied into six places, and each copy drifted from the others: one said every step ends its pass, one said the cause was line breaks, though a tab alone can tip a table with none. Cell.Content now holds the rule in full, including the bound on measurements and what it changes. TableElement, LayoutDiagnosticCode, TableRenderer.Layout, the runtime message and the CHANGELOG say what they add and point there. Also fixes the running band note that a carriage return and line feed pair is two spaces, and replaces the CHANGELOG sentence about identical bytes with what was measured. --- CHANGELOG.md | 58 ++++++++-------- src/VellumPdf.Layout/Elements/RunningBand.cs | 7 +- src/VellumPdf.Layout/Elements/Table/Cell.cs | 68 ++++++++++++------- .../Elements/Table/TableElement.cs | 19 +++--- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 25 ++----- 5 files changed, 89 insertions(+), 88 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d5978800d..56338e6fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,8 +27,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). call must not reuse it. - **`LayoutDiagnosticCode.CellWhiteSpaceDropped` (301).** A table cell was wrapped at spaces alone and sized from its whole text, and its tabs and line breaks were left out of what is drawn, - because honouring the line breaks of the cells around it would have left a repeated header row - or rows joined by a `RowSpan` no room on a page. A warning, so `StrictDiagnostics` saves: the + because reading its line breaks, or its other control white space as spaces, would have left a + repeated header row or rows joined by a `RowSpan` no room on a page. A warning, so `StrictDiagnostics` saves: the text stays, and the words those characters separated run together in the drawing and in extracted text. `Count` is the number of pages on which the cell was drawn from its first line, so a repeated @@ -563,9 +563,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). tall at 12 pt, where it was one. A table whose cell holds a line break gets taller rows and different automatic column widths. A table that holds none of tab, carriage return, line feed, form feed, line tabulation, next-line character, U+2028 and U+2029 saves to the same bytes as - before: 20,000 random tables whose texts include U+0001, U+007F, no-break spaces and U+2003 - saved to identical bytes on the build before this change, and so did the first 3,331 of 4,000 - set in DejaVu Sans. + before, and is refused where it was refused. Random tables whose texts include U+0001, + U+007F, no-break spaces and U+2003 matched the build before this change in both, 20,000 in + Helvetica and 4,000 in DejaVu Sans. - A band template measured a tab, a line feed, a carriage return or a form feed at its font's width for that character, zero in Helvetica, and now measures each as one space. A band that fit can therefore be cut: `A` followed by 120 tabs and `B` in Helvetica 10 on a 300 pt page @@ -583,33 +583,29 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). 2000 x 600 pt page in a 1900 pt column, saved in 314 pages on 2.3.3 and now stops at the limit of 50,000 page continuations with the `InvalidOperationException` that names it. The same cell of 2,350,047 words saves, in 50,001 pages, and one of 2,350,048 is refused. - - **A repeated header row, or rows joined by a `RowSpan`, whose breaks would leave them no room - on a page keep the one-line layout.** Those rows are never cut between their lines, so - honouring the breaks would turn a table that saved into a too-tall refusal. The header rows - have no room when they do not fit a page, or when they leave a row below them less than one - line of one of its cells; a span group has none when it is taller than what a page leaves - under the repeated header rows. A cell of them is then wrapped at - spaces alone and sized from its whole text, as 2.3.3 did, with each tab and break measured at - the width its font gives it and then left out of what is drawn, so no line is wider than it was - measured. A header of 60 two-letter lines stays inside its cell in a 100pt column and in - automatic columns on a 400pt page, and `pdftotext -raw` returns all 120 letters in order. A - glyph wider than its column still extends past it, as in any cell: a column 10pt wide draws a - `W` 5.44pt past its border. The words the dropped characters separated run together, in the - drawing and in extracted text. The save lists the cell as the new + - **A repeated header row, or rows joined by a `RowSpan`, keep the one-line layout of their cells + when reading the cells' breaks would leave them no room on a page.** Those rows are never cut + between their lines, so reading the breaks would turn a table that saved into a too-tall + refusal. The cause is a line break, or any other control white space, which a cell reads as a + space where 2.3.3 measured the character at its own width: a tab can tip a table that has no + line break in it. A cell of such rows is then wrapped at spaces alone and sized from its whole + text, as 2.3.3 did, with each tab and break measured at the width its font gives it and then + left out of what is drawn, so no line is wider than it was measured. The words they separated + run together, in the drawing and in extracted text. The save lists the cell as the new `LayoutDiagnosticCode.CellWhiteSpaceDropped` (301, a warning, so `StrictDiagnostics` still - saves). A header row of 46 two-letter lines, 560pt tall, keeps its lines on a 580pt page above - a 20pt row, where a line fits in the 20pt left; one of 47 is 572pt, fits the page alone, but - leaves the row 8pt, so it falls back. Which cells fall back is decided in steps, each taken only - while the rows still do not fit a page, and each ending its pass so the heights are taken - again before the next step is judged: the cells of the group that hold a carriage return or - line feed; then those of the header rows; then the cells that hold any control white-space - character and sit in the rows of the group or the header, or in an automatically sized column - that a cell of those rows is in. A cell that holds only a line feed can fall back at any of - the three steps. A cell no step reaches keeps its breaks. A row that can be cut is cut between - its lines when it is taller than a page; a repeated header row or a span group is never cut, - and is refused when it does not fit. A table whose rows are all headers repeats none of - them, so its rows are ordinary rows and are cut. A renderer laid out through a context built - with the public constructor knows no page and keeps every break. + saves). A header of 60 two-letter lines stays inside its cell in a 100pt column, and + `pdftotext -raw` returns all 120 letters in order. A header row of 46 two-letter lines, 560pt + tall, keeps its lines on a 580pt page above a 20pt row, where a line fits in the 20pt left; + one of 47 is 572pt, fits the page alone, but leaves the row 8pt, so it falls back. The XML + documentation of `Cell.Content` states when a header or a group has no room, which cells + fall back and in what order, and what a renderer laid out without the document does. + - **The decision costs a measurement of the whole table each time a header row, or a group + that gives up a cell in an automatically sized column, falls back.** After 8 such + measurements the groups not yet judged are judged together, which bounds the cost of a table + with many such groups. A table that needs no more than 8 measurements is decided exactly as + group-by-group judging would decide it; beyond that, a later group can give up cells that + group-by-group judging would have kept. Groups that give up a cell in fixed-width columns + only measure their own rows and do not count towards the 8. - **`/FontBBox` of an embedded font is the font's own bounding box (#596).** The descriptor of every embedded TrueType and OpenType font held `[0, hhea descender, 1000 * 1000 / unitsPerEm, hhea ascender]`: a zero for xMin and a constant for xMax, so DejaVu Sans, Liberation Sans and Liberation diff --git a/src/VellumPdf.Layout/Elements/RunningBand.cs b/src/VellumPdf.Layout/Elements/RunningBand.cs index 75f68348e..593743773 100644 --- a/src/VellumPdf.Layout/Elements/RunningBand.cs +++ b/src/VellumPdf.Layout/Elements/RunningBand.cs @@ -28,9 +28,10 @@ public sealed class RunningBand { /// Text template — may contain {page} and/or {pages}. /// - /// A band is one line: a tab, a line break, a form feed or any other white-space control - /// character in the template is drawn as one space each, and is measured as one, so no - /// white-space control character reaches the font from it. The same holds for the text a + /// A band is one line: a tab, a line feed, a carriage return, a form feed or any other + /// white-space control character in the template is drawn as one space and measured as one, + /// so a carriage return and line feed pair is two spaces, and no white-space control + /// character reaches the font from it. The same holds for the text a /// prints for {page}. A control character that is not white /// space, such as U+0001, is written as it is. /// Not checked when it is set: the constructor stores a null template, and the save throws diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 1f244652d..2a87fbb79 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -40,32 +40,48 @@ public sealed class Cell /// each such character as , and /// refuses it; see /// . - /// A cell has no tab stops, so a tab is one space. A cell of a repeated header row, or - /// of rows joined by a , is laid out unbroken when honouring the line - /// breaks of those rows would leave them no room on a page, because such rows are never cut - /// between their lines. The header rows have no room when they do not fit a page, or when they - /// leave a row below them less than one line of one of its cells. A span group has no room when - /// it is taller than what a page leaves under the repeated header rows. The cell is then - /// wrapped at spaces alone and sized from its whole text, each tab and line break in it - /// measured at the width its font gives it and left out of what is drawn. The words they - /// separated run together in the drawing and in extracted text, and no line is wider than it - /// was measured, though a glyph wider than its column can still extend past it, as in any - /// cell. The save lists the cell as - /// , a warning that - /// saves. Which cells are laid out this way is decided - /// in three steps, each taken only while the rows still have no room: the cells of the group - /// that hold a carriage return or a line feed, then those of the header rows, then every cell - /// that holds any control white space and sits in the group's rows, in the header rows, or in - /// an automatically sized column that a cell of those rows is in. A cell that holds only a - /// line feed can be laid out this way by any step. A cell outside those rows and columns keeps - /// its breaks, and a row that can be cut between its lines is cut when it is taller than a - /// page, which a repeated header row or a span group never is: those are refused. A table - /// whose rows are all headers repeats none of them, so its rows are ordinary rows and are cut - /// like any other. Do not pass a line break in a repeated header row or a span group - /// that has no room and expect the lines to be drawn: move the text to a row that can be cut, - /// or shorten it. A renderer you lay out without the document, through a - /// built with the public constructor, knows no page and keeps - /// every break. + /// A cell has no tab stops, so a tab is one space. + /// A cell is laid out unbroken, with its tabs and line breaks left out of what is + /// drawn, when reading them would leave a row that cannot be cut no room on a page. This + /// is the one place that states the rule; the other members that mention it point here. The + /// rows that are never cut between their lines are the repeated header rows and the rows + /// joined by a . The header rows have no room when they do not fit a + /// page, or when they leave a row below them less than one line of one of its cells. A span + /// group has no room when it is taller than what a page leaves under the repeated header + /// rows. The cause is a line break, which adds a line, or any other control white space, + /// because a tab is one space wide where the font measures the tab character at its own + /// width: a tab can tip a table that holds no line break. Such a cell is wrapped at spaces + /// alone and sized from its whole text, each tab and line break in it measured at the width + /// its font gives it and left out of what is drawn. The words they separated run together in + /// the drawing and in extracted text, and no line is wider than it was measured, though a + /// glyph wider than its column can still extend past it, as in any cell. The save lists the + /// cell as , a + /// warning that saves. + /// Which cells give them up is decided in order: the header rows are judged first, then + /// each group of rows joined by a , each on the heights the decisions + /// before it leave. A group is relieved in three steps, each taken only while the group still + /// has no room: the cells of the group that hold a carriage return or a line feed; then those + /// of the header rows; then every cell that holds any control white space and sits in the + /// group's rows, in the header rows, or in an automatically sized column that a cell of + /// those rows is in. The header rows are relieved in the same way: by their own cells that + /// hold a carriage return or a line feed, and then by every cell that holds any control white + /// space and sits in them or in an automatically sized column that a cell of them is in. A + /// cell that holds only a line feed can be reached by any step. A cell no step reaches keeps + /// its breaks. + /// The table's heights are measured again each time a header row, or a group in an + /// automatically sized column, gives up a cell, because that can change other rows. After the + /// table has been measured again 8 times for this decision, the groups not yet judged are + /// judged together on the heights as they stand. A table that needs no more than 8 such + /// measurements is laid out as if every group were judged on the heights the earlier ones + /// left; beyond that, a later group can give up cells that judging it on those heights would + /// have kept. + /// A row that can be cut between its lines is cut when it is taller than a page. A + /// repeated header row or a span group is never cut, and the save refuses it when it does not + /// fit; a table whose rows are all headers repeats none of them, so its rows are cut like any + /// other. Do not pass a line break in a repeated header row or a span group that has no + /// room and expect the lines to be drawn: move the text to a row that can be cut, or shorten + /// it. A renderer you lay out without the document, through a built + /// with the public constructor, knows no page and keeps every break. /// /// public string Content { get; } diff --git a/src/VellumPdf.Layout/Elements/Table/TableElement.cs b/src/VellumPdf.Layout/Elements/Table/TableElement.cs index 488720834..272630470 100644 --- a/src/VellumPdf.Layout/Elements/Table/TableElement.cs +++ b/src/VellumPdf.Layout/Elements/Table/TableElement.cs @@ -31,15 +31,16 @@ namespace VellumPdf.Layout.Elements.Table; /// page is a TD, or a TH in a header row, and a cell with no line on the page is an /// empty TD, also in a header row. /// A carriage return or line feed in a cell ends a line, so it makes the row taller. A -/// repeated header row, or rows joined by a , whose breaks would leave -/// them no room on a page are never cut, so cells of them are wrapped at spaces alone with each -/// tab and break left out of what is drawn, and the save lists each as -/// ; see . -/// Groups that give up cells in fixed-width columns only are judged together, in one measurement -/// of the table. A header that gives up a cell, and a group that gives up a cell in an -/// automatically sized column, each cost another measurement of the whole table, because they -/// change the heights of other rows, so a table with many of those takes time that grows with -/// the square of their number. +/// repeated header row, or rows joined by a , can lose the breaks and +/// tabs of some cells, and the save lists each as +/// ; says when +/// and which. +/// Each time a header row, or a group in an automatically sized column, gives up a cell, +/// the save measures the whole table again. A group that gives up cells in fixed-width +/// columns only measures its own rows again. After 8 measurements of the whole table for this +/// decision, the groups not yet judged are judged together, so a table with many groups in +/// automatically sized columns does not take one more for each. says +/// what that changes in what is drawn. /// These are refused, and never cut. /// throws whose message starts with the standard /// too-tall text and ends with a sentence naming the rows, for: header rows that together do not diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index 681269bfa..1b857a2dc 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -118,8 +118,8 @@ public enum LayoutDiagnosticCode /// /// A table cell holds a tab, a line break or another control white-space character, and the - /// save left it out of what it drew, because honouring the line breaks of the cells around it - /// would have left rows that cannot be cut between their lines no room on a page. + /// save left it out of what it drew, because reading it would have left a row that cannot be + /// cut no room on a page. /// is the number of pages on which the cell was drawn from /// its first line, so a header row that repeats on every page counts once per page, and any /// other cell counts once, however many pages a cut row spans. The message names the row and @@ -128,23 +128,10 @@ public enum LayoutDiagnosticCode /// /// The words such a character separated run together in the cell, in drawing and in /// extracted text, and nothing else is lost, so this is a warning and strict mode saves. - /// The cell is wrapped at spaces alone and sized from its whole text, each such character - /// measured at the width its font gives it and then not drawn, so no line is wider than it was - /// measured. A glyph wider than its column can still extend past it, as in any cell. The rows - /// in question are the leading header rows that repeat on every page and are never cut, and - /// the rows joined by a , which are never cut either. - /// The header rows have no room when they do not fit a page, or when they leave a row below - /// them less than one line of one of its cells. A span group has no room when it is taller - /// than what a page leaves under the repeated header rows. A cell is laid out this way in - /// three steps, each taken only while the rows still have no room: a cell of the group that - /// holds a carriage return or a line feed; then such a cell of the header rows; then a cell - /// that holds any control white space and sits in the rows of the group or the header, or in - /// an automatically sized column that a cell of those rows is in. A cell that holds only a - /// line feed can be laid out this way by any of the three. A cell no step reaches keeps its - /// breaks and is not reported, in a table that has other such cells as in any other. A table - /// whose rows are all headers repeats none of them, so none of its cells is in question. - /// Do not pass a repeated header row or a span group that has no room on a page: put - /// the breaks in rows that can be cut, or shorten the text. + /// A cell that keeps its breaks is not reported. + /// says which rows, when, and which cells. Do not pass a repeated header row or a span + /// group that has no room on a page: put the breaks in rows that can be cut, or shorten the + /// text. /// CellWhiteSpaceDropped = 301, From 574806cc9b235b3d8a602c3412c009a0d0f1d668 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 06:44:25 +0100 Subject: [PATCH 15/48] docs(layout): state what the table pass limit does not bound The limit of 8 measurements ends passes that stop at the first shared step. A table in which each group's fallback changes the column widths the next group is judged against still takes one measurement per group, and above the limit a later group can give up more cells or fewer than group-by-group judging would. Say so in the XML docs, comments and CHANGELOG, and pin the batch-mode branches of the group loop with tests. --- CHANGELOG.md | 16 +- src/VellumPdf.Layout/Elements/Table/Cell.cs | 15 +- .../Elements/Table/TableElement.cs | 7 +- .../Rendering/Table/TableRenderer.cs | 23 ++- .../TableCellBreakTests.cs | 162 +++++++++++++++++- 5 files changed, 197 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 56338e6fc..cd7327d00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -601,11 +601,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). fall back and in what order, and what a renderer laid out without the document does. - **The decision costs a measurement of the whole table each time a header row, or a group that gives up a cell in an automatically sized column, falls back.** After 8 such - measurements the groups not yet judged are judged together, which bounds the cost of a table - with many such groups. A table that needs no more than 8 measurements is decided exactly as - group-by-group judging would decide it; beyond that, a later group can give up cells that - group-by-group judging would have kept. Groups that give up a cell in fixed-width columns - only measure their own rows and do not count towards the 8. + measurements a pass no longer ends at the first group that gives up a cell: it judges every + group it reaches on the heights as they stand, and the passes repeat until one adds nothing. + That keeps the cost off the number of groups when they all lack room on the heights the table + starts with. A table that needs no more than 8 measurements is decided exactly as + group-by-group judging would decide it; beyond that, a later group can give up more cells + than group-by-group judging would, or fewer. When each group's fallback changes the width of + an automatic column that the next group is judged by, the next group is found only by the + next measurement, so the table is still measured once for each group: 400 such groups took + 23s and 9,382MB of allocation in one run, where the same table took 4.9s and 3,023MB before + this change. Groups that give up a cell in fixed-width columns only measure their own rows and do + not count towards the 8. - **`/FontBBox` of an embedded font is the font's own bounding box (#596).** The descriptor of every embedded TrueType and OpenType font held `[0, hhea descender, 1000 * 1000 / unitsPerEm, hhea ascender]`: a zero for xMin and a constant for xMax, so DejaVu Sans, Liberation Sans and Liberation diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 2a87fbb79..f0144574e 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -70,11 +70,16 @@ public sealed class Cell /// its breaks. /// The table's heights are measured again each time a header row, or a group in an /// automatically sized column, gives up a cell, because that can change other rows. After the - /// table has been measured again 8 times for this decision, the groups not yet judged are - /// judged together on the heights as they stand. A table that needs no more than 8 such - /// measurements is laid out as if every group were judged on the heights the earlier ones - /// left; beyond that, a later group can give up cells that judging it on those heights would - /// have kept. + /// table has been measured again 8 times for this decision, a pass no longer ends at the + /// first group that gives up such a cell: it judges every group it reaches on the heights as + /// they stand, and passes repeat until one adds no cell. A header row that gives up cells + /// still ends the pass. A table that needs no more than 8 such measurements is laid out as if + /// every group were judged on the heights the earlier ones left; beyond that, a later group + /// can give up more cells than judging it on those heights would, or fewer. That keeps the + /// measurements down for groups that all lack room on the heights the table starts with. When + /// the cells each group gives up change the width of an automatically sized column that the + /// next group is judged by, the next group is found only by the next measurement, so the + /// table is still measured once for each group. /// A row that can be cut between its lines is cut when it is taller than a page. A /// repeated header row or a span group is never cut, and the save refuses it when it does not /// fit; a table whose rows are all headers repeats none of them, so its rows are cut like any diff --git a/src/VellumPdf.Layout/Elements/Table/TableElement.cs b/src/VellumPdf.Layout/Elements/Table/TableElement.cs index 272630470..560812fa9 100644 --- a/src/VellumPdf.Layout/Elements/Table/TableElement.cs +++ b/src/VellumPdf.Layout/Elements/Table/TableElement.cs @@ -38,9 +38,10 @@ namespace VellumPdf.Layout.Elements.Table; /// Each time a header row, or a group in an automatically sized column, gives up a cell, /// the save measures the whole table again. A group that gives up cells in fixed-width /// columns only measures its own rows again. After 8 measurements of the whole table for this -/// decision, the groups not yet judged are judged together, so a table with many groups in -/// automatically sized columns does not take one more for each. says -/// what that changes in what is drawn. +/// decision, a pass judges every group it reaches together, which saves measurements only when +/// no group is tipped by the cells another gave up: a table in which each group's cells change +/// the width of a column the next group is judged by is still measured once for each group. +/// says what that changes in what is drawn. /// These are refused, and never cut. /// throws whose message starts with the standard /// too-tall text and ends with a sentence naming the rows, for: header rows that together do not diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index dcefc48aa..cb2b1d94d 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -64,9 +64,12 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IPlacementSourc /// /// The number of passes over the table's heights that each stop at the first step changing - /// another group's height. Pass 9 and later judge every group they reach together, which - /// bounds the cost of a table with many groups that give up a cell in an automatically sized - /// column. + /// another group's height. Pass 9 and later judge every group they reach, each on the heights + /// as they stand, and the passes repeat until one adds no cell. That keeps the measurements + /// down for groups that all lack room on the heights the table starts with. It does not for a + /// chain in which each group is tipped by the cells the one before it gave up: that table is + /// measured once per group. + /// states the rule. /// internal const int MaxPassesBeforeBatching = 8; @@ -272,8 +275,8 @@ public LayoutResult Layout(LayoutContext context) // them so are laid out unbroken, and the grid and the heights are taken again. Each // pass adds cells, so this ends; most tables, which hold no control white space, take // no second pass. Each pass costs one measurement of the whole table, so after - // MaxPassesBeforeBatching of them a pass no longer stops at the first step that - // changes other groups' heights. + // MaxPassesBeforeBatching of them a pass no longer stops at the first group step that + // changes other groups' heights. A step in the header rows still ends it. if (!decided && fresh is not null && AnyControlSpace(rows)) { var passes = 0; @@ -468,8 +471,11 @@ private static bool AnyControlSpace(IReadOnlyList rows) /// method judges the header rows first and then each group in /// order, and a group again after its own breaks are given up in fixed-width columns. A step /// that adds a cell in a header row, or in an automatically sized column, ends the pass, - /// because every height has to be taken again before the next group is judged; with - /// set it ends that group's judging instead. + /// because every height has to be taken again before the next group is judged. With + /// set, a step in a group ends that group's judging instead and the + /// next group is judged on the heights as they stand; a step in the header rows still ends + /// the pass. Each of the two header steps takes every cell it reaches at once, so the header + /// ends at most two passes. /// private HashSet<(int Row, int Cell)>? CellsToReadAsOneLine(LayoutBox[] fresh, TextStyle style, bool batch) { @@ -581,7 +587,8 @@ void Reach(int from, int to) // A step that adds a cell the other groups' heights can depend on ends the pass, // because the next group would be judged by heights that the step changes, a // column's width among them. After the bound on such passes (see the caller) it - // ends this group's judging instead, and the groups after it are judged together. + // ends this group's judging instead, and the groups after it are judged on the + // heights as they stand. The header steps below end the pass in either case. // A step that stays in this group's rows and in fixed-width columns changes no // other group's height, so the next group is judged in the same pass. own = (first, last); diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index 5feec3dff..32a08111f 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -1456,11 +1456,12 @@ public void TheCostOfGivingUpBreaksInFixedColumnsDoesNotGrowWithEachGroup() } /// - /// A group that gives up a cell in an automatically sized column measures the whole table again, - /// so the measurements of such groups are bounded: after eight, the groups not yet judged are - /// judged together. The allocations of 400 such groups stay under a fixed multiple of those of - /// the same table with the lines separated by spaces, which has nothing to give up. Without the - /// bound the multiple grows with the number of groups. Allocations are counted, not time. + /// A group that gives up a cell in an automatically sized column measures the whole table again. + /// After eight such measurements a pass judges every group it reaches, so groups that all lack + /// room on the heights the table starts with no longer take one measurement each. The + /// allocations of 400 such groups stay under a fixed multiple of those of the same table with + /// the lines separated by spaces, which has nothing to give up. Without the limit the multiple + /// grows with the number of groups. Allocations are counted, not time. /// [Fact] public void TheCostOfGivingUpBreaksInAutoColumnsIsBounded() @@ -1526,6 +1527,157 @@ public void AfterEightMeasurementsLaterGroupsAreJudgedTogether(int fillers, bool Assert.Equal(laterGroupGivesUp, dropped.Contains($"row {2 * fillers + 2}, cell 0")); } + /// The cells that filler groups give up, in row order. + private static string[] FillerReports(int fillers) => + [.. Enumerable.Range(0, fillers).Select(i => $"row {2 * i + 1}, cell 2")]; + + /// + /// Columns of 36pt, 36pt and one sized by its content, after an optional header. Each filler + /// group is a cell of 60 lines in the last column beside two short cells. It has no room on the + /// page and gives up its breaks in a column that other rows share, so each filler ends one + /// pass, and the pass after of them is the first to judge past a + /// group that ends its own judging. + /// + private static TableElement FillerTable(int fillers, Action? header = null) + { + var t = Wide10(36, 36, 0); + header?.Invoke(t); + for (var i = 0; i < fillers; i++) + { + t.AddRow().AddCell("x").AddCell("x").AddCell(new Cell(Words(60)) { RowSpan = 2 }); + t.AddRow().AddCell("y"); + } + return t; + } + + private static void LineFeedHeader(TableElement t) => t.AddRow(isHeader: true).AddCell(Words(30)); + + /// + /// A group of 268pt: a row of two short cells, the first spanning both rows, and a row of 20 + /// lines. A header of 30 lines leaves it 212pt, and a header of one line leaves it 560pt. + /// + private static void TwentyLineGroup(TableElement t) + { + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("b"); + t.AddRow().AddCell(Words(20)); + } + + /// + /// Every row of a group is measured again after the group gives up cells in it. A header of 30 + /// lines leaves 212pt, and a group of three rows is 20 + 20 + 248pt with the lines of one row. + /// Once that row's lines are given up the group is 60pt and fits, so the header keeps its + /// breaks. A measurement that leaves out the last row, or reads only the first, keeps the group + /// too tall and the header is relieved as well. The row with the lines is the middle row, then + /// the last. + /// + [Theory] + [InlineData(2)] + [InlineData(3)] + public void EveryRowOfAGroupIsMeasuredAgainAfterItGivesUpItsBreaks(int rowWithLines) + { + using var doc = WidePage(); + var t = Wide10(950, 950); + t.AddRow(isHeader: true).AddCell(Words(30)); + t.AddRow().AddCell(new Cell("a") { RowSpan = 3 }).AddCell("b"); + t.AddRow().AddCell(rowWithLines == 2 ? Words(20) : "c"); + t.AddRow().AddCell(rowWithLines == 3 ? Words(20) : "c"); + doc.Add(t); + + Save(doc); + + Assert.Equal([$"row {rowWithLines}, cell 0"], Dropped(doc)); + } + + /// + /// After eight measurements a header row that gives up its breaks still ends the pass. The + /// header of 30 lines leaves 212pt. The group after the fillers is 232pt, 17 plain words in a + /// column of one word, and has no breaks of its own, so the header is relieved on its account. + /// The group after it, 268pt with its 20 lines, then fits the 560pt that remain and keeps + /// them. Judged in the same pass, on the header as it stood, it would give them up. + /// + [Fact] + public void AHeaderThatGivesUpItsBreaksStillEndsAPassAfterEightMeasurements() + { + using var doc = WidePage(); + var t = FillerTable(8, LineFeedHeader); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("b"); + t.AddRow().AddCell(Words(17, " ")); + TwentyLineGroup(t); + doc.Add(t); + + Save(doc); + + Assert.Equal(["row 0, cell 0", .. FillerReports(8)], Dropped(doc)); + } + + /// + /// After eight measurements a group that gives up a cell in a shared column ends only its own + /// judging: the group after it is judged in the same pass, on the heights as they stand. The + /// group here gives up its cell in the automatic column and is still too tall for the room the + /// header leaves, so its judging ends there. The group after it is judged on the old header, + /// 212pt of room, and gives up its 20 lines, which it would keep on the 560pt left once the + /// header is relieved. + /// + [Fact] + public void AGroupThatEndsItsOwnJudgingAfterEightMeasurementsLeavesTheNextGroupToTheSamePass() + { + using var doc = WidePage(); + var t = FillerTable(8, LineFeedHeader); + t.AddRow().AddCell("a").AddCell("b").AddCell(new Cell(Words(3)) { RowSpan = 2 }); + t.AddRow().AddCell(Words(17, " ")); + TwentyLineGroup(t); + doc.Add(t); + + Save(doc); + + Assert.Equal(["row 0, cell 0", .. FillerReports(9), "row 20, cell 0"], Dropped(doc)); + } + + /// + /// A shared step that ended one group's judging does not carry over to the next group. The + /// ninth filler gives up its cell in the shared column. The group after it gives up a cell in + /// fixed columns only, is judged again and still has no room, so the header is relieved and the + /// pass ends before the last group is judged. Were the first group's step remembered, the + /// second group would end its judging without being judged again, and the last group would + /// give up its 20 lines. + /// + [Fact] + public void ASharedStepDoesNotEndTheJudgingOfTheNextGroupAfterEightMeasurements() + { + using var doc = WidePage(); + var t = FillerTable(9, LineFeedHeader); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell(Words(3)); + t.AddRow().AddCell(Words(17, " ")); + TwentyLineGroup(t); + doc.Add(t); + + Save(doc); + + Assert.Equal(["row 0, cell 0", .. FillerReports(9), "row 19, cell 1"], Dropped(doc)); + } + + /// + /// A tab that tips a group, with one in the header too, is a shared step of the third step. + /// After eight measurements it ends only that group's judging: the group after it is judged in + /// the same pass, on the header as it stood (32pt, 548pt of room), and gives up its 44 lines. + /// Its 556pt fits the 560pt left once the tab in the header is laid out unbroken. + /// + [Fact] + public void ASharedThirdStepAfterEightMeasurementsLeavesTheNextGroupToTheSamePass() + { + using var doc = WidePage(); + var t = FillerTable(8, x => x.AddRow(isHeader: true).AddCell("ab\tab")); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("ab\tab"); + t.AddRow().AddCell(Words(43, " ")); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("b"); + t.AddRow().AddCell(Words(44)); + doc.Add(t); + + Save(doc); + + Assert.Equal(["row 0, cell 0", .. FillerReports(8), "row 17, cell 1", "row 20, cell 0"], Dropped(doc)); + } + /// /// The same holds when a tab tips the groups over the page, the third step: each group is a /// span cell, a tab cell that wraps one line taller as two words than as one, and 46 plain From daa40c14546d1530acb3b1a1eb4bcd546ff4b480 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 07:42:38 +0100 Subject: [PATCH 16/48] refactor(layout): keep one control-space helper for bands and cells The chapter token added a second copy of the predicate and the replacement that LayoutText already holds. A table cell, a page label and a bookmark title now read control white space through the one helper. --- src/VellumPdf.Layout/Elements/BandTemplate.cs | 29 +------------------ .../Rendering/DocumentRenderer.cs | 2 +- 2 files changed, 2 insertions(+), 29 deletions(-) diff --git a/src/VellumPdf.Layout/Elements/BandTemplate.cs b/src/VellumPdf.Layout/Elements/BandTemplate.cs index 9608d9f0d..aa11172bc 100644 --- a/src/VellumPdf.Layout/Elements/BandTemplate.cs +++ b/src/VellumPdf.Layout/Elements/BandTemplate.cs @@ -186,7 +186,7 @@ internal sealed class BandText /// /// What {chapter} prints, or null for no text. Copied as it is and never scanned for a /// token. The caller has already read its control white space as spaces; see - /// . + /// . /// internal void Reset(int pageNumber, int totalPages, string? pageLabel = null, string? chapter = null) { @@ -218,33 +218,6 @@ internal void Reset(int pageNumber, int totalPages, string? pageLabel = null, st _offset = 0; } - /// - /// Returns with every tab, line break, form feed and other control - /// white space replaced by U+0020, or the same instance when it holds none. A band draws one - /// line, and no font draws these characters, so left as written they reach glyph lookup. The - /// Unicode space separators, the no-break spaces among them, are left as they are, because a - /// font draws them. - /// - internal static string ControlSpacesToSpaces(string text) - { - var at = -1; - for (var i = 0; i < text.Length; i++) - { - if (IsControlSpace(text[i])) { at = i; break; } - } - if (at < 0) return text; - - return string.Create(text.Length, (text, at), static (span, state) => - { - state.text.AsSpan().CopyTo(span); - for (var i = state.at; i < span.Length; i++) - if (IsControlSpace(span[i])) span[i] = ' '; - }); - } - - private static bool IsControlSpace(char c) => - char.IsWhiteSpace(c) && char.GetUnicodeCategory(c) != System.Globalization.UnicodeCategory.SpaceSeparator; - internal char this[int index] { get diff --git a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs index 554af93bb..15a8361d8 100644 --- a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs @@ -572,7 +572,7 @@ private void NoteChapter(IRenderer renderer) ChapterNotes++; if (renderer is not HeadingRenderer { Element: { Level: 0 } heading }) return; - var title = BandText.ControlSpacesToSpaces(heading.ResolvedBookmarkTitle); + var title = LayoutText.ControlSpacesToSpaces(heading.ResolvedBookmarkTitle); _chapterFirst ??= title; _chapterLatest = title; } From d12dcaad0e8471717670ff10676215ce3e16811c Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 07:42:40 +0100 Subject: [PATCH 17/48] perf(layout): measure each table cell's widths once per decision A decision that reads cells unbroken measured every cell's longest word and widest line again on each pass, though both depend only on the cell's text and mode. They are kept for the decision and dropped with it, so a table edited between saves is measured from nothing. --- .../Rendering/Table/TableGridResolver.cs | 56 +++++++++-- .../Rendering/Table/TableMeasureCache.cs | 68 +++++++++++++ .../Rendering/Table/TableRenderer.cs | 20 ++-- .../TableMeasureCacheTests.cs | 97 +++++++++++++++++++ 4 files changed, 225 insertions(+), 16 deletions(-) create mode 100644 src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs create mode 100644 tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs diff --git a/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs b/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs index 08af5c39a..585611718 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs @@ -37,6 +37,12 @@ internal sealed class TableGridResolver /// public IReadOnlySet<(int Row, int Cell)>? OneLineCells { get; init; } + /// + /// The measurements an earlier resolution of the same table already made, or null to measure + /// every cell. Which cells are read unbroken is part of an entry's key. + /// + public TableMeasureCache? Cache { get; init; } + public void Resolve(TableElement table, double availableWidth) { // The column count is the widest row, not merely the first (#480 section 1). Nothing stops @@ -305,17 +311,28 @@ private static void ScaleToFit(double[] widths, double available) // The widest word and the widest line of the lines the cell is measured in. A cell // of one line, which is every cell that holds no line break, measures as it always - // has. - var lines = TableRenderer.CellLines(cell.Content, honourBreaks: OneLineCells?.Contains((r, c)) != true); - var longest = 0.0; - var widest = 0.0; - for (var l = 0; l < lines.Length; l++) + // has. They depend on the text, the style and the mode alone, so a decision that + // measures the table again takes them from its cache. + var honourBreaks = OneLineCells?.Contains((r, c)) != true; + double longest, widest; + if (Cache is null) { - var words = lines[l].Split(' '); - var lineLongest = words.Max(w => cellStyle.FontRef.MeasureString(w, cellStyle.FontSize)); - var lineWidth = cellStyle.FontRef.MeasureString(lines[l], cellStyle.FontSize); - longest = l == 0 ? lineLongest : Math.Max(longest, lineLongest); - widest = l == 0 ? lineWidth : Math.Max(widest, lineWidth); + (longest, widest) = MeasureCell(cell.Content, cellStyle, honourBreaks); + } + else + { + ref var entry = ref Cache.Of(r, c, cells.Count, honourBreaks); + if (!entry.HasWidths) + { + (entry.LongestWord, entry.WidestLine) = MeasureCell(cell.Content, cellStyle, honourBreaks); + entry.HasWidths = true; + if (TableMeasureProbe.Current is { } miss) miss.WidthMisses++; + } + else if (TableMeasureProbe.Current is { } hit) + { + hit.WidthHits++; + } + (longest, widest) = (entry.LongestWord, entry.WidestLine); } var full = widest + cell.Padding.Horizontal; @@ -330,4 +347,23 @@ private static void ScaleToFit(double[] widths, double available) } return (minW, maxW); } + + /// + /// The widest word and the widest line of a cell's text, each line measured on its own. + /// + private static (double Longest, double Widest) MeasureCell(string content, TextStyle style, bool honourBreaks) + { + var lines = TableRenderer.CellLines(content, honourBreaks); + var longest = 0.0; + var widest = 0.0; + for (var l = 0; l < lines.Length; l++) + { + var words = lines[l].Split(' '); + var lineLongest = words.Max(w => style.FontRef.MeasureString(w, style.FontSize)); + var lineWidth = style.FontRef.MeasureString(lines[l], style.FontSize); + longest = l == 0 ? lineLongest : Math.Max(longest, lineLongest); + widest = l == 0 ? lineWidth : Math.Max(widest, lineWidth); + } + return (longest, widest); + } } diff --git a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs new file mode 100644 index 000000000..cb1b8c230 --- /dev/null +++ b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs @@ -0,0 +1,68 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +namespace VellumPdf.Layout.Rendering.Table; + +/// +/// What one table decision has measured of its cells, so that measuring the table again does not +/// measure every cell again. The decision that reads some cells unbroken measures the whole table +/// once per step; most steps change no cell's text, mode or width, and a cell's measurements +/// depend on nothing else. +/// +/// +/// The cache holds, per cell and per mode (breaks kept or read unbroken), the cell's longest +/// word and widest line, which depend on its text and mode alone. It lives for one decision and is +/// dropped with it, so a table that is edited between saves is measured from nothing. +/// Each entry is exact: a lookup returns what measuring again would return, bit for bit, or +/// misses. +/// +internal sealed class TableMeasureCache(int rowCount) +{ + private readonly CellMeasure[]?[] _rows = new CellMeasure[rowCount][]; + + /// The entry of a cell in one mode, created empty on first use. + public ref CellMeasure Of(int row, int cell, int cellCount, bool honourBreaks) + { + var slots = _rows[row] ??= new CellMeasure[cellCount * 2]; + return ref slots[(cell * 2) + (honourBreaks ? 0 : 1)]; + } +} + +/// One cell's cached measurements in one mode. +internal struct CellMeasure +{ + /// True when and are set. + public bool HasWidths; + + /// The widest word of the lines the cell is measured in, without padding. + public double LongestWord; + + /// The widest of the lines the cell is measured in, without padding. + public double WidestLine; +} + +/// +/// A hook for tests of the table caches: counts what the caches answered. It is thread-static and +/// null by default, so a save pays one null test for it. +/// +internal sealed class TableMeasureProbe +{ + [ThreadStatic] + private static TableMeasureProbe? s_current; + + /// The probe the saving thread reports to, or null. + public static TableMeasureProbe? Current + { + get => s_current; + set => s_current = value; + } + + /// Cells whose longest word and widest line a resolution took from the cache. + public int WidthHits { get; set; } + + /// Cells whose longest word and widest line a resolution measured. + public int WidthMisses { get; set; } + + /// The number of times the decision measured the whole table. + public int Passes { get; set; } +} diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 08d447307..d1c1da7da 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -271,7 +271,14 @@ public LayoutResult Layout(LayoutContext context) var decided = key is not null && _decidedFor is { } was && was.Equals(key.Value); if (!decided) _oneLine = null; - ResolveGrid(area.Width, style); + // A decision that reads some cells unbroken measures the table once per step, so it + // keeps what each cell measures: nothing else depends on the cells' text, and the + // cache is dropped with the decision. A table that reads no cell unbroken measures + // once. + var passesNeeded = !decided && fresh is not null && AnyControlSpace(rows); + var cache = passesNeeded ? new TableMeasureCache(rows.Count) : null; + + ResolveGrid(area.Width, style, cache); // Rows that cannot be cut between their lines must not be left without room on a page // by reading a cell's line breaks, or its other control white space as spaces; @@ -281,14 +288,14 @@ public LayoutResult Layout(LayoutContext context) // no second pass. Each pass costs one measurement of the whole table, so after // MaxPassesBeforeBatching of them a pass no longer stops at the first group step that // changes other groups' heights. A step in the header rows still ends it. - if (!decided && fresh is not null && AnyControlSpace(rows)) + if (passesNeeded) { var passes = 0; - while (CellsToReadAsOneLine(fresh, style, ++passes > MaxPassesBeforeBatching) is { } more) + while (CellsToReadAsOneLine(fresh!, style, ++passes > MaxPassesBeforeBatching) is { } more) { _oneLine ??= []; _oneLine.UnionWith(more); - ResolveGrid(area.Width, style); + ResolveGrid(area.Width, style, cache); } } _decidedFor = key; @@ -413,10 +420,11 @@ public LayoutResult Layout(LayoutContext context) /// Resolves the column widths and every row's height, reading the breaks of the cells in /// _oneLine unbroken. The checks run in the order the exceptions are documented in. /// - private void ResolveGrid(double areaWidth, TextStyle style) + private void ResolveGrid(double areaWidth, TextStyle style, TableMeasureCache? cache) { + if (TableMeasureProbe.Current is { } probe) probe.Passes++; var rows = _table.Rows; - var grid = new TableGridResolver { OneLineCells = _oneLine }; + var grid = new TableGridResolver { OneLineCells = _oneLine, Cache = cache }; grid.Resolve(_table, areaWidth); _colWidths = grid.ColWidths; diff --git a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs new file mode 100644 index 000000000..da9901865 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs @@ -0,0 +1,97 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Elements.Table; +using VellumPdf.Layout.Rendering.Table; + +namespace VellumPdf.Layout.Tests; + +/// +/// The caches of the decision that reads some table cells unbroken. A cache answers what measuring +/// again would, so these tests count what it answered and compare the outcome with the one the +/// documentation states; the differential against the build without the caches is run apart from +/// the suite. +/// +public sealed class TableMeasureCacheTests +{ + private static TextStyle Helvetica(double size = 10) => new() + { + FontRef = new FontReference(Standard14.Helvetica), + FontSize = size, + }; + + private static Document WidePage() => new() + { + PageSize = new PdfRectangle(0, 0, 2000, 600), + Margins = new EdgeInsets(10), + }; + + private static string Words(int n, string separator = "\n") => + string.Join(separator, Enumerable.Repeat("ab", n)); + + private static byte[] Save(Document doc) + { + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + private static string[] Dropped(Document doc) => + [.. doc.Diagnostics + .Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped) + .Select(d => Regex.Match(d.Message, @"row \d+, cell \d+").Value) + .OrderBy(m => int.Parse(Regex.Match(m, @"\d+").Value, CultureInfo.InvariantCulture)) + .ThenBy(m => m, StringComparer.Ordinal)]; + + /// Runs with a probe on this thread, and returns the probe. + private static TableMeasureProbe Probed(Action save) + { + var probe = new TableMeasureProbe(); + TableMeasureProbe.Current = probe; + try { save(); } + finally { TableMeasureProbe.Current = null; } + return probe; + } + + /// + /// Columns of 36pt, 36pt and one sized by its content, then groups + /// that each give up the breaks of a cell of 60 lines in the automatic column. + /// + private static TableElement FillerTable(int groups) + { + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(36, 36, 0); + for (var i = 0; i < groups; i++) + { + t.AddRow().AddCell("x").AddCell("x").AddCell(new Cell(Words(60)) { RowSpan = 2 }); + t.AddRow().AddCell("y"); + } + return t; + } + + /// + /// A cell's longest word and widest line are measured once per mode. Each of the 6 groups ends + /// a pass, so the table is resolved more than 6 times, and a cell is measured once as it is + /// and, for the cell that gives up its breaks, once as it is read unbroken. + /// + [Fact] + public void ACellIsMeasuredForItsColumnWidthOncePerMode() + { + const int groups = 6; + using var doc = WidePage(); + doc.Add(FillerTable(groups)); + + var probe = Probed(() => Save(doc)); + + Assert.Equal(Enumerable.Range(0, groups).Select(i => $"row {2 * i}, cell 2").ToArray(), Dropped(doc)); + Assert.True(probe.Passes > groups, $"{probe.Passes} resolutions"); + const int cells = 4 * groups; + Assert.Equal(cells + groups, probe.WidthMisses); + Assert.True(probe.WidthHits > probe.WidthMisses, $"{probe.WidthHits} hits, {probe.WidthMisses} misses"); + } +} From fbb20f280e340ea6d9b62e86fbf335ad260313f3 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 07:46:50 +0100 Subject: [PATCH 18/48] perf(layout): count a cell's lines once per width interval Measuring a row wrapped every cell again, though a cell's line count only changes when the column width crosses one of the comparisons the wrap made. The count is kept with the interval of widths over which every comparison comes out the same; a word that was broken at its characters pins it to that width. A test probe can check each hit against a fresh wrap. --- .../Rendering/Table/TableMeasureCache.cs | 50 ++++++- .../Rendering/Table/TableRenderer.cs | 140 +++++++++++++++++- .../TableMeasureCacheTests.cs | 122 +++++++++++++++ 3 files changed, 306 insertions(+), 6 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs index cb1b8c230..c1f63a9ae 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs @@ -11,8 +11,9 @@ namespace VellumPdf.Layout.Rendering.Table; /// /// /// The cache holds, per cell and per mode (breaks kept or read unbroken), the cell's longest -/// word and widest line, which depend on its text and mode alone. It lives for one decision and is -/// dropped with it, so a table that is edited between saves is measured from nothing. +/// word and widest line, which depend on its text and mode alone, and the number of lines it wraps +/// into, with the interval of widths over which that number holds. It lives for one decision and +/// is dropped with it, so a table that is edited between saves is measured from nothing. /// Each entry is exact: a lookup returns what measuring again would return, bit for bit, or /// misses. /// @@ -39,11 +40,41 @@ internal struct CellMeasure /// The widest of the lines the cell is measured in, without padding. public double WidestLine; + + /// True when and the interval that holds it are set. + public bool HasLines; + + /// + /// True when the count depends on the exact width, because a word wider than the width was + /// broken at its characters. then holds that width and + /// is unused. + /// + public bool Pinned; + + /// The number of lines the cell wraps into. + public int Lines; + + /// + /// The lowest width at which every comparison of the wrap comes out as it did. + /// + public double From; + + /// + /// The lowest width from which one of those comparisons comes out differently. + /// + public double Below; + + /// + /// True when the cell wraps into lines at . + /// + public readonly bool Holds(double width) => + HasLines && (Pinned ? width.Equals(From) : From <= width && width < Below); } /// -/// A hook for tests of the table caches: counts what the caches answered. It is thread-static and -/// null by default, so a save pays one null test for it. +/// A hook for tests of the table caches: counts what the caches answered, and when +/// is set measures again on every hit and throws when the answer differs. +/// It is thread-static and null by default, so a save pays one null test for it. /// internal sealed class TableMeasureProbe { @@ -57,6 +88,17 @@ public static TableMeasureProbe? Current set => s_current = value; } + /// + /// When set, a cached line count is checked against a fresh wrap on every hit. + /// + public bool Verify { get; init; } + + /// Cells whose line count a measurement took from the cache. + public int WrapHits { get; set; } + + /// Cells whose line count a measurement wrapped. + public int WrapMisses { get; set; } + /// Cells whose longest word and widest line a resolution took from the cache. public int WidthHits { get; set; } diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index d1c1da7da..a83156659 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -62,6 +62,9 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IP // break is kept. private HashSet<(int Row, int Cell)>? _oneLine; + // What the decision under way has measured of each cell; null outside it. + private TableMeasureCache? _measured; + /// /// The number of passes over the table's heights that each stop at the first step changing /// another group's height. Pass 9 and later judge every group they reach, each on the heights @@ -298,6 +301,7 @@ public LayoutResult Layout(LayoutContext context) ResolveGrid(area.Width, style, cache); } } + _measured = null; _decidedFor = key; } @@ -423,6 +427,7 @@ public LayoutResult Layout(LayoutContext context) private void ResolveGrid(double areaWidth, TextStyle style, TableMeasureCache? cache) { if (TableMeasureProbe.Current is { } probe) probe.Passes++; + _measured = cache; var rows = _table.Rows; var grid = new TableGridResolver { OneLineCells = _oneLine, Cache = cache }; grid.Resolve(_table, areaWidth); @@ -454,7 +459,11 @@ private double MeasureRow(int r, TextStyle style) LayoutValidation.ValidateFontSize(cs, $"Table row {r}, cell {cellIndex}"); var colW = ColSpanWidth(col, cell.ColSpan); var innerW = colW - cell.Padding.Horizontal; - var lines = WordWrapCount(cell.Content, cs, Math.Max(1, innerW), HonoursBreaks(r, cellIndex)); + var honourBreaks = HonoursBreaks(r, cellIndex); + var wrapWidth = Math.Max(1, innerW); + var lines = _measured is null + ? WordWrapCount(cell.Content, cs, wrapWidth, honourBreaks) + : CachedLineCount(_measured, (r, cellIndex, row.Cells.Count), cell.Content, cs, wrapWidth, honourBreaks); var cellH = lines * cs.EffectiveLeading + cell.Padding.Vertical; maxH = Math.Max(maxH, cellH); col += cell.ColSpan; @@ -462,6 +471,133 @@ private double MeasureRow(int r, TextStyle style) return maxH; } + /// + /// The number of lines wraps the text into at + /// , from the decision's cache when the width lies in the interval the + /// cached count was found for. + /// + private static int CachedLineCount( + TableMeasureCache cache, (int Row, int Cell, int CellCount) at, string text, TextStyle style, + double width, bool honourBreaks) + { + ref var entry = ref cache.Of(at.Row, at.Cell, at.CellCount, honourBreaks); + var probe = TableMeasureProbe.Current; + if (entry.Holds(width)) + { + if (probe is not null) + { + probe.WrapHits++; + if (probe.Verify && WordWrapCount(text, style, width, honourBreaks) != entry.Lines) + throw new InvalidOperationException( + $"A cached line count of {entry.Lines} does not hold at width {width:R}."); + } + return entry.Lines; + } + + if (probe is not null) probe.WrapMisses++; + entry.Lines = CountLines(text, style, width, honourBreaks, out entry.From, out entry.Below, out entry.Pinned); + entry.HasLines = true; + return entry.Lines; + } + + /// + /// The number of lines returns, without building them, and the + /// widths over which the count is the same. Each comparison of a width against a measurement + /// narrows and , so the count holds for every + /// width in [from, below), and for exactly the width given when a word wider than it was + /// broken at its characters (), because where that word breaks + /// follows the width. This method follows step for step, an empty word + /// included, and takes the same measurements from the font in the same order. + /// + internal static int CountLines( + string text, TextStyle style, double maxWidth, bool honourBreaks, + out double from, out double below, out bool pinned) + { + from = double.NegativeInfinity; + below = double.PositiveInfinity; + pinned = false; + if (string.IsNullOrEmpty(text)) return 1; + + var total = 0; + foreach (var line in CellLines(text, honourBreaks)) + total += CountLine(line, style, maxWidth, ref from, ref below, ref pinned); + if (pinned) from = maxWidth; + return total; + } + + private static int CountLine( + string text, TextStyle style, double maxWidth, ref double from, ref double below, ref bool pinned) + { + if (string.IsNullOrEmpty(text)) return 1; + + var words = text.Split(' '); + var spaceW = style.FontRef.MeasureString(" ", style.FontSize); + + // The length of the line under way, as WrapLine's buffer holds it: an empty word at the + // start of a line leaves the buffer empty, so the next word starts a line again. + var length = 0; + var lineW = 0.0; + var lines = 0; + + foreach (var word in words) + { + var ww = style.FontRef.MeasureString(word, style.FontSize); + if (length > 0) + { + var joined = lineW + spaceW + ww; + if (joined <= maxWidth) + { + from = Math.Max(from, joined); + length += 1 + word.Length; + lineW += spaceW + ww; + continue; + } + + below = Math.Min(below, joined); + lines++; + length = 0; + lineW = 0.0; + } + + // The start of a line. A word wider than the line is broken at its characters, which + // adds its fragments and leaves no line under way. + if (ww > maxWidth) + { + below = Math.Min(below, ww); + pinned = true; + lines += CountHardBreakFragments(word, style, maxWidth); + continue; + } + from = Math.Max(from, ww); + length = word.Length; + lineW = ww; + } + if (length > 0) lines++; + return lines == 0 ? 1 : lines; + } + + /// The number of lines adds for a word. + private static int CountHardBreakFragments(string word, TextStyle style, double maxWidth) + { + var fragments = 0; + var open = false; + var fragmentW = 0.0; + foreach (var rune in word.EnumerateRunes()) + { + var charW = style.FontRef.MeasureString(rune.ToString(), style.FontSize); + if (open && fragmentW + charW > maxWidth) + { + fragments++; + fragmentW = 0.0; + open = false; + } + open = true; + fragmentW += charW; + } + if (open) fragments++; + return fragments; + } + /// /// True when the cell's line breaks are kept; false when the table lays the cell out unbroken. /// @@ -1381,7 +1517,7 @@ private double ColSpanWidth(int startCol, int span) /// let the hard-break below (#473) reach both call sites from a single change instead of two /// that would otherwise have to be kept in step by hand. /// - private static int WordWrapCount(string text, TextStyle style, double maxWidth, bool honourBreaks) => + internal static int WordWrapCount(string text, TextStyle style, double maxWidth, bool honourBreaks) => WordWrapLines(text, style, maxWidth, honourBreaks).Count; /// diff --git a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs index da9901865..4e84ba1cf 100644 --- a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs @@ -94,4 +94,126 @@ public void ACellIsMeasuredForItsColumnWidthOncePerMode() Assert.Equal(cells + groups, probe.WidthMisses); Assert.True(probe.WidthHits > probe.WidthMisses, $"{probe.WidthHits} hits, {probe.WidthMisses} misses"); } + + private static readonly string[] Alphabet = + ["a", "i", "W", "ab", "word", "m", " ", " ", " ", " ", "\n", "\t", "\r\n", "x\u00A0y", "\u0001", "WWWWWWWW"]; + + private static string RandomText(Random rng) + { + var parts = rng.Next(0, 24); + var sb = new System.Text.StringBuilder(); + for (var i = 0; i < parts; i++) sb.Append(Alphabet[rng.Next(Alphabet.Length)]); + return sb.ToString(); + } + + /// + /// The count a certificate returns is the count of the wrap it stands for, and it holds across + /// the interval it names: at the width it was made for, at the low end, and just under the + /// high end. A word wider than the width is broken at its characters, which pins the count to + /// that width. The texts include empty words, doubled spaces, line breaks and tabs, in both + /// modes, and widths down to one point. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ACertificateCountsLikeTheWrapItStandsForAcrossItsInterval(bool honourBreaks) + { + var style = Helvetica(); + var rng = new Random(honourBreaks ? 1 : 2); + var pinned = 0; + var intervals = 0; + for (var n = 0; n < 4000; n++) + { + var text = RandomText(rng); + var width = Math.Max(1, rng.NextDouble() * 120); + var lines = TableRenderer.CountLines(text, style, width, honourBreaks, out var from, out var below, out var isPinned); + + Assert.Equal(TableRenderer.WordWrapCount(text, style, width, honourBreaks), lines); + if (isPinned) + { + pinned++; + Assert.Equal(width, from); + continue; + } + + intervals++; + Assert.True(from <= width && width < below, $"{from} <= {width} < {below}"); + if (double.IsFinite(from) && from >= 1) + Assert.Equal(lines, TableRenderer.WordWrapCount(text, style, from, honourBreaks)); + if (double.IsFinite(below)) + Assert.Equal(lines, TableRenderer.WordWrapCount(text, style, Math.BitDecrement(below), honourBreaks)); + } + + Assert.True(pinned > 100 && intervals > 100, $"{pinned} pinned, {intervals} intervals"); + } + + /// + /// A wrap whose words all fit holds over a range of widths, and one that broke a word holds + /// at the width alone. One more point of width moves no break in "ab ab ab ab" at 36pt, and + /// moves the break of "abcdefghijklmnop" in a 20pt column. + /// + [Fact] + public void ACertificateHoldsOverARangeUnlessAWordWasBroken() + { + var style = Helvetica(); + + var lines = TableRenderer.CountLines("ab ab ab ab", style, 36, true, out var from, out var below, out var pinned); + Assert.Equal(TableRenderer.WordWrapCount("ab ab ab ab", style, 36, true), lines); + Assert.False(pinned); + Assert.True(from < 36 && 37 < below, $"[{from}, {below})"); + + TableRenderer.CountLines("abcdefghijklmnop", style, 20, true, out from, out _, out pinned); + Assert.True(pinned); + Assert.Equal(20.0, from); + } + + /// + /// The line counts the caches answer are the counts of a fresh wrap: the probe measures again + /// on every hit and throws on a difference. Widths that shrink as groups give up their breaks + /// move across the intervals, so both hits and misses are exercised. + /// + [Fact] + public void EveryCachedLineCountEqualsAFreshWrap() + { + using var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }; + for (var i = 0; i < 5; i++) + { + t.AddRow().AddCell("x").AddCell(new Cell(Words(48 + i)) { RowSpan = 2 }) + .AddCell(string.Join(" ", Enumerable.Repeat("lorem ipsum dolor", 3 + i))); + t.AddRow().AddCell("y"); + } + doc.Add(t); + + var probe = new TableMeasureProbe { Verify = true }; + TableMeasureProbe.Current = probe; + try { Save(doc); } + finally { TableMeasureProbe.Current = null; } + + Assert.True(probe.WrapHits > 0, $"{probe.WrapHits} hits"); + Assert.True(probe.WrapMisses > 0, $"{probe.WrapMisses} misses"); + Assert.Equal(5, Dropped(doc).Length); + } + + /// + /// A cell read unbroken and the same cell with its breaks kept are two entries: the count of + /// one is not the count of the other. The header of 60 lines is 728pt and the page holds 580pt, + /// so it is read unbroken; the next table keeps its breaks at 60 lines in a row that can be cut. + /// + [Fact] + public void TheModeOfACellIsPartOfItsEntry() + { + using var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(500, 500); + t.AddRow(isHeader: true).AddCell(Words(60)).AddCell("h"); + t.AddRow().AddCell(Words(60)).AddCell("y"); + doc.Add(t); + + var probe = new TableMeasureProbe { Verify = true }; + TableMeasureProbe.Current = probe; + try { Save(doc); } + finally { TableMeasureProbe.Current = null; } + + Assert.Equal(["row 0, cell 0"], Dropped(doc)); + } } From a9cdc73b8d573b5868220aee3a80147aa4699bbe Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 07:56:21 +0100 Subject: [PATCH 19/48] fix(layout): judge every table group on the heights before it After eight measurements a pass judged all the groups it reached on the heights it started with, so a group could give up more cells than judging it on the heights its predecessors left would. The limit goes, and a table decides the same cells however many groups it holds. The commits after this one keep what each cell measures, which is what made the limit unnecessary. --- CHANGELOG.md | 13 -- src/VellumPdf.Layout/Elements/Table/Cell.cs | 16 +- .../Elements/Table/TableElement.cs | 11 +- .../Rendering/Table/TableRenderer.cs | 40 +--- .../TableCellBreakTests.cs | 197 ------------------ 5 files changed, 17 insertions(+), 260 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e25e500d..ee0828a8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -662,19 +662,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). one of 47 is 572pt, fits the page alone, but leaves the row 8pt, so it falls back. The XML documentation of `Cell.Content` states when a header or a group has no room, which cells fall back and in what order, and what a renderer laid out without the document does. - - **The decision costs a measurement of the whole table each time a header row, or a group - that gives up a cell in an automatically sized column, falls back.** After 8 such - measurements a pass no longer ends at the first group that gives up a cell: it judges every - group it reaches on the heights as they stand, and the passes repeat until one adds nothing. - That keeps the cost off the number of groups when they all lack room on the heights the table - starts with. A table that needs no more than 8 measurements is decided exactly as - group-by-group judging would decide it; beyond that, a later group can give up more cells - than group-by-group judging would, or fewer. When each group's fallback changes the width of - an automatic column that the next group is judged by, the next group is found only by the - next measurement, so the table is still measured once for each group: 400 such groups took - 23s and 9,382MB of allocation in one run, where the same table took 4.9s and 3,023MB before - this change. Groups that give up a cell in fixed-width columns only measure their own rows and do - not count towards the 8. - **`/FontBBox` of an embedded font is the font's own bounding box (#596).** The descriptor of every embedded TrueType and OpenType font held `[0, hhea descender, 1000 * 1000 / unitsPerEm, hhea ascender]`: a zero for xMin and a constant for xMax, so DejaVu Sans, Liberation Sans and Liberation diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index f0144574e..1747d0ee2 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -68,18 +68,10 @@ public sealed class Cell /// space and sits in them or in an automatically sized column that a cell of them is in. A /// cell that holds only a line feed can be reached by any step. A cell no step reaches keeps /// its breaks. - /// The table's heights are measured again each time a header row, or a group in an - /// automatically sized column, gives up a cell, because that can change other rows. After the - /// table has been measured again 8 times for this decision, a pass no longer ends at the - /// first group that gives up such a cell: it judges every group it reaches on the heights as - /// they stand, and passes repeat until one adds no cell. A header row that gives up cells - /// still ends the pass. A table that needs no more than 8 such measurements is laid out as if - /// every group were judged on the heights the earlier ones left; beyond that, a later group - /// can give up more cells than judging it on those heights would, or fewer. That keeps the - /// measurements down for groups that all lack room on the heights the table starts with. When - /// the cells each group gives up change the width of an automatically sized column that the - /// next group is judged by, the next group is found only by the next measurement, so the - /// table is still measured once for each group. + /// A header row, or a group in an automatically sized column, that gives up a cell can + /// change other rows: the column's width is shared with every row that has a cell in it. The + /// groups after it are judged on the heights that result, so every group is judged on the + /// heights the decisions before it leave, however many groups the table has. /// A row that can be cut between its lines is cut when it is taller than a page. A /// repeated header row or a span group is never cut, and the save refuses it when it does not /// fit; a table whose rows are all headers repeats none of them, so its rows are cut like any diff --git a/src/VellumPdf.Layout/Elements/Table/TableElement.cs b/src/VellumPdf.Layout/Elements/Table/TableElement.cs index 464d47575..7048d0d25 100644 --- a/src/VellumPdf.Layout/Elements/Table/TableElement.cs +++ b/src/VellumPdf.Layout/Elements/Table/TableElement.cs @@ -35,13 +35,10 @@ namespace VellumPdf.Layout.Elements.Table; /// tabs of some cells, and the save lists each as /// ; says when /// and which. -/// Each time a header row, or a group in an automatically sized column, gives up a cell, -/// the save measures the whole table again. A group that gives up cells in fixed-width -/// columns only measures its own rows again. After 8 measurements of the whole table for this -/// decision, a pass judges every group it reaches together, which saves measurements only when -/// no group is tipped by the cells another gave up: a table in which each group's cells change -/// the width of a column the next group is judged by is still measured once for each group. -/// says what that changes in what is drawn. +/// Every group is judged on the heights the groups before it leave. A header row, or +/// a group in an automatically sized column, that gives up a cell can change the width of a +/// column the next group is judged by, so the next group is judged on the widths that result, +/// however many groups there are. says which cells are given up. /// These are refused, and never cut. /// throws whose message starts with the standard /// too-tall text and ends with a sentence naming the rows, for: header rows that together do not diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index a83156659..67506d022 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -65,17 +65,6 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IP // What the decision under way has measured of each cell; null outside it. private TableMeasureCache? _measured; - /// - /// The number of passes over the table's heights that each stop at the first step changing - /// another group's height. Pass 9 and later judge every group they reach, each on the heights - /// as they stand, and the passes repeat until one adds no cell. That keeps the measurements - /// down for groups that all lack room on the heights the table starts with. It does not for a - /// chain in which each group is tipped by the cells the one before it gave up: that table is - /// measured once per group. - /// states the rule. - /// - internal const int MaxPassesBeforeBatching = 8; - // What _oneLine was decided for: the table width and the vertical extent of the two fresh // boxes. // A renderer that carries the decision to the next page reuses it when it lays out at the same @@ -288,13 +277,10 @@ public LayoutResult Layout(LayoutContext context) // Cell.Content says when, and which cells give them up. The cells that would leave // them so are laid out unbroken, and the grid and the heights are taken again. Each // pass adds cells, so this ends; most tables, which hold no control white space, take - // no second pass. Each pass costs one measurement of the whole table, so after - // MaxPassesBeforeBatching of them a pass no longer stops at the first group step that - // changes other groups' heights. A step in the header rows still ends it. + // no second pass. if (passesNeeded) { - var passes = 0; - while (CellsToReadAsOneLine(fresh!, style, ++passes > MaxPassesBeforeBatching) is { } more) + while (CellsToReadAsOneLine(fresh!, style) is { } more) { _oneLine ??= []; _oneLine.UnionWith(more); @@ -619,13 +605,11 @@ private static bool AnyControlSpace(IReadOnlyList rows) /// method judges the header rows first and then each group in /// order, and a group again after its own breaks are given up in fixed-width columns. A step /// that adds a cell in a header row, or in an automatically sized column, ends the pass, - /// because every height has to be taken again before the next group is judged. With - /// set, a step in a group ends that group's judging instead and the - /// next group is judged on the heights as they stand; a step in the header rows still ends - /// the pass. Each of the two header steps takes every cell it reaches at once, so the header - /// ends at most two passes. + /// because every height has to be taken again before the next group is judged. Each of the + /// two header steps takes every cell it reaches at once, so the header ends at most two + /// passes. /// - private HashSet<(int Row, int Cell)>? CellsToReadAsOneLine(LayoutBox[] fresh, TextStyle style, bool batch) + private HashSet<(int Row, int Cell)>? CellsToReadAsOneLine(LayoutBox[] fresh, TextStyle style) { var rows = _table.Rows; var header = FindHeaderRowIndices(rows); @@ -734,20 +718,14 @@ void Reach(int from, int to) // A step that adds a cell the other groups' heights can depend on ends the pass, // because the next group would be judged by heights that the step changes, a - // column's width among them. After the bound on such passes (see the caller) it - // ends this group's judging instead, and the groups after it are judged on the - // heights as they stand. The header steps below end the pass in either case. + // column's width among them. The header steps below end it too. // A step that stays in this group's rows and in fixed-width columns changes no // other group's height, so the next group is judged in the same pass. own = (first, last); shared = false; if (CollectBreaks(first, last)) { - if (shared) - { - if (!batch) return found; - break; - } + if (shared) return found; // Only this group's rows are measured again, in the columns they have. (_oneLine ??= []).UnionWith(found!); @@ -757,7 +735,7 @@ void Reach(int from, int to) own = (-1, -1); if (header.Count > 0 && CollectBreaks(0, header[^1])) return found; own = (first, last); - if (CollectControlSpace(first, last) && shared && !batch) return found; + if (CollectControlSpace(first, last) && shared) return found; break; } } diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index 32a08111f..73a73983c 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -1455,113 +1455,6 @@ public void TheCostOfGivingUpBreaksInFixedColumnsDoesNotGrowWithEachGroup() Assert.True(withBreaks.Bytes < 1.5 * withSpaces.Bytes, $"{withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); } - /// - /// A group that gives up a cell in an automatically sized column measures the whole table again. - /// After eight such measurements a pass judges every group it reaches, so groups that all lack - /// room on the heights the table starts with no longer take one measurement each. The - /// allocations of 400 such groups stay under a fixed multiple of those of the same table with - /// the lines separated by spaces, which has nothing to give up. Without the limit the multiple - /// grows with the number of groups. Allocations are counted, not time. - /// - [Fact] - public void TheCostOfGivingUpBreaksInAutoColumnsIsBounded() - { - static (long Bytes, int Reported) Allocated(int groups, string separator) - { - using var doc = WidePage(); - var t = new TableElement { DefaultCellStyle = Helvetica(10) }; - for (var i = 0; i < groups; i++) - { - t.AddRow().AddCell(new Cell(Words(60, separator)) { RowSpan = 2 }).AddCell("x"); - t.AddRow().AddCell("y"); - } - doc.Add(t); - var before = GC.GetAllocatedBytesForCurrentThread(); - Save(doc); - var bytes = GC.GetAllocatedBytesForCurrentThread() - before; - return (bytes, doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped).Sum(d => d.Count)); - } - - Allocated(10, "\n"); - Allocated(10, " "); - var withBreaks = Allocated(400, "\n"); - var withSpaces = Allocated(400, " "); - - Assert.Equal(400, withBreaks.Reported); - Assert.Equal(0, withSpaces.Reported); - Assert.True(withBreaks.Bytes < 2.0 * withSpaces.Bytes, $"{withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); - } - - /// - /// The bound on measurements is eight, and what it changes is what the documentation says. Each - /// filler group gives up a cell in an automatic column and so ends a pass. The groups after the - /// fillers are one that gives up its cell, and one that keeps its breaks when it is judged on - /// the heights the first one leaves. With seven fillers before them that holds; with eight the - /// two are judged together, on the heights before the first was relieved, and the second gives up - /// its cell too. - /// - [Theory] - [InlineData(7, false)] - [InlineData(8, true)] - public void AfterEightMeasurementsLaterGroupsAreJudgedTogether(int fillers, bool laterGroupGivesUp) - { - using var doc = new Document { PageSize = new PdfRectangle(0, 0, 600, 300), Margins = new EdgeInsets(10) }; - var t = new TableElement { DefaultCellStyle = Helvetica(10) }; - for (var i = 0; i < fillers; i++) - { - t.AddRow().AddCell("x").AddCell("x").AddCell(new Cell(string.Join("\n", Enumerable.Repeat("i", 40))) { RowSpan = 2 }); - t.AddRow().AddCell("y"); - } - t.AddRow().AddCell(new Cell(Words(30)) { RowSpan = 2 }).AddCell("x"); - t.AddRow().AddCell("y"); - t.AddRow().AddCell(new Cell(Words(12).Replace("ab", "word word word")) { RowSpan = 2 }).AddCell("z"); - t.AddRow().AddCell("y"); - t.AddRow().AddCell("o").AddCell(string.Join(" ", Enumerable.Repeat("lorem ipsum dolor sit amet", 16))); - doc.Add(t); - - Save(doc); - - var dropped = Dropped(doc); - Assert.Equal(fillers + 1 + (laterGroupGivesUp ? 1 : 0), dropped.Length); - Assert.Contains($"row {2 * fillers}, cell 0", dropped); - Assert.Equal(laterGroupGivesUp, dropped.Contains($"row {2 * fillers + 2}, cell 0")); - } - - /// The cells that filler groups give up, in row order. - private static string[] FillerReports(int fillers) => - [.. Enumerable.Range(0, fillers).Select(i => $"row {2 * i + 1}, cell 2")]; - - /// - /// Columns of 36pt, 36pt and one sized by its content, after an optional header. Each filler - /// group is a cell of 60 lines in the last column beside two short cells. It has no room on the - /// page and gives up its breaks in a column that other rows share, so each filler ends one - /// pass, and the pass after of them is the first to judge past a - /// group that ends its own judging. - /// - private static TableElement FillerTable(int fillers, Action? header = null) - { - var t = Wide10(36, 36, 0); - header?.Invoke(t); - for (var i = 0; i < fillers; i++) - { - t.AddRow().AddCell("x").AddCell("x").AddCell(new Cell(Words(60)) { RowSpan = 2 }); - t.AddRow().AddCell("y"); - } - return t; - } - - private static void LineFeedHeader(TableElement t) => t.AddRow(isHeader: true).AddCell(Words(30)); - - /// - /// A group of 268pt: a row of two short cells, the first spanning both rows, and a row of 20 - /// lines. A header of 30 lines leaves it 212pt, and a header of one line leaves it 560pt. - /// - private static void TwentyLineGroup(TableElement t) - { - t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("b"); - t.AddRow().AddCell(Words(20)); - } - /// /// Every row of a group is measured again after the group gives up cells in it. A header of 30 /// lines leaves 212pt, and a group of three rows is 20 + 20 + 248pt with the lines of one row. @@ -1588,96 +1481,6 @@ public void EveryRowOfAGroupIsMeasuredAgainAfterItGivesUpItsBreaks(int rowWithLi Assert.Equal([$"row {rowWithLines}, cell 0"], Dropped(doc)); } - /// - /// After eight measurements a header row that gives up its breaks still ends the pass. The - /// header of 30 lines leaves 212pt. The group after the fillers is 232pt, 17 plain words in a - /// column of one word, and has no breaks of its own, so the header is relieved on its account. - /// The group after it, 268pt with its 20 lines, then fits the 560pt that remain and keeps - /// them. Judged in the same pass, on the header as it stood, it would give them up. - /// - [Fact] - public void AHeaderThatGivesUpItsBreaksStillEndsAPassAfterEightMeasurements() - { - using var doc = WidePage(); - var t = FillerTable(8, LineFeedHeader); - t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("b"); - t.AddRow().AddCell(Words(17, " ")); - TwentyLineGroup(t); - doc.Add(t); - - Save(doc); - - Assert.Equal(["row 0, cell 0", .. FillerReports(8)], Dropped(doc)); - } - - /// - /// After eight measurements a group that gives up a cell in a shared column ends only its own - /// judging: the group after it is judged in the same pass, on the heights as they stand. The - /// group here gives up its cell in the automatic column and is still too tall for the room the - /// header leaves, so its judging ends there. The group after it is judged on the old header, - /// 212pt of room, and gives up its 20 lines, which it would keep on the 560pt left once the - /// header is relieved. - /// - [Fact] - public void AGroupThatEndsItsOwnJudgingAfterEightMeasurementsLeavesTheNextGroupToTheSamePass() - { - using var doc = WidePage(); - var t = FillerTable(8, LineFeedHeader); - t.AddRow().AddCell("a").AddCell("b").AddCell(new Cell(Words(3)) { RowSpan = 2 }); - t.AddRow().AddCell(Words(17, " ")); - TwentyLineGroup(t); - doc.Add(t); - - Save(doc); - - Assert.Equal(["row 0, cell 0", .. FillerReports(9), "row 20, cell 0"], Dropped(doc)); - } - - /// - /// A shared step that ended one group's judging does not carry over to the next group. The - /// ninth filler gives up its cell in the shared column. The group after it gives up a cell in - /// fixed columns only, is judged again and still has no room, so the header is relieved and the - /// pass ends before the last group is judged. Were the first group's step remembered, the - /// second group would end its judging without being judged again, and the last group would - /// give up its 20 lines. - /// - [Fact] - public void ASharedStepDoesNotEndTheJudgingOfTheNextGroupAfterEightMeasurements() - { - using var doc = WidePage(); - var t = FillerTable(9, LineFeedHeader); - t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell(Words(3)); - t.AddRow().AddCell(Words(17, " ")); - TwentyLineGroup(t); - doc.Add(t); - - Save(doc); - - Assert.Equal(["row 0, cell 0", .. FillerReports(9), "row 19, cell 1"], Dropped(doc)); - } - - /// - /// A tab that tips a group, with one in the header too, is a shared step of the third step. - /// After eight measurements it ends only that group's judging: the group after it is judged in - /// the same pass, on the header as it stood (32pt, 548pt of room), and gives up its 44 lines. - /// Its 556pt fits the 560pt left once the tab in the header is laid out unbroken. - /// - [Fact] - public void ASharedThirdStepAfterEightMeasurementsLeavesTheNextGroupToTheSamePass() - { - using var doc = WidePage(); - var t = FillerTable(8, x => x.AddRow(isHeader: true).AddCell("ab\tab")); - t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("ab\tab"); - t.AddRow().AddCell(Words(43, " ")); - t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("b"); - t.AddRow().AddCell(Words(44)); - doc.Add(t); - - Save(doc); - - Assert.Equal(["row 0, cell 0", .. FillerReports(8), "row 17, cell 1", "row 20, cell 0"], Dropped(doc)); - } - /// /// The same holds when a tab tips the groups over the page, the third step: each group is a /// span cell, a tab cell that wraps one line taller as two words than as one, and 46 plain From 22268ccac1357f07e8a8e8f4e8f34251b46af1c3 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 08:01:40 +0100 Subject: [PATCH 20/48] perf(layout): keep the pass going when a step moves no column A group that gave up cells in an automatic column ended the pass, because the width of that column can change other rows. When the widths come out bit for bit as they were, and every cell given up lies in the group's own rows, no other row measures differently, so the pass goes on with the next group instead of starting again from the first. --- .../Rendering/Table/TableMeasureCache.cs | 6 ++ .../Rendering/Table/TableRenderer.cs | 67 +++++++++++++---- .../TableMeasureCacheTests.cs | 73 ++++++++++++++++++- 3 files changed, 132 insertions(+), 14 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs index c1f63a9ae..c3d0ff774 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs @@ -105,6 +105,12 @@ public static TableMeasureProbe? Current /// Cells whose longest word and widest line a resolution measured. public int WidthMisses { get; set; } + /// + /// Steps that gave up cells in a column other rows share and left every column width as it + /// was, so the pass went on. + /// + public int StepsKeptPassGoing { get; set; } + /// The number of times the decision measured the whole table. public int Passes { get; set; } } diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 67506d022..123036195 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -243,6 +243,14 @@ public LayoutResult Layout(LayoutContext context) _resumeLines = null; _resumeFrom = null; + // A decision made for this width and these boxes by the renderer that handed the table + // over stands: the cells it read unbroken are the cells this layout reads unbroken. + var key = fresh is { Length: 2 } + ? (area.Width, fresh[0].Y, fresh[0].Bottom, fresh[1].Y, fresh[1].Bottom) + : ((double, double, double, double, double)?)null; + var decided = key is not null && _decidedFor is { } was && was.Equals(key.Value); + if (!decided) _oneLine = null; + // Before the grid resolves: a ColSpan of zero gives a column count of zero, so Resolve // returns no widths and Layout gives up below, and the caller was told the table was too // tall to fit (#481). Checking here names the cell instead. @@ -255,14 +263,6 @@ public LayoutResult Layout(LayoutContext context) LayoutValidation.ValidateLineWidthIsFinite(_table.BorderWidth, "A table"); - // A decision made for this width and these boxes by the renderer that handed the table - // over stands: the cells it read unbroken are the cells this layout reads unbroken. - var key = fresh is { Length: 2 } - ? (area.Width, fresh[0].Y, fresh[0].Bottom, fresh[1].Y, fresh[1].Bottom) - : ((double, double, double, double, double)?)null; - var decided = key is not null && _decidedFor is { } was && was.Equals(key.Value); - if (!decided) _oneLine = null; - // A decision that reads some cells unbroken measures the table once per step, so it // keeps what each cell measures: nothing else depends on the cells' text, and the // cache is dropped with the decision. A table that reads no cell unbroken measures @@ -280,7 +280,7 @@ public LayoutResult Layout(LayoutContext context) // no second pass. if (passesNeeded) { - while (CellsToReadAsOneLine(fresh!, style) is { } more) + while (CellsToReadAsOneLine(fresh!, style, area.Width, cache!) is { } more) { _oneLine ??= []; _oneLine.UnionWith(more); @@ -609,7 +609,8 @@ private static bool AnyControlSpace(IReadOnlyList rows) /// two header steps takes every cell it reaches at once, so the header ends at most two /// passes. /// - private HashSet<(int Row, int Cell)>? CellsToReadAsOneLine(LayoutBox[] fresh, TextStyle style) + private HashSet<(int Row, int Cell)>? CellsToReadAsOneLine( + LayoutBox[] fresh, TextStyle style, double areaWidth, TableMeasureCache cache) { var rows = _table.Rows; var header = FindHeaderRowIndices(rows); @@ -627,9 +628,33 @@ private static bool AnyControlSpace(IReadOnlyList rows) var own = (First: -1, Last: -1); var shared = false; + // Whether a cell was added in a row outside the group, which changes that row's height + // whatever the columns do. + var outside = false; + + // True when the cells found so far, read unbroken, leave every column the width it has. + // Then no row outside the group measures differently, so a step that stayed in the group's + // rows does not end the pass: going on judges the next group on the heights a new pass + // would start from. The widths are compared bit for bit, because a width that moved by + // one unit in the last place can move a line break. + bool ColumnWidthsHold() + { + if (outside) return false; + var trial = new HashSet<(int Row, int Cell)>(_oneLine ?? []); + trial.UnionWith(found!); + var grid = new TableGridResolver { OneLineCells = trial, Cache = cache }; + grid.Resolve(_table, areaWidth); + if (grid.ColWidths.Length != _colWidths.Length) return false; + for (var i = 0; i < _colWidths.Length; i++) + if (BitConverter.DoubleToInt64Bits(grid.ColWidths[i]) != BitConverter.DoubleToInt64Bits(_colWidths[i])) + return false; + if (TableMeasureProbe.Current is { } probe) probe.StepsKeptPassGoing++; + return true; + } + void Note(int r, int col, int span) { - if (r < own.First || r > own.Last) { shared = true; return; } + if (r < own.First || r > own.Last) { shared = true; outside = true; return; } for (var k = 0; k < span && col + k < _colWidths.Length; k++) if (IsAutoColumn(col + k)) { shared = true; return; } } @@ -723,9 +748,10 @@ void Reach(int from, int to) // other group's height, so the next group is judged in the same pass. own = (first, last); shared = false; + outside = false; if (CollectBreaks(first, last)) { - if (shared) return found; + if (shared && !ColumnWidthsHold()) return found; // Only this group's rows are measured again, in the columns they have. (_oneLine ??= []).UnionWith(found!); @@ -735,7 +761,22 @@ void Reach(int from, int to) own = (-1, -1); if (header.Count > 0 && CollectBreaks(0, header[^1])) return found; own = (first, last); - if (CollectControlSpace(first, last) && shared) return found; + shared = false; + outside = false; + if (CollectControlSpace(first, last) && shared) + { + // The last step takes every cell it can reach, so the group is not judged + // again after it; the cells are applied here when the pass goes on. + if (ColumnWidthsHold()) + { + (_oneLine ??= []).UnionWith(found!); + for (var r = first; r <= last; r++) _rowHeights[r] = MeasureRow(r, style); + } + else + { + return found; + } + } break; } } diff --git a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs index 4e84ba1cf..25fc8bb8e 100644 --- a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs @@ -89,7 +89,6 @@ public void ACellIsMeasuredForItsColumnWidthOncePerMode() var probe = Probed(() => Save(doc)); Assert.Equal(Enumerable.Range(0, groups).Select(i => $"row {2 * i}, cell 2").ToArray(), Dropped(doc)); - Assert.True(probe.Passes > groups, $"{probe.Passes} resolutions"); const int cells = 4 * groups; Assert.Equal(cells + groups, probe.WidthMisses); Assert.True(probe.WidthHits > probe.WidthMisses, $"{probe.WidthHits} hits, {probe.WidthMisses} misses"); @@ -216,4 +215,76 @@ public void TheModeOfACellIsPartOfItsEntry() Assert.Equal(["row 0, cell 0"], Dropped(doc)); } + + /// + /// A group that gives up its breaks in an automatic column does not end the pass when no + /// column changes width: the unbroken text of its cell is narrower than a word of another row + /// in the same column, so the table is measured once for all six groups, not once for each. + /// + [Fact] + public void AStepThatLeavesEveryColumnWidthAsItWasDoesNotEndThePass() + { + const int groups = 6; + using var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }; + t.AddRow().AddCell("x").AddCell(new string('W', 100)).AddCell("x"); + for (var i = 0; i < groups; i++) + { + t.AddRow().AddCell("x").AddCell(new Cell(Words(60)) { RowSpan = 2 }).AddCell("x"); + t.AddRow().AddCell("y").AddCell("y"); + } + doc.Add(t); + + var probe = Probed(() => Save(doc)); + + Assert.Equal(Enumerable.Range(0, groups).Select(i => $"row {2 * i + 1}, cell 1").ToArray(), Dropped(doc)); + Assert.Equal(groups, probe.StepsKeptPassGoing); + Assert.True(probe.Passes <= 3, $"{probe.Passes} resolutions"); + } + + /// + /// A step that moves a column's width still ends the pass: the next group is judged on the + /// widths it leaves. Each group's cell is longer than the one before it, so each step widens + /// the automatic column, no step keeps a pass going, and the table is resolved once for each + /// group and once more. + /// + [Fact] + public void AStepThatMovesAColumnWidthStillEndsThePass() + { + const int groups = 4; + using var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }; + for (var i = 0; i < groups; i++) + { + t.AddRow().AddCell("x").AddCell(new Cell(Words(60 + (20 * i))) { RowSpan = 2 }); + t.AddRow().AddCell("y"); + } + doc.Add(t); + + var probe = Probed(() => Save(doc)); + + Assert.Equal(groups, Dropped(doc).Length); + Assert.Equal(0, probe.StepsKeptPassGoing); + Assert.True(probe.Passes > groups, $"{probe.Passes} resolutions"); + } + + /// + /// A step in a row outside the group does not keep the pass going even when no column moves, + /// because that row is measured again: a tab in the header, which the group's third step + /// takes, changes the header's height. + /// + [Fact] + public void AStepInAHeaderRowStillEndsThePass() + { + using var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }; + t.AddRow(isHeader: true).AddCell(new string('W', 100)).AddCell("a" + (char)9 + "b"); + t.AddRow().AddCell(new Cell("a") { RowSpan = 2 }).AddCell("b" + (char)9 + "b"); + t.AddRow().AddCell(Words(47, " ")); + doc.Add(t); + + var probe = Probed(() => Save(doc)); + + Assert.Equal(0, probe.StepsKeptPassGoing); + } } From 644ac2af956cadc1fd1f6ae42a3f6b4cedf6f04c Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 08:04:25 +0100 Subject: [PATCH 21/48] perf(layout): resolve a table's grid once for all its pages Every page of a table resolved the grid again, though the renderer that carries the table over holds the grid, the heights and the decision for the same width and fresh page. The checks of the cells and the border width ran on the page that made the decision, so a later page keeps them as they were. --- .../Rendering/Table/TableMeasureCache.cs | 6 ++ .../Rendering/Table/TableRenderer.cs | 69 ++++++++++-------- .../TableMeasureCacheTests.cs | 71 +++++++++++++++++++ 3 files changed, 117 insertions(+), 29 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs index c3d0ff774..6eff9c83f 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs @@ -111,6 +111,12 @@ public static TableMeasureProbe? Current /// public int StepsKeptPassGoing { get; set; } + /// + /// Layouts that kept the grid and heights of the decision they were handed, and resolved + /// nothing. + /// + public int GridsReused { get; set; } + /// The number of times the decision measured the whole table. public int Passes { get; set; } } diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 123036195..7e869ce3d 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -251,44 +251,55 @@ public LayoutResult Layout(LayoutContext context) var decided = key is not null && _decidedFor is { } was && was.Equals(key.Value); if (!decided) _oneLine = null; - // Before the grid resolves: a ColSpan of zero gives a column count of zero, so Resolve - // returns no widths and Layout gives up below, and the caller was told the table was too - // tall to fit (#481). Checking here names the cell instead. - for (var r = 0; r < _table.Rows.Count; r++) + // The grid and the heights that decision was made with stand too: they follow from the + // table, the width and the cells read unbroken, which are all the same. The renderer + // that made the decision resolved the grid and ran every check below on it, so a + // renderer that carries it to a later page checks and resolves nothing again. + if (decided && _colWidths.Length > 0 && _rowHeights.Length == rows.Count) { - var cells = _table.Rows[r].Cells; - for (var c = 0; c < cells.Count; c++) - LayoutValidation.ValidateCell(cells[c], r, c); + if (TableMeasureProbe.Current is { } held) held.GridsReused++; } + else + { + // Before the grid resolves: a ColSpan of zero gives a column count of zero, so + // Resolve returns no widths and Layout gives up below, and the caller was told the + // table was too tall to fit (#481). Checking here names the cell instead. + for (var r = 0; r < _table.Rows.Count; r++) + { + var cells = _table.Rows[r].Cells; + for (var c = 0; c < cells.Count; c++) + LayoutValidation.ValidateCell(cells[c], r, c); + } - LayoutValidation.ValidateLineWidthIsFinite(_table.BorderWidth, "A table"); + LayoutValidation.ValidateLineWidthIsFinite(_table.BorderWidth, "A table"); - // A decision that reads some cells unbroken measures the table once per step, so it - // keeps what each cell measures: nothing else depends on the cells' text, and the - // cache is dropped with the decision. A table that reads no cell unbroken measures - // once. - var passesNeeded = !decided && fresh is not null && AnyControlSpace(rows); - var cache = passesNeeded ? new TableMeasureCache(rows.Count) : null; + // A decision that reads some cells unbroken measures the table once per step, so + // it keeps what each cell measures: nothing else depends on the cells' text, and + // the cache is dropped with the decision. A table that reads no cell unbroken + // measures once. + var passesNeeded = !decided && fresh is not null && AnyControlSpace(rows); + var cache = passesNeeded ? new TableMeasureCache(rows.Count) : null; - ResolveGrid(area.Width, style, cache); + ResolveGrid(area.Width, style, cache); - // Rows that cannot be cut between their lines must not be left without room on a page - // by reading a cell's line breaks, or its other control white space as spaces; - // Cell.Content says when, and which cells give them up. The cells that would leave - // them so are laid out unbroken, and the grid and the heights are taken again. Each - // pass adds cells, so this ends; most tables, which hold no control white space, take - // no second pass. - if (passesNeeded) - { - while (CellsToReadAsOneLine(fresh!, style, area.Width, cache!) is { } more) + // Rows that cannot be cut between their lines must not be left without room on a + // page by reading a cell's line breaks, or its other control white space as + // spaces; Cell.Content says when, and which cells give them up. The cells that + // would leave them so are laid out unbroken, and the grid and the heights are + // taken again. Each pass adds cells, so this ends; most tables, which hold no + // control white space, take no second pass. + if (passesNeeded) { - _oneLine ??= []; - _oneLine.UnionWith(more); - ResolveGrid(area.Width, style, cache); + while (CellsToReadAsOneLine(fresh!, style, area.Width, cache!) is { } more) + { + _oneLine ??= []; + _oneLine.UnionWith(more); + ResolveGrid(area.Width, style, cache); + } } + _measured = null; + _decidedFor = key; } - _measured = null; - _decidedFor = key; } // The repeatable header is the leading contiguous run of IsHeader rows — see diff --git a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs index 25fc8bb8e..aa7931ac7 100644 --- a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs @@ -287,4 +287,75 @@ public void AStepInAHeaderRowStillEndsThePass() Assert.Equal(0, probe.StepsKeptPassGoing); } + + /// + /// A table that runs over many pages resolves its grid once: the renderer that carries it to + /// the next page, laid out at the same width and fresh page, keeps the grid and the heights. + /// + [Fact] + public void ATableOverManyPagesResolvesItsGridOnce() + { + using var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(500, 500); + for (var i = 0; i < 400; i++) t.AddRow().AddCell("row " + i).AddCell("x"); + doc.Add(t); + + var probe = Probed(() => Save(doc)); + + Assert.Equal(1, probe.Passes); + Assert.True(probe.GridsReused >= 5, $"{probe.GridsReused} layouts kept the grid"); + } + + /// + /// A page of another width resolves the grid again: the cached one was made for the width the + /// first page had. + /// + [Fact] + public void ALaterPageOfAnotherWidthResolvesTheGridAgain() + { + var t = new TableElement { DefaultCellStyle = Helvetica() }; + for (var i = 0; i < 100; i++) t.AddRow().AddCell("row " + i).AddCell(Words(3, " ")); + var tall = new LayoutBox(10, 10, 1980, 600); + var narrow = new LayoutBox(10, 10, 300, 600); + + var probe = new TableMeasureProbe(); + TableMeasureProbe.Current = probe; + try + { + var first = new TableRenderer(t).Layout(new LayoutContext(new LayoutBox(10, 10, 1980, 100)) { FreshPageArea = tall }); + var same = first.OverflowRenderer!.Layout(new LayoutContext(new LayoutBox(10, 10, 1980, 100)) { FreshPageArea = tall }); + Assert.Equal(1, probe.GridsReused); + Assert.NotNull(same.OverflowRenderer); + + same.OverflowRenderer!.Layout(new LayoutContext(narrow) { FreshPageArea = narrow }); + } + finally { TableMeasureProbe.Current = null; } + + Assert.Equal(1, probe.GridsReused); + Assert.Equal(2, probe.Passes); + } + + /// + /// A cell that is refused is refused when the table is first laid out, whichever page it is + /// on, so keeping the grid for the later pages hides no refusal: the save throws from the + /// first page, naming the cell, as it does when nothing is kept. + /// + [Theory] + [InlineData("fontSize")] + [InlineData("colSpan")] + public void ACellOnALaterPageIsRefusedFromTheFirstPage(string fault) + { + using var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(500, 500); + for (var i = 0; i < 200; i++) t.AddRow().AddCell("row " + i).AddCell("x"); + var last = t.AddRow().AddCell("last"); + last.AddCell(fault == "fontSize" + ? new Cell("bad") { Style = Helvetica(double.NaN) } + : new Cell("bad") { ColSpan = 0 }); + doc.Add(t); + + var ex = Assert.Throws(() => Save(doc)); + + Assert.Contains("row 200, cell 1", ex.Message); + } } From 0ac4144d2559d3c9d8b4a6018e77ff580f14ac67 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 08:12:45 +0100 Subject: [PATCH 22/48] test(layout): pin the cost of the table decision on three shapes Allocations are counted, not time, so a loaded machine does not move the pins. The shapes are groups that give up a cell in a column other rows share, groups that each widen that column, and a chain in which each group changes the width the next is judged by. --- .../TableMeasureCacheTests.cs | 152 ++++++++++++++++++ 1 file changed, 152 insertions(+) diff --git a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs index aa7931ac7..7c4a8bc7b 100644 --- a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs @@ -358,4 +358,156 @@ public void ACellOnALaterPageIsRefusedFromTheFirstPage(string fault) Assert.Contains("row 200, cell 1", ex.Message); } + + private static (long Bytes, int Reported) Allocated(Func build) + { + using var doc = build(); + var before = GC.GetAllocatedBytesForCurrentThread(); + Save(doc); + var bytes = GC.GetAllocatedBytesForCurrentThread() - before; + return (bytes, doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped).Sum(d => d.Count)); + } + + /// + /// Fillers in an automatic column: each group is a cell of 60 lines in the column other rows + /// share, beside two short cells in 36pt columns. The allocations of 400 of them stay under + /// a fixed multiple of those of the same table with the lines separated by spaces, which has + /// nothing to give up. Allocations are counted, not time, because the same run on a loaded + /// machine takes several times as long. + /// + [Fact] + public void TheCostOfGivingUpBreaksInASharedAutoColumnDoesNotGrowWithEachGroup() + { + static Document Build(int groups, string separator) + { + var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(36, 36, 0); + for (var i = 0; i < groups; i++) + { + t.AddRow().AddCell("x").AddCell("x").AddCell(new Cell(Words(60, separator)) { RowSpan = 2 }); + t.AddRow().AddCell("y"); + } + doc.Add(t); + return doc; + } + + Allocated(() => Build(10, "\n")); + Allocated(() => Build(10, " ")); + var withBreaks = Allocated(() => Build(400, "\n")); + var withSpaces = Allocated(() => Build(400, " ")); + + Assert.Equal(400, withBreaks.Reported); + Assert.Equal(0, withSpaces.Reported); + Assert.True(withBreaks.Bytes < 4.0 * withSpaces.Bytes, $"{withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); + } + + /// + /// Groups that each widen the automatic column, and so change what the next group is judged + /// by: the cell of group i has 48 + i lines. Every step moves a column width, so none keeps + /// the pass going and every group is judged on the widths the one before it leaves. The + /// allocations of 300 of them stay under 35 times those of the same table with the lines + /// separated by spaces, which has nothing to give up. + /// + [Fact] + public void TheCostOfGroupsThatEachWidenTheColumnStaysUnderAFixedMultiple() + { + static Document Build(int groups, bool breaks) + { + var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(0, 0, 0); + for (var i = 0; i < groups; i++) + { + t.AddRow().AddCell("x").AddCell(new Cell(Words(48 + i, breaks ? "\n" : " ")) { RowSpan = 2 }) + .AddCell("lorem ipsum dolor sit amet " + i); + t.AddRow().AddCell("y"); + } + doc.Add(t); + return doc; + } + + Allocated(() => Build(10, true)); + Allocated(() => Build(10, false)); + var withBreaks = Allocated(() => Build(300, true)); + var withSpaces = Allocated(() => Build(300, false)); + + Assert.Equal(300, withBreaks.Reported); + Assert.Equal(0, withSpaces.Reported); + Assert.True(withBreaks.Bytes < 35.0 * withSpaces.Bytes, $"{withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); + } + + /// + /// A chain of groups in which each one's cell is a little wider than the one before it, beside + /// a fixed column and an automatic one, and each has a wrapping cell under it sized to the + /// width the automatic column takes once the group before gave up its breaks. Every group is + /// reported, and the allocations of 60 of them stay under 30MB. + /// + [Fact] + public void TheCostOfAChainOfTippedGroupsStaysUnderAFixedBound() + { + const int groups = 60; + using var doc = WidePage(); + doc.Add(CascadeTable(groups)); + var before = GC.GetAllocatedBytesForCurrentThread(); + Save(doc); + var bytes = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.Equal(groups, Dropped(doc).Length); + Assert.True(bytes < 30_000_000L, $"{bytes} bytes"); + } + + private static TableElement CascadeTable(int n) + { + var font = new FontReference(Standard14.Helvetica); + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(1980, 0); + var hp = new Cell("x").Padding.Horizontal; + + string Text(int k) + { + var lines = k == 1 ? 60 : 38; + var chars = 100 + k; + var sb = new System.Text.StringBuilder(); + for (var l = 0; l < lines; l++) + { + if (l > 0) sb.Append('\n'); + sb.Append('i', (chars / lines) + (l < chars % lines ? 1 : 0)); + } + return sb.ToString(); + } + + var a = Enumerable.Range(1, n).Select(Text).ToArray(); + var longestLine = a.Max(x => x.Split('\n').Max(l => font.MeasureString(l, 10))); + double Inner(double floorA) => 1980 - (floorA + hp) - hp; + var inner = new double[n + 1]; + inner[0] = Inner(longestLine); + for (var j = 1; j <= n; j++) inner[j] = Inner(font.MeasureString(a[j - 1], 10)); + var iw = font.MeasureString("i", 10); + var sp = font.MeasureString(" ", 10); + for (var k = 1; k <= n; k++) + { + string b; + if (k == 1) + { + b = "r"; + } + else + { + var target = (inner[k - 2] + inner[k - 1]) / 2; + string? best = null; + var bestErr = double.MaxValue; + for (var y = 0; y < 6; y++) + { + var fw = font.MeasureString(new string('f', y), 10); + var x = (int)Math.Round((((target - sp) / 2) - fw) / iw); + if (x < 0) continue; + var w = new string('i', x) + new string('f', y); + var err = Math.Abs(font.MeasureString(w + " " + w, 10) - target); + if (err < bestErr) { bestErr = err; best = w; } + } + b = string.Join(" ", Enumerable.Repeat(best!, 14)); + } + t.AddRow().AddCell("r").AddCell(new Cell(a[k - 1]) { RowSpan = 2 }); + t.AddRow().AddCell(b); + } + return t; + } } From 72330b7905f09a0923db75a725573fd453953292 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 08:17:18 +0100 Subject: [PATCH 23/48] docs(layout): say that every table group is judged in order The pass limit and its cost paragraph are gone from the changelog and the XML documentation, which now state the rule once on Cell.Content. A test pins the interval of a cached line count as closed below and open above. --- CHANGELOG.md | 9 ++++++ .../Rendering/Table/TableMeasureCache.cs | 4 +-- .../Rendering/Table/TableRenderer.cs | 17 ++++++---- .../TableMeasureCacheTests.cs | 32 ++++++++++++++++--- 4 files changed, 49 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee0828a8d..9cc15d1a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -662,6 +662,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). one of 47 is 572pt, fits the page alone, but leaves the row 8pt, so it falls back. The XML documentation of `Cell.Content` states when a header or a group has no room, which cells fall back and in what order, and what a renderer laid out without the document does. + - **Every group is judged in order, and the decision measures each cell once.** A table that + gives up cells in several groups measures its cells' widths once per mode and its line counts + once per interval of column widths, keeps the pass going when a group's step leaves every + column width as it was, and resolves its grid once for all its pages. No limit on the number + of measurements applies, so a group is judged on the heights the groups before it leave + whatever their number. Measured in Release on net10.0, one run each: 400 groups that each + change the width the next is judged by took 0.95s and 170MB, where main took 4.55s and + 3,022MB; 1,000 groups that each widen an automatic column took 8.6s and 13,376MB, where main + took 29.8s and 48,492MB. - **`/FontBBox` of an embedded font is the font's own bounding box (#596).** The descriptor of every embedded TrueType and OpenType font held `[0, hhea descender, 1000 * 1000 / unitsPerEm, hhea ascender]`: a zero for xMin and a constant for xMax, so DejaVu Sans, Liberation Sans and Liberation diff --git a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs index 6eff9c83f..ec44d376c 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs @@ -6,8 +6,8 @@ namespace VellumPdf.Layout.Rendering.Table; /// /// What one table decision has measured of its cells, so that measuring the table again does not /// measure every cell again. The decision that reads some cells unbroken measures the whole table -/// once per step; most steps change no cell's text, mode or width, and a cell's measurements -/// depend on nothing else. +/// once per step, while a cell's longest word and widest line depend on its text and mode alone, +/// and its line count on those and the width it wraps at. /// /// /// The cache holds, per cell and per mode (breaks kept or read unbroken), the cell's longest diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 7e869ce3d..083c42d2c 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -67,9 +67,9 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IP // What _oneLine was decided for: the table width and the vertical extent of the two fresh // boxes. - // A renderer that carries the decision to the next page reuses it when it lays out at the same - // width and heights, and so resolves the grid once, where deciding again would resolve it once - // per pass on every page. The boxes' x is left out of the key: the decision never reads it, and + // A renderer that carries the decision to the next page reuses it, with the grid and the + // heights it was made with, when it lays out at the same width and heights; Layout says what + // that leaves out. The boxes' x is left out of the key: the decision never reads it, and // mirrored margins move it on every other page. private (double Width, double Top0, double Bottom0, double Top1, double Bottom1)? _decidedFor; @@ -616,9 +616,11 @@ private static bool AnyControlSpace(IReadOnlyList rows) /// method judges the header rows first and then each group in /// order, and a group again after its own breaks are given up in fixed-width columns. A step /// that adds a cell in a header row, or in an automatically sized column, ends the pass, - /// because every height has to be taken again before the next group is judged. Each of the - /// two header steps takes every cell it reaches at once, so the header ends at most two - /// passes. + /// because every height has to be taken again before the next group is judged. The one + /// exception is a step whose cells all lie in the group's own rows and leave every column + /// width as it was, bit for bit: no other row measures differently then, so the group's rows + /// are measured again and the next group is judged in the same pass. Each of the two header + /// steps takes every cell it reaches at once, so the header ends at most two passes. /// private HashSet<(int Row, int Cell)>? CellsToReadAsOneLine( LayoutBox[] fresh, TextStyle style, double areaWidth, TableMeasureCache cache) @@ -754,7 +756,8 @@ void Reach(int from, int to) // A step that adds a cell the other groups' heights can depend on ends the pass, // because the next group would be judged by heights that the step changes, a - // column's width among them. The header steps below end it too. + // column's width among them, unless the widths come out as they were and the step + // stays in this group's rows (ColumnWidthsHold). The header steps below end it too. // A step that stays in this group's rows and in fixed-width columns changes no // other group's height, so the next group is judged in the same pass. own = (first, last); diff --git a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs index 7c4a8bc7b..daf031bf2 100644 --- a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs @@ -166,6 +166,31 @@ public void ACertificateHoldsOverARangeUnlessAWordWasBroken() Assert.Equal(20.0, from); } + /// + /// The interval a count holds over is closed at its low end and open at its high end: the + /// width the count was found at and the lowest width of the interval hold it, the width the + /// comparisons first flip at does not, and neither does the one just under the low end. + /// + [Fact] + public void AnIntervalIsClosedBelowAndOpenAbove() + { + var style = Helvetica(); + var text = "ab ab ab ab"; + var lines = TableRenderer.CountLines(text, style, 36, true, out var from, out var below, out var pinned); + Assert.False(pinned); + Assert.True(double.IsFinite(from) && double.IsFinite(below), $"[{from}, {below})"); + var entry = new CellMeasure { HasLines = true, Lines = lines, From = from, Below = below }; + + Assert.True(entry.Holds(36)); + Assert.True(entry.Holds(from)); + Assert.True(entry.Holds(Math.BitDecrement(below))); + Assert.False(entry.Holds(below)); + Assert.False(entry.Holds(Math.BitDecrement(from))); + Assert.False(new CellMeasure().Holds(36)); + Assert.False(new CellMeasure { HasLines = true, Pinned = true, Lines = 3, From = 20 }.Holds(Math.BitIncrement(20))); + Assert.True(new CellMeasure { HasLines = true, Pinned = true, Lines = 3, From = 20 }.Holds(20)); + } + /// /// The line counts the caches answer are the counts of a fresh wrap: the probe measures again /// on every hit and throws on a difference. Widths that shrink as groups give up their breaks @@ -436,10 +461,9 @@ static Document Build(int groups, bool breaks) } /// - /// A chain of groups in which each one's cell is a little wider than the one before it, beside - /// a fixed column and an automatic one, and each has a wrapping cell under it sized to the - /// width the automatic column takes once the group before gave up its breaks. Every group is - /// reported, and the allocations of 60 of them stay under 30MB. + /// A chain of 60 groups, each with a cell a little wider than the one before it beside a fixed + /// column and an automatic one, and a wrapping cell under it. Every group is reported, and the + /// save allocates under 30MB. /// [Fact] public void TheCostOfAChainOfTippedGroupsStaysUnderAFixedBound() From 8b6d2d3f7d721ccde51aab260655be7290c5c195 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 09:57:37 +0100 Subject: [PATCH 24/48] fix(layout): relieve a group that a cell outside it narrowed A table the previous release saved was refused when an automatic column's cell, in a row of no group, held a line break: reading it per line took the column's minimum from its widest line, the explicit columns were scaled down to what that left, and the group's own cells held no control white space for any step to give up. When a header or a group still has no room after the three steps, a last step reads every control-white-space cell that spans an automatic column unbroken. Those cells alone decide every column's width, so the widths, and the header and group heights, come out as when every cell was one line. A test hook measures a table that way, for the property test. --- CHANGELOG.md | 8 +- src/VellumPdf.Layout/Elements/Table/Cell.cs | 12 +- .../Elements/Table/TableElement.cs | 6 +- .../Rendering/Table/TableMeasureCache.cs | 6 + .../Rendering/Table/TableRenderer.cs | 74 +++++- .../TableLastStepTests.cs | 248 ++++++++++++++++++ .../TableRandomDocuments.cs | 156 +++++++++++ 7 files changed, 498 insertions(+), 12 deletions(-) create mode 100644 tests/VellumPdf.Layout.Tests/TableLastStepTests.cs create mode 100644 tests/VellumPdf.Layout.Tests/TableRandomDocuments.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cc15d1a1..67e3c5b10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -661,7 +661,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). tall, keeps its lines on a 580pt page above a 20pt row, where a line fits in the 20pt left; one of 47 is 572pt, fits the page alone, but leaves the row 8pt, so it falls back. The XML documentation of `Cell.Content` states when a header or a group has no room, which cells - fall back and in what order, and what a renderer laid out without the document does. + fall back and in what order, and what a renderer laid out without the document does. A header + or a group that still has no room once those cells have given up their breaks makes every + cell in an automatic column that holds control white space give up its breaks as well, because + the width of every column follows from those cells. With those cells unbroken the columns are + as wide as 2.3.3 made them, and the header and the groups as tall. In a table with two 100pt + columns and an automatic one, a group of two rows is 424pt tall on a page that leaves 280pt + while a cell of the automatic column in a third row keeps its line break, and 100pt without it. - **Every group is judged in order, and the decision measures each cell once.** A table that gives up cells in several groups measures its cells' widths once per mode and its line counts once per interval of column widths, keeps the pass going when a group's step leaves every diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 1747d0ee2..20e5494d2 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -66,8 +66,16 @@ public sealed class Cell /// those rows is in. The header rows are relieved in the same way: by their own cells that /// hold a carriage return or a line feed, and then by every cell that holds any control white /// space and sits in them or in an automatically sized column that a cell of them is in. A - /// cell that holds only a line feed can be reached by any step. A cell no step reaches keeps - /// its breaks. + /// cell that holds only a line feed can be reached by any step. + /// When those steps leave a header or a group with no room, a fourth step lays out + /// unbroken every cell that holds control white space and spans a column that is sized + /// automatically, wherever its row is. The width of every column follows from the + /// cells of the automatic columns, whichever rows they are in, so a cell in a column that no + /// cell of the group is in can still have narrowed the group's columns by the width its + /// breaks leave. With all of those cells unbroken every column is as wide as when the table + /// measured each cell as one line, and the header rows and the groups are as tall as that + /// measured them, so one of them is refused only if it was too tall measured so. A cell no + /// step reaches keeps its breaks. /// A header row, or a group in an automatically sized column, that gives up a cell can /// change other rows: the column's width is shared with every row that has a cell in it. The /// groups after it are judged on the heights that result, so every group is judged on the diff --git a/src/VellumPdf.Layout/Elements/Table/TableElement.cs b/src/VellumPdf.Layout/Elements/Table/TableElement.cs index 7048d0d25..2a8819715 100644 --- a/src/VellumPdf.Layout/Elements/Table/TableElement.cs +++ b/src/VellumPdf.Layout/Elements/Table/TableElement.cs @@ -32,9 +32,9 @@ namespace VellumPdf.Layout.Elements.Table; /// empty TD, also in a header row. /// A carriage return or line feed in a cell ends a line, so it makes the row taller. A /// repeated header row, or rows joined by a , can lose the breaks and -/// tabs of some cells, and the save lists each as -/// ; says when -/// and which. +/// tabs of some cells, those of a cell in an automatically sized column among them, and the save +/// lists each as ; +/// says when and which. /// Every group is judged on the heights the groups before it leave. A header row, or /// a group in an automatically sized column, that gives up a cell can change the width of a /// column the next group is judged by, so the next group is judged on the widths that result, diff --git a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs index ec44d376c..3af0ca309 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs @@ -93,6 +93,12 @@ public static TableMeasureProbe? Current /// public bool Verify { get; init; } + /// + /// When set, a table that holds control white space is measured with every cell as one line + /// and no decision, as it was measured before breaks were honoured. + /// + public bool ReadEveryCellUnbroken { get; init; } + /// Cells whose line count a measurement took from the cache. public int WrapHits { get; set; } diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 083c42d2c..6005b537d 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -174,8 +174,8 @@ void IPlacementSource.ReportPlacements(PlacementSink sink) /// the saved lines are dropped and the row is laid out again from its first line, which /// under a context without the box is not cut. /// A carriage return or line feed in a cell ends a line. A repeated header row, or rows - /// joined by a , can lose the breaks of some cells, and the save - /// reports each as ; + /// joined by a , can lose the breaks of some cells, those of a cell + /// in an automatically sized column among them, and the save reports each as ; /// says when and which. A context built with the public /// constructor of keeps every break. /// These are refused with the too-tall exception, extended with a sentence naming the @@ -278,6 +278,18 @@ public LayoutResult Layout(LayoutContext context) // the cache is dropped with the decision. A table that reads no cell unbroken // measures once. var passesNeeded = !decided && fresh is not null && AnyControlSpace(rows); + + // A test measures the table as it was before breaks were honoured: every cell as + // one line, with nothing to decide. + if (passesNeeded && TableMeasureProbe.Current is { ReadEveryCellUnbroken: true }) + { + _oneLine = []; + for (var r = 0; r < rows.Count; r++) + for (var c = 0; c < rows[r].Cells.Count; c++) + _oneLine.Add((r, c)); + passesNeeded = false; + } + var cache = passesNeeded ? new TableMeasureCache(rows.Count) : null; ResolveGrid(area.Width, style, cache); @@ -620,7 +632,9 @@ private static bool AnyControlSpace(IReadOnlyList rows) /// exception is a step whose cells all lie in the group's own rows and leave every column /// width as it was, bit for bit: no other row measures differently then, so the group's rows /// are measured again and the next group is judged in the same pass. Each of the two header - /// steps takes every cell it reaches at once, so the header ends at most two passes. + /// steps takes every cell it reaches at once, so the header ends at most two passes. When a + /// pass finds nothing to change and a header or a group still has no room, the last step takes + /// every cell in an automatically sized column that holds control white space. /// private HashSet<(int Row, int Cell)>? CellsToReadAsOneLine( LayoutBox[] fresh, TextStyle style, double areaWidth, TableMeasureCache cache) @@ -737,11 +751,17 @@ void Reach(int from, int to) return added; } + // True when a header or a group has no room and the steps above could take nothing more + // from it. It is read only when the pass finds nothing else to change. + var exhausted = false; + // The header rows have no room when they do not fit a page, and when they leave a row below // them no room for one line of one of its cells. - if (header.Count > 0 && (!FitsFresh(fresh, 0, headerHeight) || LeavesNoRoomForALine(fresh, headerHeight, lastHeaderRow, style)) - && (CollectBreaks(0, header[^1]) || CollectControlSpace(0, header[^1]))) - return found; + if (header.Count > 0 && (!FitsFresh(fresh, 0, headerHeight) || LeavesNoRoomForALine(fresh, headerHeight, lastHeaderRow, style))) + { + if (CollectBreaks(0, header[^1]) || CollectControlSpace(0, header[^1])) return found; + exhausted = true; + } foreach (var (first, last) in SpanGroups(lastHeaderRow)) { @@ -791,13 +811,55 @@ void Reach(int from, int to) return found; } } + exhausted = true; break; } } + // The widths of the columns that are not fixed follow from every cell in an automatically + // sized column, whichever row it is in, and the columns that are fixed are scaled by what + // those leave. When a header or a group still has no room, a cell in a row of no group + // that is reached can be what made the columns too narrow: the widest line of it is + // narrower than its whole text, so reading its breaks leaves less to share out than 2.3.3 + // measured. The last step reads every such cell unbroken (see Cell.Content), which gives + // the widths, and so the heights, 2.3.3 measured for the header and the groups. + return found ?? (exhausted ? CollectAutoColumnControlSpace() : null); + } + + /// + /// Every cell that holds control white space and has a column that is sized automatically + /// among those it spans, and is not laid out unbroken yet, or null when there is none. The + /// widths of the columns come out of the cells of these columns alone, so with these cells + /// unbroken, and those of the rows that have no room, every column is as wide as it was when + /// every cell was measured as one line. + /// + private HashSet<(int Row, int Cell)>? CollectAutoColumnControlSpace() + { + var rows = _table.Rows; + HashSet<(int Row, int Cell)>? found = null; + for (var r = 0; r < rows.Count; r++) + { + var cells = rows[r].Cells; + var col = 0; + for (var c = 0; c < cells.Count && col < _colWidths.Length; c++) + { + var span = cells[c].ColSpan; + if (HonoursBreaks(r, c) && LayoutText.HasControlSpace(cells[c].Content) && TouchesAutoColumn(col, span)) + (found ??= []).Add((r, c)); + col += span; + } + } return found; } + /// True when a column that a cell at for columns is in is sized automatically. + private bool TouchesAutoColumn(int col, int span) + { + for (var k = 0; k < span && col + k < _colWidths.Length; k++) + if (IsAutoColumn(col + k)) return true; + return false; + } + /// /// True when a column of that a cell at for /// columns is in is automatically sized and is one that a relieved row diff --git a/tests/VellumPdf.Layout.Tests/TableLastStepTests.cs b/tests/VellumPdf.Layout.Tests/TableLastStepTests.cs new file mode 100644 index 000000000..d19a29c03 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableLastStepTests.cs @@ -0,0 +1,248 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements.Table; +using VellumPdf.Layout.Rendering.Table; +using VellumPdf.TestSupport; + +namespace VellumPdf.Layout.Tests; + +/// +/// The last step of the decision that reads some table cells unbroken: a header or a group that +/// still has no room takes every control-white-space cell in an automatically sized column, so a +/// table that fits when every cell is measured as one line is not refused for what the breaks do +/// to the widths. The fixtures are 400x300pt with 10pt margins in Helvetica 10pt, where a line is +/// 12pt and a "W" is 9.44pt wide. +/// +public sealed class TableLastStepTests +{ + private const string Lorem = "lorem ipsum dolor sit amet consectetur"; + + private static readonly string s_twoLines = W(37) + "\n" + W(4); + + private static TextStyle Helvetica(double size = 10) => new() + { + FontRef = new FontReference(Standard14.Helvetica), + FontSize = size, + }; + + private static Document SmallPage() => new() + { + PageSize = new PdfRectangle(0, 0, 400, 300), + Margins = new EdgeInsets(10), + }; + + private static string W(int n) => new('W', n); + + private static byte[] Save(Document doc) + { + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + private static int PageCount(byte[] pdf) => + Regex.Matches(Encoding.Latin1.GetString(pdf), @"/Type\s*/Page\b").Count; + + private static string[] Dropped(Document doc) => + [.. doc.Diagnostics + .Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped) + .Select(d => Regex.Match(d.Message, @"row \d+, cell \d+").Value) + .OrderBy(m => int.Parse(Regex.Match(m, @"\d+").Value, CultureInfo.InvariantCulture)) + .ThenBy(m => m, StringComparer.Ordinal)]; + + private static void RequireDejaVu() + { + if (!File.Exists(TableRandomDocuments.DejaVu)) + OracleGate.Unavailable("DejaVuSans.ttf", "DejaVu Sans is needed for an embedded font."); + } + + /// + /// Two fixed columns of 100pt and an automatic one. Rows 0 and 1 are the group, or the header + /// and a row, and the cell of row 0 in the first column is tall in 100pt. Row 2's cell in the + /// automatic column holds the given text, in a column that no cell of the group is in. + /// + private static TableElement Table(bool header, string third, string[]? extraRow = null) + { + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(100, 100); + var first = t.AddRow(header); + first.AddCell(header ? new Cell(Lorem) : new Cell(Lorem) { RowSpan = 2 }); + first.AddCell("a"); + t.AddRow().AddCell("b"); + t.AddRow().AddCell("c").AddCell("d").AddCell(third); + if (extraRow is not null) + { + var row = t.AddRow(); + foreach (var cell in extraRow) row.AddCell(cell); + } + return t; + } + + /// + /// The group of rows 0 and 1 is 424pt tall when the line feed is a break, and a page leaves + /// 280pt. The cell that does that is in row 2, and the group's own cells hold no control white + /// space, so only the last step reaches it. Measured as one line the automatic column is 253pt + /// wide, the fixed ones are scaled to 63.4pt each and the group is 100pt tall. + /// + [Fact] + public void AGroupThatACellOutsideItNarrowedIsRelievedByThatCell() + { + using var doc = SmallPage(); + doc.Add(Table(header: false, s_twoLines)); + + var bytes = Save(doc); + + Assert.Equal(["row 2, cell 2"], Dropped(doc)); + Assert.Equal(1, PageCount(bytes)); + } + + /// The same with a repeated header row in place of the group. + [Fact] + public void AHeaderThatACellOutsideItNarrowedIsRelievedByThatCell() + { + using var doc = SmallPage(); + doc.Add(Table(header: true, s_twoLines)); + + var bytes = Save(doc); + + Assert.Equal(["row 2, cell 2"], Dropped(doc)); + Assert.Equal(1, PageCount(bytes)); + } + + /// + /// The last step takes the cells that the widths follow from and no others: a break in a fixed + /// column of another row is kept, and so is a break in an automatic column's cell that holds + /// none. + /// + [Fact] + public void TheLastStepLeavesTheOtherCellsTheirBreaks() + { + using var doc = SmallPage(); + doc.Add(Table(header: false, s_twoLines, ["p\nq", "r\ns", "t"])); + + Save(doc); + + Assert.Equal(["row 2, cell 2"], Dropped(doc)); + } + + /// + /// A table that the one-line measurement refuses too is still refused: with a space where the + /// line feed was, the cell is one 387pt line in either measurement. + /// + [Fact] + public void ATableThatTheOneLineMeasurementRefusesIsStillRefused() + { + using var doc = SmallPage(); + doc.Add(Table(header: false, W(37) + " " + W(4))); + + var ex = Assert.Throws(() => Save(doc)); + + Assert.Contains("RowSpan", ex.Message, StringComparison.Ordinal); + } + + /// + /// The seeds of the long random tables whose group or header the first three steps cannot + /// relieve: each saves when every cell is measured as one line, and none is refused. + /// + [Theory] + [InlineData(366)] + [InlineData(1482)] + [InlineData(2461)] + public void ALongRandomTableThatTheThreeStepsCouldNotRelieveIsSaved(int seed) + { + RequireDejaVu(); + using var doc = TableRandomDocuments.Long(seed); + + var bytes = Save(doc); + + Assert.True(PageCount(bytes) > 1); + } + + // ── Property: a table that fits measured as one line is saved ─────────────── + + /// + /// A table in the shape of the fixtures above with random line widths, a random column layout + /// and a random place for the tall cell, and a tab, a line feed or a carriage return and line + /// feed between the lines of the cell in the automatic column. + /// + private static Document Shaped(int seed) + { + var rng = new Random(seed); + var doc = SmallPage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }; + _ = rng.Next(3) switch + { + 0 => t.SetColumnWidths(100, 100), + 1 => t.SetColumnWidths(rng.Next(60, 140), 0, 0), + _ => t.SetColumnWidths(rng.Next(60, 140), rng.Next(60, 140), 0), + }; + var header = rng.Next(3) == 0; + var spanText = string.Join(rng.Next(4) == 0 ? "\n" : " ", Enumerable.Repeat("lorem ipsum", rng.Next(1, 5))); + var row0 = t.AddRow(header); + row0.AddCell(header ? new Cell(spanText) : new Cell(spanText) { RowSpan = 2 }).AddCell("a"); + t.AddRow().AddCell("b"); + var sep = rng.Next(3) switch { 0 => "\n", 1 => "\t", _ => "\r\n" }; + t.AddRow().AddCell("c").AddCell("d").AddCell(W(rng.Next(0, 45)) + sep + W(rng.Next(0, 12))); + if (rng.Next(2) == 0) t.AddRow().AddCell("e\nf").AddCell(W(rng.Next(0, 30)) + "\n" + W(rng.Next(0, 30))); + doc.Add(t); + return doc; + } + + private static bool Saves(Func build, bool measuredAsOneLine) + { + using var doc = build(); + TableMeasureProbe.Current = new TableMeasureProbe { ReadEveryCellUnbroken = measuredAsOneLine }; + try + { + Save(doc); + return true; + } + catch (InvalidOperationException) + { + return false; + } + finally + { + TableMeasureProbe.Current = null; + } + } + + /// + /// A document that saves with every cell measured as one line, as it was measured before breaks + /// were honoured, saves. The shaped tables come out of the first three steps refused often + /// enough that the property fails without the last one; the long random tables are the wider + /// net, over fixed, automatic, zero, negative and NaN widths, spans and header rows. + /// + [Fact] + public void ADocumentThatSavesMeasuredAsOneLineSaves() + { + RequireDejaVu(); + var checkedShaped = 0; + for (var seed = 0; seed < 600; seed++) + { + var s = seed; + if (!Saves(() => Shaped(s), measuredAsOneLine: true)) continue; + checkedShaped++; + Assert.True(Saves(() => Shaped(s), measuredAsOneLine: false), $"shaped table {seed} is refused"); + } + + var checkedLong = 0; + for (var seed = 0; seed < 250; seed++) + { + var s = seed; + if (!Saves(() => TableRandomDocuments.Long(s), measuredAsOneLine: true)) continue; + checkedLong++; + Assert.True(Saves(() => TableRandomDocuments.Long(s), measuredAsOneLine: false), $"long table {seed} is refused"); + } + + // The property is not vacuous: most of each family saves measured as one line. + Assert.True(checkedShaped > 300, $"only {checkedShaped} shaped tables save measured as one line"); + Assert.True(checkedLong > 40, $"only {checkedLong} long tables save measured as one line"); + } +} diff --git a/tests/VellumPdf.Layout.Tests/TableRandomDocuments.cs b/tests/VellumPdf.Layout.Tests/TableRandomDocuments.cs new file mode 100644 index 000000000..9744d3868 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableRandomDocuments.cs @@ -0,0 +1,156 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Text; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Elements.Table; + +namespace VellumPdf.Layout.Tests; + +/// +/// Seeded documents of long tables whose cells hold control white space, for the tests that compare +/// one measurement of a table with another over many tables. The same seed gives the same document. +/// +internal static class TableRandomDocuments +{ + internal static readonly string DejaVu = Path.Combine(AppContext.BaseDirectory, "Fonts", "DejaVuSans.ttf"); + + private static readonly DateTimeOffset s_pin = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + private static readonly byte[] s_pinId = [.. Enumerable.Range(1, 16).Select(i => (byte)i)]; + + private static string Text(Random rng, int maxTokens, bool controls, int tallLines) + { + string[] words = + [ + "ab", "x", "iiii", "WWW", "lorem", "ipsum", "caf\u00e9", "x\u00a0y", "\u2003em", "q", "mm", + rng.Next(6) == 0 ? "Superlongwordwithoutanybreak" : "ok", "1234567", "", "f", + ]; + string[] seps = controls + ? [" ", " ", " ", " ", "\t", "\n", "\n", "\r\n", "\r", "\f", "\v", "\u0085", "\u2028", "\u2029", "\t\t", "\n\n"] + : [" ", " ", " ", " "]; + var sb = new StringBuilder(); + var k = rng.Next(7) == 0 && tallLines > 0 ? rng.Next(tallLines / 2, tallLines + 6) : rng.Next(0, maxTokens + 1); + + // A tall cell is mostly line feeds, so its height is near the page's. + var tall = k > maxTokens; + for (var i = 0; i < k; i++) + { + if (i > 0) sb.Append(tall && controls && rng.Next(5) != 0 ? (rng.Next(6) == 0 ? "\r\n" : "\n") : seps[rng.Next(seps.Length)]); + sb.Append(words[rng.Next(words.Length)]); + } + if (controls && rng.Next(10) == 0) sb.Append(seps[rng.Next(seps.Length)]); + if (controls && rng.Next(15) == 0) sb.Insert(0, "\t"); + return sb.ToString(); + } + + private static TextStyle Style(Random rng, EmbeddedFontHandle dv) + { + double[] sizes = [7, 9, 10, 12, 14]; + FontReference f = rng.Next(5) switch + { + 0 => Standard14.TimesRoman, + 1 => Standard14.Courier, + 2 or 3 => dv, + _ => Standard14.Helvetica, + }; + var size = sizes[rng.Next(sizes.Length)]; + + // The generator once drew a leading here; the draw stays so that a seed keeps its tables. + _ = rng.Next(6); + return new TextStyle { FontRef = f, FontSize = size }; + } + + private static void Widths(Random rng, TableElement t, int cols, double pw) + { + switch (rng.Next(5)) + { + case 0: break; + case 1: + t.SetColumnWidths([.. Enumerable.Range(0, cols).Select(_ => (double)rng.Next(20, Math.Max(21, (int)(pw / cols))))]); + break; + case 2: + t.SetColumnWidths([.. Enumerable.Range(0, cols).Select(_ => rng.Next(4) switch + { + 0 => 0.0, + 1 => -5.0, + 2 => double.NaN, + _ => (double)rng.Next(20, Math.Max(21, (int)(pw / cols))), + })]); + break; + case 3: + t.SetColumnWidths([.. Enumerable.Range(0, rng.Next(1, cols + 1)).Select(_ => (double)rng.Next(20, Math.Max(21, (int)(pw / cols))))]); + break; + default: + t.SetColumnWidths([.. Enumerable.Range(0, cols).Select(i => i == 0 ? (double)rng.Next(30, Math.Max(31, (int)(pw * 0.7))) : 0.0)]); + break; + } + } + + private static void Fill(Random rng, TableElement t, int rows, int cols, int headers, bool controls, int tallLines, EmbeddedFontHandle dv, double rowSpanP, double colSpanP) + { + for (var r = 0; r < rows; r++) + { + var isHeader = r < headers || rng.Next(25) == 0; + var row = t.AddRow(isHeader); + var c = 0; + var n = rng.Next(8) == 0 ? cols + 1 : cols; + while (c < n) + { + var colSpan = rng.NextDouble() < colSpanP ? rng.Next(2, 4) : 1; + var rowSpan = rng.NextDouble() < rowSpanP ? rng.Next(2, 5) : 1; + var cell = new Cell(Text(rng, 14, controls, isHeader ? tallLines / 5 : rowSpan > 1 ? tallLines / 3 : tallLines)) + { + ColSpan = colSpan, + RowSpan = rowSpan, + Style = rng.Next(4) == 0 ? Style(rng, dv) : null, + Padding = rng.Next(5) == 0 ? new EdgeInsets(rng.Next(0, 9), rng.Next(0, 9), rng.Next(0, 9), rng.Next(0, 9)) : new EdgeInsets(4, 6, 4, 6), + }; + row.AddCell(cell); + c += colSpan; + } + } + } + + /// + /// Long tables over many pages: repeated header rows, rows cut between their lines, mirrored + /// margins of unequal sides, running bands, and several tables with paragraphs between them. + /// Explicit, zero, negative and NaN column widths all occur. The caller disposes the document. + /// + internal static Document Long(int seed) + { + var rng = new Random((seed * 31337) + 5); + var pw = rng.Next(350, 900); + var ph = rng.Next(300, 700); + var d = new Document + { + Timestamp = s_pin, + DocumentId = s_pinId, + PageSize = new PdfRectangle(0, 0, pw, ph), + Margins = new EdgeInsets(rng.Next(5, 50), rng.Next(5, 80), rng.Next(5, 50), rng.Next(5, 80)), + MirrorMargins = rng.Next(2) == 0, + Tagged = rng.Next(6) == 0, + Language = "en", + }; + var dv = d.UseTrueTypeFont(File.ReadAllBytes(DejaVu)); + if (rng.Next(3) == 0) + d.SetHeader(rng.Next(2) == 0 ? "Page {page}\tof {total}" : "Head {page}", new TextStyle { FontRef = rng.Next(2) == 0 ? dv : new FontReference(Standard14.Helvetica), FontSize = 8 }); + if (rng.Next(4) == 0) d.SetFooter("{page}", new TextStyle { FontSize = 8 }); + d.MirrorMargins = true; + var tables = rng.Next(1, 4); + for (var k = 0; k < tables; k++) + { + if (rng.Next(2) == 0) d.Add(new Paragraph(string.Join(" ", Enumerable.Repeat("before", rng.Next(1, 200))))); + var cols = rng.Next(1, 5); + var t = new TableElement { DefaultCellStyle = rng.Next(2) == 0 ? new TextStyle { FontRef = dv, FontSize = 9 } : null }; + Widths(rng, t, cols, pw); + var size = t.DefaultCellStyle?.FontSize ?? 12; + var tall = (int)(ph / (size * 1.2)); + Fill(rng, t, rng.Next(20, 120), cols, rng.Next(0, 3), true, tall, dv, 0.04, 0.05); + d.Add(t); + } + return d; + } +} From 2a1ffaa1fbd7054c710b01d40bce07dc6b0b5d09 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 10:18:35 +0100 Subject: [PATCH 25/48] perf(layout): stop re-resolving the whole grid for every table step Fillers in a shared automatic column grew with the square of the groups because each step copied the set of cells read unbroken and resolved the whole grid to see whether a column moved. A step now raises the per-column content widths kept for the pass by what its cells contribute unbroken, which is exact when no cell contributes less than before and falls back to measuring the table when one does. A line count also holds over an interval of widths when a word is broken at its characters, since every comparison the break makes bounds it, so a hard-broken cell no longer misses the cache at each new width. Measuring a broken word no longer allocates a string per character, and a row's height no longer builds its error text unless it is refused. --- .../Rendering/Table/TableGridResolver.cs | 49 ++++- .../Rendering/Table/TableMeasureCache.cs | 21 +- .../Rendering/Table/TableRenderer.cs | 205 +++++++++++++++--- .../TableMeasureCacheTests.cs | 180 +++++++++------ 4 files changed, 337 insertions(+), 118 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs b/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs index 585611718..f733ff133 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs @@ -43,8 +43,21 @@ internal sealed class TableGridResolver /// public TableMeasureCache? Cache { get; init; } + /// + /// The per-column minimum and maximum content widths to resolve from, in place of measuring the + /// cells, together with the column count they were taken for. Null to measure. + /// + public (double[] MinW, double[] MaxW)? Content { get; init; } + + /// + /// The per-column minimum and maximum content widths the resolution used, or null when it read + /// none: every column has a width of its own, or there are no columns. + /// + public (double[] MinW, double[] MaxW)? ContentUsed { get; private set; } + public void Resolve(TableElement table, double availableWidth) { + ContentUsed = null; // The column count is the widest row, not merely the first (#480 section 1). Nothing stops // a caller giving one row more cells than another: Row.AddCell checks no other row's arity, // and TableElement exposes no column count to check against. So a later row with an extra @@ -69,15 +82,22 @@ public void Resolve(TableElement table, double availableWidth) // have turned that into a silently wrapped, wrong column count and a quietly wrong document // instead — the same class of regression the reconciliation below exists to avoid on the // width axis. - ColCount = 0; - foreach (var row in table.Rows) + ColCount = Content is { } known ? known.MinW.Length : 0; + if (Content is null) { - var rowCols = 0; - checked + // Indexed, because an enumerator over a list of cells is one allocation per row, and + // the decision resolves the grid again for every step that moves a column. + var rows = table.Rows; + for (var r = 0; r < rows.Count; r++) { - foreach (var cell in row.Cells) rowCols += cell.ColSpan; + var cells = rows[r].Cells; + var rowCols = 0; + checked + { + for (var c = 0; c < cells.Count; c++) rowCols += cells[c].ColSpan; + } + if (rowCols > ColCount) ColCount = rowCols; } - if (rowCols > ColCount) ColCount = rowCols; } if (ColCount == 0) { ColWidths = []; return; } @@ -169,7 +189,7 @@ private double[] ReconcileExplicitWidths(TableElement table, double available, i if (autoCount > 0) { var residual = Math.Max(0.0, available - explicitSum); - var (minW, maxW) = ContentWidths(table, cols); + var (minW, maxW) = ContentOf(table, cols); var autoMaxTotal = 0.0; for (var i = 0; i < cols; i++) if (isAuto[i]) autoMaxTotal += maxW[i]; @@ -249,7 +269,7 @@ private double[] ReconcileExplicitWidths(TableElement table, double available, i /// private double[] AutoWidth(TableElement table, double available, int cols) { - var (minW, maxW) = ContentWidths(table, cols); + var (minW, maxW) = ContentOf(table, cols); // Distribute available width proportionally to max-content widths var totalMax = maxW.Sum(); @@ -285,6 +305,17 @@ private static void ScaleToFit(double[] widths, double available) for (var i = 0; i < widths.Length; i++) widths[i] *= scale; } + /// + /// The content widths this resolution works from: the ones it was given, or the ones it + /// measures. It keeps them for . + /// + private (double[] MinW, double[] MaxW) ContentOf(TableElement table, int cols) + { + var content = Content ?? ContentWidths(table, cols); + ContentUsed = content; + return content; + } + /// /// Per-column min-content (longest word) and max-content (full text) widths, shared by the /// fully-auto path and the residual distribution runs for @@ -351,7 +382,7 @@ private static void ScaleToFit(double[] widths, double available) /// /// The widest word and the widest line of a cell's text, each line measured on its own. /// - private static (double Longest, double Widest) MeasureCell(string content, TextStyle style, bool honourBreaks) + internal static (double Longest, double Widest) MeasureCell(string content, TextStyle style, bool honourBreaks) { var lines = TableRenderer.CellLines(content, honourBreaks); var longest = 0.0; diff --git a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs index 3af0ca309..e2e3e87be 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs @@ -44,13 +44,6 @@ internal struct CellMeasure /// True when and the interval that holds it are set. public bool HasLines; - /// - /// True when the count depends on the exact width, because a word wider than the width was - /// broken at its characters. then holds that width and - /// is unused. - /// - public bool Pinned; - /// The number of lines the cell wraps into. public int Lines; @@ -68,7 +61,7 @@ internal struct CellMeasure /// True when the cell wraps into lines at . /// public readonly bool Holds(double width) => - HasLines && (Pinned ? width.Equals(From) : From <= width && width < Below); + HasLines && From <= width && width < Below; } /// @@ -117,6 +110,18 @@ public static TableMeasureProbe? Current /// public int StepsKeptPassGoing { get; set; } + /// + /// Steps whose column widths came from raising the widths kept for the pass, without measuring + /// the table. + /// + public int WidthsRaised { get; set; } + + /// + /// Steps that measured the whole table again, because a cell would contribute less to a column + /// read unbroken than it did as it was. + /// + public int WidthsMeasuredAgain { get; set; } + /// /// Layouts that kept the grid and heights of the decision they were handed, and resolved /// nothing. diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 6005b537d..c13741e04 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -65,6 +65,11 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IP // What the decision under way has measured of each cell; null outside it. private TableMeasureCache? _measured; + // The per-column content widths the last resolution of the grid worked from, which the steps of + // one decision keep up to date as cells give up their breaks. Null outside a decision and when + // no column takes its width from its content. + private (double[] MinW, double[] MaxW)? _content; + // What _oneLine was decided for: the table width and the vertical extent of the two fresh // boxes. // A renderer that carries the decision to the next page reuses it, with the grid and the @@ -310,6 +315,7 @@ public LayoutResult Layout(LayoutContext context) } } _measured = null; + _content = null; _decidedFor = key; } } @@ -441,6 +447,7 @@ private void ResolveGrid(double areaWidth, TextStyle style, TableMeasureCache? c var grid = new TableGridResolver { OneLineCells = _oneLine, Cache = cache }; grid.Resolve(_table, areaWidth); _colWidths = grid.ColWidths; + _content = grid.ContentUsed; // #481's third refusal, and the one route to it that no span check covers: a table with no // rows, or rows holding no cells, resolves to no columns without any bad ColSpan, and @@ -460,12 +467,17 @@ private double MeasureRow(int r, TextStyle style) var maxH = 0.0; var col = 0; var cellIndex = -1; - foreach (var cell in row.Cells) + var rowCells = row.Cells; + for (var k = 0; k < rowCells.Count; k++) { + var cell = rowCells[k]; cellIndex++; if (col >= _colWidths.Length) break; var cs = cell.Style ?? style; - LayoutValidation.ValidateFontSize(cs, $"Table row {r}, cell {cellIndex}"); + + // The owner text is built only for the refusal: this runs for every cell on every pass. + if (!double.IsFinite(cs.FontSize)) + LayoutValidation.ValidateFontSize(cs, $"Table row {r}, cell {cellIndex}"); var colW = ColSpanWidth(col, cell.ColSpan); var innerW = colW - cell.Padding.Horizontal; var honourBreaks = HonoursBreaks(r, cellIndex); @@ -504,38 +516,37 @@ private static int CachedLineCount( } if (probe is not null) probe.WrapMisses++; - entry.Lines = CountLines(text, style, width, honourBreaks, out entry.From, out entry.Below, out entry.Pinned); + entry.Lines = CountLines(text, style, width, honourBreaks, out entry.From, out entry.Below); entry.HasLines = true; return entry.Lines; } /// /// The number of lines returns, without building them, and the - /// widths over which the count is the same. Each comparison of a width against a measurement - /// narrows and , so the count holds for every - /// width in [from, below), and for exactly the width given when a word wider than it was - /// broken at its characters (), because where that word breaks - /// follows the width. This method follows step for step, an empty word - /// included, and takes the same measurements from the font in the same order. + /// widths over which the count is the same. Every comparison of a width against a measurement + /// that the wrap makes, including the ones that decide where a word wider than the width is + /// broken at its characters, narrows and : + /// the wrap takes the same path at every width in [from, below), and so returns the same + /// lines. This method follows and step for + /// step, an empty word included, and takes the same measurements from the font in the same + /// order. /// internal static int CountLines( string text, TextStyle style, double maxWidth, bool honourBreaks, - out double from, out double below, out bool pinned) + out double from, out double below) { from = double.NegativeInfinity; below = double.PositiveInfinity; - pinned = false; if (string.IsNullOrEmpty(text)) return 1; var total = 0; foreach (var line in CellLines(text, honourBreaks)) - total += CountLine(line, style, maxWidth, ref from, ref below, ref pinned); - if (pinned) from = maxWidth; + total += CountLine(line, style, maxWidth, ref from, ref below); return total; } private static int CountLine( - string text, TextStyle style, double maxWidth, ref double from, ref double below, ref bool pinned) + string text, TextStyle style, double maxWidth, ref double from, ref double below) { if (string.IsNullOrEmpty(text)) return 1; @@ -573,8 +584,7 @@ private static int CountLine( if (ww > maxWidth) { below = Math.Min(below, ww); - pinned = true; - lines += CountHardBreakFragments(word, style, maxWidth); + lines += CountHardBreakFragments(word, style, maxWidth, ref from, ref below); continue; } from = Math.Max(from, ww); @@ -585,20 +595,34 @@ private static int CountLine( return lines == 0 ? 1 : lines; } - /// The number of lines adds for a word. - private static int CountHardBreakFragments(string word, TextStyle style, double maxWidth) + /// + /// The number of lines adds for a word. A fragment is cut where + /// the next character no longer fits, so each such comparison narrows the widths the count + /// holds over, like the ones in . + /// + private static int CountHardBreakFragments( + string word, TextStyle style, double maxWidth, ref double from, ref double below) { var fragments = 0; var open = false; var fragmentW = 0.0; foreach (var rune in word.EnumerateRunes()) { - var charW = style.FontRef.MeasureString(rune.ToString(), style.FontSize); - if (open && fragmentW + charW > maxWidth) + var charW = style.FontRef.MeasureString(RuneString(rune), style.FontSize); + if (open) { - fragments++; - fragmentW = 0.0; - open = false; + var grown = fragmentW + charW; + if (grown > maxWidth) + { + below = Math.Min(below, grown); + fragments++; + fragmentW = 0.0; + open = false; + } + else + { + from = Math.Max(from, grown); + } } open = true; fragmentW += charW; @@ -607,6 +631,20 @@ private static int CountHardBreakFragments(string word, TextStyle style, double return fragments; } + // The text of a rune, taken from a table for the characters below U+0100 so that measuring a + // long word one character at a time does not allocate a string per character. + private static readonly string[] s_latin1Strings = BuildLatin1Strings(); + + private static string[] BuildLatin1Strings() + { + var table = new string[256]; + for (var i = 0; i < table.Length; i++) table[i] = ((char)i).ToString(); + return table; + } + + private static string RuneString(System.Text.Rune rune) => + rune.Value < s_latin1Strings.Length ? s_latin1Strings[rune.Value] : rune.ToString(); + /// /// True when the cell's line breaks are kept; false when the table lays the cell out unbroken. /// @@ -647,6 +685,9 @@ private static bool AnyControlSpace(IReadOnlyList rows) HashSet<(int Row, int Cell)>? found = null; + // The cells the step under way has added to found, in the order it added them. + var step = new List<(int Row, int Cell)>(); + // The rows of the group being judged, and whether a cell was added that another group's // height can depend on: one in a row outside the group, which is a header row, or one in an // automatically sized column, whose width every row that has a cell in an automatic column @@ -667,20 +708,67 @@ private static bool AnyControlSpace(IReadOnlyList rows) bool ColumnWidthsHold() { if (outside) return false; - var trial = new HashSet<(int Row, int Cell)>(_oneLine ?? []); - trial.UnionWith(found!); - var grid = new TableGridResolver { OneLineCells = trial, Cache = cache }; - grid.Resolve(_table, areaWidth); - if (grid.ColWidths.Length != _colWidths.Length) return false; + + // The widths the table would have with the cells of this step read unbroken. Each + // column's minimum and maximum is the greatest of what its cells contribute, and a + // cell read unbroken contributes at least what it did, so the step raises them to the + // greater of the two and nothing else needs to be measured. When a cell would + // contribute less, the table is measured again from scratch. + var widths = WidthsWithStep(step); + if (widths is null) + { + if (TableMeasureProbe.Current is { } again) again.WidthsMeasuredAgain++; + widths = WidthsMeasuredAgain(); + } + else if (TableMeasureProbe.Current is { } raised) + { + raised.WidthsRaised++; + if (raised.Verify) + { + var fresh = WidthsMeasuredAgain(); + for (var i = 0; i < fresh.Length; i++) + if (fresh.Length != widths.Length || BitConverter.DoubleToInt64Bits(fresh[i]) != BitConverter.DoubleToInt64Bits(widths[i])) + throw new InvalidOperationException("Column widths raised by a step differ from the table measured again."); + } + } + if (widths.Length != _colWidths.Length) return false; for (var i = 0; i < _colWidths.Length; i++) - if (BitConverter.DoubleToInt64Bits(grid.ColWidths[i]) != BitConverter.DoubleToInt64Bits(_colWidths[i])) + if (BitConverter.DoubleToInt64Bits(widths[i]) != BitConverter.DoubleToInt64Bits(_colWidths[i])) return false; if (TableMeasureProbe.Current is { } probe) probe.StepsKeptPassGoing++; return true; } - void Note(int r, int col, int span) + // The column widths with every cell of the pass so far read unbroken, measuring the whole + // table. The step's cells are in neither _oneLine nor the measurements until the step is + // taken, so they come from the set found. + double[] WidthsMeasuredAgain() { + var trial = new HashSet<(int Row, int Cell)>(_oneLine ?? []); + trial.UnionWith(found!); + var grid = new TableGridResolver { OneLineCells = trial, Cache = cache }; + grid.Resolve(_table, areaWidth); + _content = grid.ContentUsed; + return grid.ColWidths; + } + + // The column widths with the cells of the step read unbroken, taken from the content widths + // kept for the pass, or null when a cell would contribute less than it did. + double[]? WidthsWithStep(List<(int Row, int Cell)> cells) + { + if (_content is not { } content) return null; + foreach (var (r, c) in cells) + if (!RaiseContentWidths(content, r, c, cache)) + return null; + + var grid = new TableGridResolver { Content = content }; + grid.Resolve(_table, areaWidth); + return grid.ColWidths; + } + + void Note(int r, int c, int col, int span) + { + step.Add((r, c)); if (r < own.First || r > own.Last) { shared = true; outside = true; return; } for (var k = 0; k < span && col + k < _colWidths.Length; k++) if (IsAutoColumn(col + k)) { shared = true; return; } @@ -701,7 +789,7 @@ bool CollectBreaks(int first, int last) if (HonoursBreaks(r, c) && LayoutText.HasLineBreak(cells[c].Content) && (found ??= []).Add((r, c))) { added = true; - Note(r, col, span); + Note(r, c, col, span); } col += span; } @@ -743,7 +831,7 @@ void Reach(int from, int to) && (found ??= []).Add((r, c))) { added = true; - Note(r, col, span); + Note(r, c, col, span); } col += span; } @@ -783,6 +871,7 @@ void Reach(int from, int to) own = (first, last); shared = false; outside = false; + step.Clear(); if (CollectBreaks(first, last)) { if (shared && !ColumnWidthsHold()) return found; @@ -797,6 +886,7 @@ void Reach(int from, int to) own = (first, last); shared = false; outside = false; + step.Clear(); if (CollectControlSpace(first, last) && shared) { // The last step takes every cell it can reach, so the group is not judged @@ -826,6 +916,52 @@ void Reach(int from, int to) return found ?? (exhausted ? CollectAutoColumnControlSpace() : null); } + /// + /// Raises the per-column content widths by what cell of row + /// contributes when it is read unbroken, as + /// would take it, and returns false, leaving the widths + /// unusable, when the cell contributes less to some column than it did read as it is. A + /// column's width is the greatest contribution of its cells, so a contribution that does not + /// fall leaves that greatest equal to the one a measurement of the whole table finds, bit for + /// bit, and one that is not a number is left to that measurement. + /// + private bool RaiseContentWidths((double[] MinW, double[] MaxW) content, int r, int c, TableMeasureCache cache) + { + var cells = _table.Rows[r].Cells; + var cols = content.MinW.Length; + var col = 0; + for (var k = 0; k < c; k++) col += cells[k].ColSpan; + if (col >= cols) return true; + + var cell = cells[c]; + ref var before = ref cache.Of(r, c, cells.Count, honourBreaks: true); + if (!before.HasWidths) return false; + + ref var after = ref cache.Of(r, c, cells.Count, honourBreaks: false); + if (!after.HasWidths) + { + var style = cell.Style ?? _table.DefaultCellStyle ?? TextStyle.Default; + (after.LongestWord, after.WidestLine) = TableGridResolver.MeasureCell(cell.Content, style, honourBreaks: false); + after.HasWidths = true; + if (TableMeasureProbe.Current is { } miss) miss.WidthMisses++; + } + + var share = cell.ColSpan; + var padding = cell.Padding.Horizontal; + var minBefore = (before.LongestWord / share) + padding; + var minAfter = (after.LongestWord / share) + padding; + var maxBefore = (before.WidestLine + padding) / share; + var maxAfter = (after.WidestLine + padding) / share; + if (!(minAfter >= minBefore) || !(maxAfter >= maxBefore)) return false; + + for (var s = 0; s < share && col + s < cols; s++) + { + content.MinW[col + s] = Math.Max(content.MinW[col + s], minAfter); + content.MaxW[col + s] = Math.Max(content.MaxW[col + s], maxAfter); + } + return true; + } + /// /// Every cell that holds control white space and has a column that is sized automatically /// among those it spans, and is not laid out unbroken yet, or null when there is none. The @@ -903,7 +1039,8 @@ private bool LeavesNoRoomForALine(LayoutBox[] fresh, double headerHeight, int fi for (var q = 0; q < rows.Count; q++) { var reach = 1; - foreach (var cell in rows[q].Cells) reach = Math.Max(reach, cell.RowSpan); + var qCells = rows[q].Cells; + for (var k = 0; k < qCells.Count; k++) reach = Math.Max(reach, qCells[k].RowSpan); if (reach <= 1) continue; var end = (int)Math.Min((long)q + reach - 1, rows.Count - 1); @@ -1700,7 +1837,7 @@ private static List WrapLine(string text, TextStyle style, double maxWid /// wrapped at spaces alone, measuring each control white-space character at its own width, and /// the lines are drawn without them, so a line is never wider than it was measured. /// - private static List WordWrapLines(string text, TextStyle style, double maxWidth, bool honourBreaks) + internal static List WordWrapLines(string text, TextStyle style, double maxWidth, bool honourBreaks) { if (string.IsNullOrEmpty(text)) return WrapLine(string.Empty, style, maxWidth); diff --git a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs index daf031bf2..8a6734783 100644 --- a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs @@ -94,6 +94,52 @@ public void ACellIsMeasuredForItsColumnWidthOncePerMode() Assert.True(probe.WidthHits > probe.WidthMisses, $"{probe.WidthHits} hits, {probe.WidthMisses} misses"); } + /// + /// A step that moves no column takes the column widths from the ones kept for the pass, raised + /// by what its cells contribute unbroken, and measures no cell of the table. The probe checks + /// every such step against the table measured again and throws on a difference. + /// + [Fact] + public void AStepRaisesTheKeptColumnWidthsAndMeasuresNoOtherCell() + { + const int groups = 6; + using var doc = WidePage(); + doc.Add(FillerTable(groups)); + + var probe = new TableMeasureProbe { Verify = true }; + TableMeasureProbe.Current = probe; + try { Save(doc); } + finally { TableMeasureProbe.Current = null; } + + Assert.Equal(groups, probe.WidthsRaised); + Assert.Equal(0, probe.WidthsMeasuredAgain); + } + + /// + /// A cell that contributes less to a column read unbroken than it did as it was is not a raise: + /// the table is measured again. "ab", a tab, "ab" and a line feed is two words and a space wide + /// with its breaks and two words wide without, because the tab and the line feed measure zero + /// in Helvetica, so its column's maximum falls. + /// + [Fact] + public void AStepThatNarrowsAColumnMeasuresTheTableAgain() + { + using var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(36, 0); + t.AddRow().AddCell(new Cell(Words(60)) { RowSpan = 2 }).AddCell("ab" + (char)9 + "ab" + (char)10); + t.AddRow().AddCell("c"); + doc.Add(t); + + var probe = new TableMeasureProbe { Verify = true }; + TableMeasureProbe.Current = probe; + try { Save(doc); } + finally { TableMeasureProbe.Current = null; } + + Assert.Equal(["row 0, cell 0", "row 0, cell 1"], Dropped(doc)); + Assert.Equal(1, probe.WidthsMeasuredAgain); + Assert.Equal(0, probe.WidthsRaised); + } + private static readonly string[] Alphabet = ["a", "i", "W", "ab", "word", "m", " ", " ", " ", " ", "\n", "\t", "\r\n", "x\u00A0y", "\u0001", "WWWWWWWW"]; @@ -108,9 +154,9 @@ private static string RandomText(Random rng) /// /// The count a certificate returns is the count of the wrap it stands for, and it holds across /// the interval it names: at the width it was made for, at the low end, and just under the - /// high end. A word wider than the width is broken at its characters, which pins the count to - /// that width. The texts include empty words, doubled spaces, line breaks and tabs, in both - /// modes, and widths down to one point. + /// high end. A word wider than the width is broken at its characters, and the comparisons that + /// decide where bound the interval as the others do. The texts include empty words, doubled + /// spaces, line breaks and tabs, in both modes, and widths down to one point. /// [Theory] [InlineData(false)] @@ -119,23 +165,16 @@ public void ACertificateCountsLikeTheWrapItStandsForAcrossItsInterval(bool honou { var style = Helvetica(); var rng = new Random(honourBreaks ? 1 : 2); - var pinned = 0; - var intervals = 0; + var broken = 0; for (var n = 0; n < 4000; n++) { var text = RandomText(rng); var width = Math.Max(1, rng.NextDouble() * 120); - var lines = TableRenderer.CountLines(text, style, width, honourBreaks, out var from, out var below, out var isPinned); + var lines = TableRenderer.CountLines(text, style, width, honourBreaks, out var from, out var below); Assert.Equal(TableRenderer.WordWrapCount(text, style, width, honourBreaks), lines); - if (isPinned) - { - pinned++; - Assert.Equal(width, from); - continue; - } - - intervals++; + if (text.Split([' ', '\n', '\r', '\t']).Any(w => style.MeasureString(w) > width)) + broken++; Assert.True(from <= width && width < below, $"{from} <= {width} < {below}"); if (double.IsFinite(from) && from >= 1) Assert.Equal(lines, TableRenderer.WordWrapCount(text, style, from, honourBreaks)); @@ -143,27 +182,32 @@ public void ACertificateCountsLikeTheWrapItStandsForAcrossItsInterval(bool honou Assert.Equal(lines, TableRenderer.WordWrapCount(text, style, Math.BitDecrement(below), honourBreaks)); } - Assert.True(pinned > 100 && intervals > 100, $"{pinned} pinned, {intervals} intervals"); + Assert.True(broken > 100, $"{broken} texts broke a word"); } /// - /// A wrap whose words all fit holds over a range of widths, and one that broke a word holds - /// at the width alone. One more point of width moves no break in "ab ab ab ab" at 36pt, and - /// moves the break of "abcdefghijklmnop" in a 20pt column. + /// A wrap that broke a word holds over a range of widths too: "abcdefghijklmnop" in a 20pt + /// column is cut at the character where the next one no longer fits, and every width that + /// leaves each cut where it is wraps into the same lines. /// [Fact] - public void ACertificateHoldsOverARangeUnlessAWordWasBroken() + public void ACertificateHoldsOverARangeWhenAWordWasBroken() { var style = Helvetica(); - - var lines = TableRenderer.CountLines("ab ab ab ab", style, 36, true, out var from, out var below, out var pinned); - Assert.Equal(TableRenderer.WordWrapCount("ab ab ab ab", style, 36, true), lines); - Assert.False(pinned); - Assert.True(from < 36 && 37 < below, $"[{from}, {below})"); - - TableRenderer.CountLines("abcdefghijklmnop", style, 20, true, out from, out _, out pinned); - Assert.True(pinned); - Assert.Equal(20.0, from); + const string word = "abcdefghijklmnop"; + + var lines = TableRenderer.CountLines(word, style, 20, true, out var from, out var below); + + Assert.True(lines > 1); + Assert.True(double.IsFinite(from) && double.IsFinite(below) && from < below, $"[{from}, {below})"); + Assert.True(from <= 20 && 20 < below, $"[{from}, {below})"); + Assert.Equal(TableRenderer.WordWrapLines(word, style, 20, true), TableRenderer.WordWrapLines(word, style, from, true)); + Assert.Equal( + TableRenderer.WordWrapLines(word, style, 20, true), + TableRenderer.WordWrapLines(word, style, Math.BitDecrement(below), true)); + Assert.NotEqual( + TableRenderer.WordWrapLines(word, style, 20, true), + TableRenderer.WordWrapLines(word, style, below, true)); } /// @@ -176,8 +220,7 @@ public void AnIntervalIsClosedBelowAndOpenAbove() { var style = Helvetica(); var text = "ab ab ab ab"; - var lines = TableRenderer.CountLines(text, style, 36, true, out var from, out var below, out var pinned); - Assert.False(pinned); + var lines = TableRenderer.CountLines(text, style, 36, true, out var from, out var below); Assert.True(double.IsFinite(from) && double.IsFinite(below), $"[{from}, {below})"); var entry = new CellMeasure { HasLines = true, Lines = lines, From = from, Below = below }; @@ -187,8 +230,6 @@ public void AnIntervalIsClosedBelowAndOpenAbove() Assert.False(entry.Holds(below)); Assert.False(entry.Holds(Math.BitDecrement(from))); Assert.False(new CellMeasure().Holds(36)); - Assert.False(new CellMeasure { HasLines = true, Pinned = true, Lines = 3, From = 20 }.Holds(Math.BitIncrement(20))); - Assert.True(new CellMeasure { HasLines = true, Pinned = true, Lines = 3, From = 20 }.Holds(20)); } /// @@ -393,56 +434,64 @@ private static (long Bytes, int Reported) Allocated(Func build) return (bytes, doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped).Sum(d => d.Count)); } + private static Document FillerDocument(int groups, string separator) + { + var doc = WidePage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(36, 36, 0); + for (var i = 0; i < groups; i++) + { + t.AddRow().AddCell("x").AddCell("x").AddCell(new Cell(Words(60, separator)) { RowSpan = 2 }); + t.AddRow().AddCell("y"); + } + doc.Add(t); + return doc; + } + /// /// Fillers in an automatic column: each group is a cell of 60 lines in the column other rows - /// share, beside two short cells in 36pt columns. The allocations of 400 of them stay under - /// a fixed multiple of those of the same table with the lines separated by spaces, which has - /// nothing to give up. Allocations are counted, not time, because the same run on a loaded - /// machine takes several times as long. + /// share, beside two short cells in 36pt columns. Every step keeps the column widths, so the + /// whole decision is one pass. The allocations of the table are a fixed multiple of those of + /// the same table with the lines separated by spaces, which has nothing to give up, at 400 + /// groups and at 1,600: a cost that grew with the square of the groups would pass the + /// smaller table and fail the larger. Allocations are counted, not time, because the same + /// run on a loaded machine takes several times as long. /// [Fact] - public void TheCostOfGivingUpBreaksInASharedAutoColumnDoesNotGrowWithEachGroup() + public void TheCostOfGivingUpBreaksInASharedAutoColumnStaysAFixedMultipleOfNotGivingThemUp() { - static Document Build(int groups, string separator) + Allocated(() => FillerDocument(10, "\n")); + Allocated(() => FillerDocument(10, " ")); + foreach (var groups in new[] { 400, 1600 }) { - var doc = WidePage(); - var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(36, 36, 0); - for (var i = 0; i < groups; i++) - { - t.AddRow().AddCell("x").AddCell("x").AddCell(new Cell(Words(60, separator)) { RowSpan = 2 }); - t.AddRow().AddCell("y"); - } - doc.Add(t); - return doc; + var withBreaks = Allocated(() => FillerDocument(groups, "\n")); + var withSpaces = Allocated(() => FillerDocument(groups, " ")); + + Assert.Equal(Math.Min(groups, 1000), withBreaks.Reported); + Assert.Equal(0, withSpaces.Reported); + Assert.True( + withBreaks.Bytes < 1.5 * withSpaces.Bytes, + $"{groups} groups: {withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); } - - Allocated(() => Build(10, "\n")); - Allocated(() => Build(10, " ")); - var withBreaks = Allocated(() => Build(400, "\n")); - var withSpaces = Allocated(() => Build(400, " ")); - - Assert.Equal(400, withBreaks.Reported); - Assert.Equal(0, withSpaces.Reported); - Assert.True(withBreaks.Bytes < 4.0 * withSpaces.Bytes, $"{withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); } /// /// Groups that each widen the automatic column, and so change what the next group is judged /// by: the cell of group i has 48 + i lines. Every step moves a column width, so none keeps /// the pass going and every group is judged on the widths the one before it leaves. The - /// allocations of 300 of them stay under 35 times those of the same table with the lines - /// separated by spaces, which has nothing to give up. + /// save of 300 of them allocates under 60MB, which is a bound on the + /// cost itself and not on its ratio to a table with nothing to give up, because that table's + /// cost moves with the caches too. /// [Fact] - public void TheCostOfGroupsThatEachWidenTheColumnStaysUnderAFixedMultiple() + public void TheCostOfGroupsThatEachWidenTheColumnStaysUnderAFixedBound() { - static Document Build(int groups, bool breaks) + static Document Build(int groups) { var doc = WidePage(); var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(0, 0, 0); for (var i = 0; i < groups; i++) { - t.AddRow().AddCell("x").AddCell(new Cell(Words(48 + i, breaks ? "\n" : " ")) { RowSpan = 2 }) + t.AddRow().AddCell("x").AddCell(new Cell(Words(48 + i)) { RowSpan = 2 }) .AddCell("lorem ipsum dolor sit amet " + i); t.AddRow().AddCell("y"); } @@ -450,14 +499,11 @@ static Document Build(int groups, bool breaks) return doc; } - Allocated(() => Build(10, true)); - Allocated(() => Build(10, false)); - var withBreaks = Allocated(() => Build(300, true)); - var withSpaces = Allocated(() => Build(300, false)); + Allocated(() => Build(10)); + var withBreaks = Allocated(() => Build(300)); Assert.Equal(300, withBreaks.Reported); - Assert.Equal(0, withSpaces.Reported); - Assert.True(withBreaks.Bytes < 35.0 * withSpaces.Bytes, $"{withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); + Assert.True(withBreaks.Bytes < 60_000_000L, $"{withBreaks.Bytes} bytes"); } /// From 329d10a819ececa06af57acca5b11e2cc4bbabd9 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 10:42:36 +0100 Subject: [PATCH 26/48] docs(layout): say what the table decision measures, and pin its cost The changelog said the decision measures each cell once, which is false: a line count is measured again when a column width leaves the interval it holds over. It now says what is kept, gives the figures against 2.3.3 rather than an unreleased build, says the early cutoff needs the step's cells to lie in the group's own rows, and says where the cost still grows. Corrects three comments: the cache is keyed by the cell's style too, the probe costs a thread-static read per lookup, and the 301 gloss names any control white space. The cost pins now fail when the shared-column step resolves the grid again, and when a broken word allocates per character. --- CHANGELOG.md | 24 ++++++++++++------- src/VellumPdf.Layout/Document.cs | 4 ++-- .../Rendering/Table/TableMeasureCache.cs | 17 +++++++------ .../Rendering/Table/TableRenderer.cs | 8 +++++-- .../TableMeasureCacheTests.cs | 21 ++++++++++++++++ 5 files changed, 54 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 67e3c5b10..2ef27e5ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -668,15 +668,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). as wide as 2.3.3 made them, and the header and the groups as tall. In a table with two 100pt columns and an automatic one, a group of two rows is 424pt tall on a page that leaves 280pt while a cell of the automatic column in a third row keeps its line break, and 100pt without it. - - **Every group is judged in order, and the decision measures each cell once.** A table that - gives up cells in several groups measures its cells' widths once per mode and its line counts - once per interval of column widths, keeps the pass going when a group's step leaves every - column width as it was, and resolves its grid once for all its pages. No limit on the number - of measurements applies, so a group is judged on the heights the groups before it leave - whatever their number. Measured in Release on net10.0, one run each: 400 groups that each - change the width the next is judged by took 0.95s and 170MB, where main took 4.55s and - 3,022MB; 1,000 groups that each widen an automatic column took 8.6s and 13,376MB, where main - took 29.8s and 48,492MB. + - **Every group is judged in order, and the decision keeps what each cell measures.** A table + that gives up cells in several groups keeps each cell's widest word and widest line per mode + and its line count with the interval of column widths it holds over, a word broken at its + characters included. After a step it takes the column widths from the widths kept for the + pass, which the step raises. A step that gives up only cells in the group's own rows, and + leaves every column width as it was, does not end the pass, and a table resolves its grid + once for all its pages. No limit on the number of measurements applies, so a group is judged + on the heights the groups before it leave whatever their number. Measured in Release on + net10.0, one run each, against 2.3.3 on the same tables: 400 groups that each change the + width the next is judged by took 1.2s and 68MB, where 2.3.3 took 6.3s and 3,022MB; 1,000 + groups that each widen an automatic column took 2.0s and 378MB, where 2.3.3 took 49.2s and + 48,489MB; 6,400 groups that give up a cell in a shared automatic column took 1.9s and 498MB, + where 2.3.3 took 12.4s and 9,319MB. The cost of groups that each widen an automatic column + still grows with the square of their number: each such step ends the pass and the next pass + visits every cell again (1,000 groups allocate 6.5 times what 400 do). - **`/FontBBox` of an embedded font is the font's own bounding box (#596).** The descriptor of every embedded TrueType and OpenType font held `[0, hhea descender, 1000 * 1000 / unitsPerEm, hhea ascender]`: a zero for xMin and a constant for xMax, so DejaVu Sans, Liberation Sans and Liberation diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index 9cf1639f9..e16a7757f 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -119,8 +119,8 @@ public Document() { } /// (mirroring ), /// (a preformatted line split with /// a marker; a warning, which saves), - /// (a table cell's tab or line break - /// left out of what is drawn; also a warning), + /// (a table cell's tab, line break or + /// other control white space left out of what is drawn; also a warning), /// , /// and /// (a request to keep elements together or diff --git a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs index e2e3e87be..9e131cc40 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs @@ -6,14 +6,15 @@ namespace VellumPdf.Layout.Rendering.Table; /// /// What one table decision has measured of its cells, so that measuring the table again does not /// measure every cell again. The decision that reads some cells unbroken measures the whole table -/// once per step, while a cell's longest word and widest line depend on its text and mode alone, -/// and its line count on those and the width it wraps at. +/// once per pass, while a cell's longest word and widest line depend on its text, its style and +/// its mode alone, and its line count on those and the width it wraps at. /// /// /// The cache holds, per cell and per mode (breaks kept or read unbroken), the cell's longest -/// word and widest line, which depend on its text and mode alone, and the number of lines it wraps -/// into, with the interval of widths over which that number holds. It lives for one decision and -/// is dropped with it, so a table that is edited between saves is measured from nothing. +/// word and widest line, which depend on its text, style and mode alone, and the number of lines +/// it wraps into, with the interval of widths over which that number holds. It lives for one +/// decision and is dropped with it, so a table that is edited between saves is measured from +/// nothing. /// Each entry is exact: a lookup returns what measuring again would return, bit for bit, or /// misses. /// @@ -66,8 +67,10 @@ public readonly bool Holds(double width) => /// /// A hook for tests of the table caches: counts what the caches answered, and when -/// is set measures again on every hit and throws when the answer differs. -/// It is thread-static and null by default, so a save pays one null test for it. +/// is set measures again on every hit, and on every step that raises the kept +/// column widths, and throws when the answer differs. +/// It is thread-static and null by default, so a save pays one thread-static read for it each +/// time a cell is looked up. /// internal sealed class TableMeasureProbe { diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index c13741e04..43f917cf5 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -180,7 +180,8 @@ void IPlacementSource.ReportPlacements(PlacementSink sink) /// under a context without the box is not cut. /// A carriage return or line feed in a cell ends a line. A repeated header row, or rows /// joined by a , can lose the breaks of some cells, those of a cell - /// in an automatically sized column among them, and the save reports each as ; + /// in an automatically sized column among them, and the save reports each as + /// ; /// says when and which. A context built with the public /// constructor of keeps every break. /// These are refused with the too-tall exception, extended with a sentence naming the @@ -988,7 +989,10 @@ private bool RaiseContentWidths((double[] MinW, double[] MaxW) content, int r, i return found; } - /// True when a column that a cell at for columns is in is sized automatically. + /// + /// True when a column that a cell at for + /// columns is in is sized automatically. + /// private bool TouchesAutoColumn(int col, int span) { for (var k = 0; k < span && col + k < _colWidths.Length; k++) diff --git a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs index 8a6734783..68e4c1123 100644 --- a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs @@ -140,6 +140,27 @@ public void AStepThatNarrowsAColumnMeasuresTheTableAgain() Assert.Equal(0, probe.WidthsRaised); } + /// + /// Counting the lines of a word broken at its characters measures each character without + /// allocating a string for it: 3,000 Latin-1 characters allocate under 4KB, where a string per + /// character is about 90KB. A cell that gives up its breaks is one long word, and the decision + /// counts it again at every width the columns take. + /// + [Fact] + public void CountingABrokenWordAllocatesNothingPerCharacter() + { + var style = Helvetica(); + var word = string.Concat(Enumerable.Repeat("abc", 1000)); + TableRenderer.CountLines(word, style, 100, true, out _, out _); + + var before = GC.GetAllocatedBytesForCurrentThread(); + var lines = TableRenderer.CountLines(word, style, 100, true, out _, out _); + var bytes = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.True(lines > 100, $"{lines} lines"); + Assert.True(bytes < 4096, $"{bytes} bytes"); + } + private static readonly string[] Alphabet = ["a", "i", "W", "ab", "word", "m", " ", " ", " ", " ", "\n", "\t", "\r\n", "x\u00A0y", "\u0001", "WWWWWWWW"]; From 7583406071ed71db5d07f3308db0bd14ac4fbf52 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 12:00:05 +0100 Subject: [PATCH 27/48] fix(layout): judge each row under a header span by its own height A RowSpan declared in a header row held the data rows under it together for the cut, but the layout may still end a page between them. The decision counted them as a group, so rows that fit a page on their own gave up their breaks, and the last step reached cells of other rows through them. Each such row is now judged alone and a span declared in a data row is still a group. Layout is unchanged. --- CHANGELOG.md | 3 + src/VellumPdf.Layout/Elements/Table/Cell.cs | 18 ++-- .../Rendering/Table/TableRenderer.cs | 45 +++++++-- .../TableLastStepTests.cs | 92 +++++++++++++++++++ 4 files changed, 142 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ef27e5ac..e8ce4a739 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -668,6 +668,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). as wide as 2.3.3 made them, and the header and the groups as tall. In a table with two 100pt columns and an automatic one, a group of two rows is 424pt tall on a page that leaves 280pt while a cell of the automatic column in a third row keeps its line break, and 100pt without it. + A span declared in a header row makes no group of the data rows under it, because a page may + end between them, so each of those rows is judged by its own height; a span declared in a data + row is a group. - **Every group is judged in order, and the decision keeps what each cell measures.** A table that gives up cells in several groups keeps each cell's widest word and widest line per mode and its line count with the interval of column widths it holds over, a word broken at its diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 20e5494d2..d6385184e 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -48,14 +48,16 @@ public sealed class Cell /// joined by a . The header rows have no room when they do not fit a /// page, or when they leave a row below them less than one line of one of its cells. A span /// group has no room when it is taller than what a page leaves under the repeated header - /// rows. The cause is a line break, which adds a line, or any other control white space, - /// because a tab is one space wide where the font measures the tab character at its own - /// width: a tab can tip a table that holds no line break. Such a cell is wrapped at spaces - /// alone and sized from its whole text, each tab and line break in it measured at the width - /// its font gives it and left out of what is drawn. The words they separated run together in - /// the drawing and in extracted text, and no line is wider than it was measured, though a - /// glyph wider than its column can still extend past it, as in any cell. The save lists the - /// cell as , a + /// rows. A span declared in a header row makes no group of the data rows under it, because a + /// page may end between them; each of those rows is judged by its own height, and a span + /// declared in a data row is a group. The cause is a line break, which adds a line, or any + /// other control white space, because a tab is one space wide where the font measures the tab + /// character at its own width: a tab can tip a table that holds no line break. Such a cell is + /// wrapped at spaces alone and sized from its whole text, each tab and line break in it + /// measured at the width its font gives it and left out of what is drawn. The words they + /// separated run together in the drawing and in extracted text, and no line is wider than it + /// was measured, though a glyph wider than its column can still extend past it, as in any + /// cell. The save lists the cell as , a /// warning that saves. /// Which cells give them up is decided in order: the header rows are judged first, then /// each group of rows joined by a , each on the heights the decisions diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 43f917cf5..acc0c3ca0 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -1032,14 +1032,23 @@ private bool LeavesNoRoomForALine(LayoutBox[] fresh, double headerHeight, int fi } /// - /// The runs of rows held together by declarations, from the first - /// data row on, merged where one reaches into another. The same runs as - /// finds one at a time, found in one pass over the rows. + /// The runs of rows that the layout keeps whole, which the decision judges one at a time: the + /// runs of rows held together by declarations in the data rows, + /// merged where one reaches into another, and each data row that lies under a span declared in + /// a header row. The same runs as never splits, found in + /// one pass over the rows, in order. /// + /// + /// A span declared in a header row holds the data rows under it together as far as the cut is + /// concerned (), but the layout may still end a page between them, so + /// each of those rows is judged alone: a run of them is not a group, and counting one as a + /// group made rows that fit a page on their own give up their breaks. + /// private List<(int First, int Last)> SpanGroups(int firstDataRow) { var rows = _table.Rows; var groups = new List<(int First, int Last)>(); + var headerReach = -1; for (var q = 0; q < rows.Count; q++) { var reach = 1; @@ -1048,15 +1057,35 @@ private bool LeavesNoRoomForALine(LayoutBox[] fresh, double headerHeight, int fi if (reach <= 1) continue; var end = (int)Math.Min((long)q + reach - 1, rows.Count - 1); - var start = Math.Max(q, firstDataRow); - if (end < start) continue; + if (q < firstDataRow) + { + headerReach = Math.Max(headerReach, end); + continue; + } - if (groups.Count > 0 && start <= groups[^1].Last) + if (groups.Count > 0 && q <= groups[^1].Last) groups[^1] = (groups[^1].First, Math.Max(groups[^1].Last, end)); else - groups.Add((start, end)); + groups.Add((q, end)); + } + + if (headerReach < firstDataRow) return groups; + + // The data rows under a header span that no group holds, each alone, in order with the rest. + var all = new List<(int First, int Last)>(groups.Count + headerReach - firstDataRow + 1); + var next = 0; + for (var r = firstDataRow; r <= headerReach; r++) + { + while (next < groups.Count && groups[next].Last < r) all.Add(groups[next++]); + if (next < groups.Count && groups[next].First <= r) + { + r = groups[next].Last; + continue; + } + all.Add((r, r)); } - return groups; + while (next < groups.Count) all.Add(groups[next++]); + return all; } // ── Cutting a row between its lines ── diff --git a/tests/VellumPdf.Layout.Tests/TableLastStepTests.cs b/tests/VellumPdf.Layout.Tests/TableLastStepTests.cs index d19a29c03..a70d7f1a1 100644 --- a/tests/VellumPdf.Layout.Tests/TableLastStepTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableLastStepTests.cs @@ -164,6 +164,98 @@ public void ALongRandomTableThatTheThreeStepsCouldNotRelieveIsSaved(int seed) Assert.True(PageCount(bytes) > 1); } + // ── A RowSpan declared in a header row ────────────────────────────────────── + + private static string Lines(int n) => string.Join("\n", Enumerable.Repeat("ab", n)); + + /// + /// A header row of 20pt whose first cell spans the two data rows under it, 152pt each on a + /// page that leaves 280pt. Each row fits on its own under the header and the two together do + /// not. The layout ends a page between them, because it keeps only a span that a data row + /// declares whole, so neither row gives up its breaks. + /// + [Fact] + public void RowsUnderAHeaderSpanAreJudgedOneAtATime() + { + using var doc = SmallPage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(100, 100); + t.AddRow(true).AddCell(new Cell("h") { RowSpan = 3 }).AddCell("H"); + t.AddRow().AddCell(Lines(12)); + t.AddRow().AddCell(Lines(12)); + doc.Add(t); + + var bytes = Save(doc); + + Assert.Empty(Dropped(doc)); + Assert.Equal(2, PageCount(bytes)); + } + + /// + /// A row under a header span that is too tall for a page under the header with its breaks, and + /// fits without them, gives them up, and the row beside it, which fits, keeps its own. + /// + [Fact] + public void ARowUnderAHeaderSpanThatHasNoRoomGivesUpItsBreaks() + { + using var doc = SmallPage(); + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(100, 100); + t.AddRow(true).AddCell(new Cell("h") { RowSpan = 3 }).AddCell("H"); + t.AddRow().AddCell(Lines(25)); + t.AddRow().AddCell(Lines(3)); + doc.Add(t); + + Save(doc); + + Assert.Equal(["row 1, cell 0"], Dropped(doc)); + } + + /// + /// The shape of a span declared in the last header row over two data rows that each fit a page + /// on their own, with a cell of an automatic column in a row of no group that holds a break. + /// Nothing has no room, so no cell gives up its breaks; counting the two rows as a group, the + /// last step took the cells of the automatic column in the rows below as well. + /// + [Theory] + [InlineData(18)] + [InlineData(24)] + [InlineData(26)] + [InlineData(34)] + public void ASpanInTheLastHeaderRowIsNotAGroupOverTheRowsItReaches(int lines) + { + string Long(int k) => string.Join(" ", Enumerable.Repeat("lorem ipsum dolor sit amet consectetur adipiscing", k)); + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 600, 400), Margins = new EdgeInsets(10) }; + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(300, 60, 0); + t.AddRow(true).AddCell(new Cell("span") { RowSpan = 3 }).AddCell("H"); + t.AddRow().AddCell(Long(lines)).AddCell("a\nb"); + t.AddRow().AddCell(Long(lines)).AddCell("c\nd"); + for (var i = 0; i < 4; i++) t.AddRow().AddCell("x").AddCell("plain").AddCell("keep\nbreak"); + doc.Add(t); + + Save(doc); + + Assert.Empty(Dropped(doc)); + } + + /// + /// The same span declared in the first data row is a group: the two rows are kept whole, they + /// do not fit a page together, and the table is refused as on 2.3.3. + /// + [Fact] + public void ASpanInADataRowStillHoldsItsRowsWhole() + { + string Long(int k) => string.Join(" ", Enumerable.Repeat("lorem ipsum dolor sit amet consectetur adipiscing", k)); + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 600, 400), Margins = new EdgeInsets(10) }; + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(300, 60, 0); + t.AddRow(true).AddCell("h").AddCell("H"); + t.AddRow().AddCell(new Cell(Long(24)) { RowSpan = 2 }).AddCell("a\nb"); + t.AddRow().AddCell(Long(24)).AddCell("c\nd"); + doc.Add(t); + + var ex = Assert.Throws(() => Save(doc)); + + Assert.Contains("RowSpan", ex.Message, StringComparison.Ordinal); + } + // ── Property: a table that fits measured as one line is saved ─────────────── /// From 17cc9af82cf02d675f034f615143a9513cf4b053 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 12:19:39 +0100 Subject: [PATCH 28/48] fix(layout): keep a table refused when it is measured as one line The decision gave up a cell's breaks only where a header or group had no room, which could leave a table that is refused when every cell is read as one line saving with its breaks kept. It now measures the table with every cell read unbroken once, from the same cache, and when that table would be refused it is laid out that way and refused with the same message. The trial measures without adding to an embedded font's subset, so a tab in a table that saves leaves no glyph 0 behind. --- CHANGELOG.md | 14 +- .../Fonts/EmbeddedFontHandle.cs | 7 + .../Fonts/TrueTypeFontEmbedder.cs | 14 ++ src/VellumPdf.Layout/Core/FontReference.cs | 19 +- src/VellumPdf.Layout/Elements/Table/Cell.cs | 8 + .../Rendering/Table/TableRenderer.cs | 140 ++++++++++- .../TableMainRefusalTests.cs | 225 ++++++++++++++++++ 7 files changed, 411 insertions(+), 16 deletions(-) create mode 100644 tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index e8ce4a739..ba11f8516 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -634,13 +634,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). fit can therefore be cut: `A` followed by 120 tabs and `B` in Helvetica 10 on a 300 pt page saved with no truncation, and now draws 1 of its 122 characters and reports `BandTruncated`, which `StrictDiagnostics` refuses. - - A table that 2.3.3 refused as too tall can now save: 6 of 20,000 random tables with control - characters (none of 20,000 without). Each is a refusal that names a `RowSpan` group, in a - table whose automatic columns are now measured per line. `qpdf --check` exits 0 for all six. - Three of the six draw text outside the row it belongs to. That comes from a mismatch that - 2.3.3 has too and this change does not alter: a row's height is measured with its cells in - consecutive columns, and the drawing skips a column that a span from an earlier row occupies. - Tables whose texts hold no tab, line break or form feed show it on 2.3.3 as well. + - **A table that is refused when every cell is measured as one line stays refused.** That is how + 2.3.3 measured a table. Reading a cell's line breaks can leave a column wider or narrower + than that measurement does, and so tip a `RowSpan` group the other way. Such a table is + refused here with the message of the one-line measurement, though every header and group has + room with its breaks read. The cells give up their breaks only to save a table that + measurement saves. A release that measures the columns a `RowSpan` occupies as they are + drawn can save some of these tables. - A cell with a very large number of lines can be refused where 2.3.3 saved it, because 2.3.3 drew its line feeds inside one line. One cell of 2,500,000 two-letter words joined by LF, on a 2000 x 600 pt page in a 1900 pt column, saved in 314 pages on 2.3.3 and now stops at the limit diff --git a/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs b/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs index ac3d70df6..ac970d943 100644 --- a/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs +++ b/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs @@ -50,6 +50,13 @@ internal EmbeddedFontHandle(TrueTypeFontEmbedder embedder, object owner, string public double MeasureString(string text, double pointSize) => Embedder.MeasureString(text, pointSize); + /// + /// The width returns, without registering any character for the + /// subset. + /// + internal double MeasureStringWithoutRegistering(string text, double pointSize) => + Embedder.MeasureStringWithoutRegistering(text, pointSize); + /// /// Maps a Unicode code point to a glyph id, registering it for font subsetting. /// Safe to call from the layout/draw phase; all registered code points are included diff --git a/src/VellumPdf.Kernel/Fonts/TrueTypeFontEmbedder.cs b/src/VellumPdf.Kernel/Fonts/TrueTypeFontEmbedder.cs index 4b6ffdc43..cfc5736ee 100644 --- a/src/VellumPdf.Kernel/Fonts/TrueTypeFontEmbedder.cs +++ b/src/VellumPdf.Kernel/Fonts/TrueTypeFontEmbedder.cs @@ -267,6 +267,20 @@ public double MeasureString(string text, double pointSize) return total / 1000.0 * pointSize; } + /// + /// The width returns, found without registering any character: the + /// subset, the ToUnicode map and the report of characters the font has no glyph for are left + /// as they were. A caller that measures text it may never draw uses this, so a measurement + /// that is dropped leaves nothing in the file. + /// + internal double MeasureStringWithoutRegistering(string text, double pointSize) + { + var total = 0.0; + foreach (var cp in EnumerateCodePoints(text)) + total += GetAdvanceWidth(PeekGlyphId(cp)); + return total / 1000.0 * pointSize; + } + // The name without the subset tag, as a glyph-0 report names the font. internal string PostScriptName => _name.PostScriptName ?? _name.FamilyName ?? "Unknown"; diff --git a/src/VellumPdf.Layout/Core/FontReference.cs b/src/VellumPdf.Layout/Core/FontReference.cs index c4a1bb1ed..c498e2c07 100644 --- a/src/VellumPdf.Layout/Core/FontReference.cs +++ b/src/VellumPdf.Layout/Core/FontReference.cs @@ -133,6 +133,23 @@ public FontReference(EmbeddedFontHandle handle) /// font measures such text without an exception. /// public double MeasureString(string text, double pointSize) => IsEmbedded - ? _embedded!.MeasureString(text, pointSize) + ? (s_measuringWithoutRegistering + ? _embedded!.MeasureStringWithoutRegistering(text, pointSize) + : _embedded!.MeasureString(text, pointSize)) : Standard14Metrics.MeasureString(_standard14, text, pointSize); + + // Set by a layout that measures text it may never draw, such as the table decision's trial of a + // measurement it can drop: the width is the same, and nothing is added to the subset. + [ThreadStatic] + private static bool s_measuringWithoutRegistering; + + /// + /// True while the calling thread measures embedded text without adding any of it to the + /// subset. + /// + internal static bool MeasuringWithoutRegistering + { + get => s_measuringWithoutRegistering; + set => s_measuringWithoutRegistering = value; + } } diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index d6385184e..73a31998a 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -82,6 +82,14 @@ public sealed class Cell /// change other rows: the column's width is shared with every row that has a cell in it. The /// groups after it are judged on the heights that result, so every group is judged on the /// heights the decisions before it leave, however many groups the table has. + /// A table that is refused when every cell is measured as one line is refused, with + /// the message that measurement gives. + /// throws , the too-tall exception, though every header + /// and group has room with its breaks read: reading the breaks can leave a column wider or + /// narrower than the one-line measurement does and so tip a group the other way, and the + /// cells above give up their breaks only to save a table that measurement saves. Do not + /// pass a table in the expectation that it stays refused: a release that measures the + /// columns a occupies as they are drawn can save some of them. /// A row that can be cut between its lines is cut when it is taller than a page. A /// repeated header row or a span group is never cut, and the save refuses it when it does not /// fit; a table whose rows are all headers repeats none of them, so its rows are cut like any diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index acc0c3ca0..d6fb316b7 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -62,6 +62,12 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IP // break is kept. private HashSet<(int Row, int Cell)>? _oneLine; + // True when every cell is laid out unbroken, as the table was measured before breaks were + // honoured. Layout sets it when the decision finds that the table, so measured, is refused: + // the table is then refused with that measurement's refusal. It is decided with _oneLine, so it + // goes with it. + private bool _allUnbroken; + // What the decision under way has measured of each cell; null outside it. private TableMeasureCache? _measured; @@ -255,7 +261,11 @@ public LayoutResult Layout(LayoutContext context) ? (area.Width, fresh[0].Y, fresh[0].Bottom, fresh[1].Y, fresh[1].Bottom) : ((double, double, double, double, double)?)null; var decided = key is not null && _decidedFor is { } was && was.Equals(key.Value); - if (!decided) _oneLine = null; + if (!decided) + { + _oneLine = null; + _allUnbroken = false; + } // The grid and the heights that decision was made with stand too: they follow from the // table, the width and the cells read unbroken, which are all the same. The renderer @@ -289,10 +299,7 @@ public LayoutResult Layout(LayoutContext context) // one line, with nothing to decide. if (passesNeeded && TableMeasureProbe.Current is { ReadEveryCellUnbroken: true }) { - _oneLine = []; - for (var r = 0; r < rows.Count; r++) - for (var c = 0; c < rows[r].Cells.Count; c++) - _oneLine.Add((r, c)); + _allUnbroken = true; passesNeeded = false; } @@ -314,6 +321,33 @@ public LayoutResult Layout(LayoutContext context) _oneLine.UnionWith(more); ResolveGrid(area.Width, style, cache); } + + // A table that 2.3.3 refused stays refused: the decision above keeps the breaks + // of the cells that left every header and group room, and that can leave the + // table fit where it measures every cell as one line and is refused. Cell.Content + // says why. + if (AnyControlSpaceKeepsItsBreaks(rows)) + { + var (widths, heights) = (_colWidths, _rowHeights); + _allUnbroken = true; + + // A trial that is dropped must leave nothing in the file: a tab measured + // in an embedded font would otherwise add glyph 0 to its subset. + FontReference.MeasuringWithoutRegistering = true; + try + { + ResolveGrid(area.Width, style, cache); + } + finally + { + FontReference.MeasuringWithoutRegistering = false; + } + if (!RefusedOnAFreshPage(fresh!, style)) + { + _allUnbroken = false; + (_colWidths, _rowHeights) = (widths, heights); + } + } } _measured = null; _content = null; @@ -419,10 +453,11 @@ public LayoutResult Layout(LayoutContext context) _headSlice = head, _tailSlice = tail, _oneLine = _oneLine, + _allUnbroken = _allUnbroken, _decidedFor = _decidedFor, }; var overflow = tail is null - ? new TableRenderer(_table, lastFit + 1) { _continuation = true, _colWidths = _colWidths, _rowHeights = _rowHeights, _oneLine = _oneLine, _decidedFor = _decidedFor } + ? new TableRenderer(_table, lastFit + 1) { _continuation = true, _colWidths = _colWidths, _rowHeights = _rowHeights, _oneLine = _oneLine, _allUnbroken = _allUnbroken, _decidedFor = _decidedFor } : new TableRenderer(_table, tail.Row) { _continuation = true, @@ -431,6 +466,7 @@ public LayoutResult Layout(LayoutContext context) _resumeLines = tail.Source, _resumeFrom = tail.Next(), _oneLine = _oneLine, + _allUnbroken = _allUnbroken, _decidedFor = _decidedFor, }; return LayoutResult.Partial(_occupied, split, overflow); @@ -445,7 +481,7 @@ private void ResolveGrid(double areaWidth, TextStyle style, TableMeasureCache? c if (TableMeasureProbe.Current is { } probe) probe.Passes++; _measured = cache; var rows = _table.Rows; - var grid = new TableGridResolver { OneLineCells = _oneLine, Cache = cache }; + var grid = new TableGridResolver { OneLineCells = _allUnbroken ? EveryCell.Instance : _oneLine, Cache = cache }; grid.Resolve(_table, areaWidth); _colWidths = grid.ColWidths; _content = grid.ContentUsed; @@ -649,7 +685,36 @@ private static string RuneString(System.Text.Rune rune) => /// /// True when the cell's line breaks are kept; false when the table lays the cell out unbroken. /// - private bool HonoursBreaks(int row, int cell) => _oneLine?.Contains((row, cell)) != true; + private bool HonoursBreaks(int row, int cell) => !_allUnbroken && _oneLine?.Contains((row, cell)) != true; + + /// True when some cell holds control white space and the table reads its breaks. + private bool AnyControlSpaceKeepsItsBreaks(IReadOnlyList rows) + { + for (var r = 0; r < rows.Count; r++) + { + var cells = rows[r].Cells; + for (var c = 0; c < cells.Count; c++) + if (HonoursBreaks(r, c) && LayoutText.HasControlSpace(cells[c].Content)) return true; + } + return false; + } + + /// The set of every cell, for a table that lays out every cell unbroken. + private sealed class EveryCell : IReadOnlySet<(int Row, int Cell)> + { + public static readonly EveryCell Instance = new(); + + public int Count => throw new NotSupportedException(); + public bool Contains((int Row, int Cell) item) => true; + public bool IsProperSubsetOf(IEnumerable<(int Row, int Cell)> other) => throw new NotSupportedException(); + public bool IsProperSupersetOf(IEnumerable<(int Row, int Cell)> other) => throw new NotSupportedException(); + public bool IsSubsetOf(IEnumerable<(int Row, int Cell)> other) => throw new NotSupportedException(); + public bool IsSupersetOf(IEnumerable<(int Row, int Cell)> other) => throw new NotSupportedException(); + public bool Overlaps(IEnumerable<(int Row, int Cell)> other) => throw new NotSupportedException(); + public bool SetEquals(IEnumerable<(int Row, int Cell)> other) => throw new NotSupportedException(); + public IEnumerator<(int Row, int Cell)> GetEnumerator() => throw new NotSupportedException(); + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => throw new NotSupportedException(); + } private static bool AnyControlSpace(IReadOnlyList rows) { @@ -1116,6 +1181,65 @@ private static bool FitsFresh(LayoutBox[] fresh, double headerHeight, double hei return false; } + /// + /// True when laying the table out from _rowHeights and _colWidths, page after + /// page, ends with a page that answers from the top + /// of a fresh page, which the save refuses with the too-tall exception. + /// + /// + /// The layout answers Nothing where no row fits the page it is given and the first row cannot + /// be cut. It is given a fresh page after every break, and a break falls only where + /// allows one, so the layout is refused exactly when + /// the header rows do not fit a page, or a run of rows it never breaks inside does not fit + /// one, and the run is not a single row that can be cut between its lines. Fitting is the fit + /// loop's own test, row by row on the running height, on each of the two boxes a fresh page + /// can offer. + /// + private bool RefusedOnAFreshPage(LayoutBox[] fresh, TextStyle style) + { + var rows = _table.Rows; + var header = FindHeaderRowIndices(rows); + var lastHeaderRow = header.Count > 0 ? header[^1] + 1 : 0; + var headerHeight = 0.0; + foreach (var i in header) headerHeight += _rowHeights[i]; + + var first = Math.Max(_startRow, lastHeaderRow); + if (first >= rows.Count) return false; + if (header.Count > 0 && !FitsFresh(fresh, 0, headerHeight)) return true; + + var blocked = BuildRowspanBlockedSet(rows, lastHeaderRow); + var ctx = new RefusalContext(fresh, header, headerHeight, lastHeaderRow); + for (var s = first; s < rows.Count;) + { + var last = s; + while (blocked.Contains(last)) last++; + if (!RunFitsFresh(fresh, headerHeight, s, last) && (last != s || !CanCut(s, ctx, style))) + return true; + s = last + 1; + } + return false; + } + + /// + /// True when rows to , taken one after the + /// other under the header rows, fit one of the fresh boxes by the fit loop's own arithmetic. + /// + private bool RunFitsFresh(LayoutBox[] fresh, double headerHeight, int first, int last) + { + foreach (var box in fresh) + { + var run = headerHeight; + var fits = true; + for (var r = first; r <= last && fits; r++) + { + fits = !(box.Y + run + _rowHeights[r] > box.Bottom + 0.001); + run += _rowHeights[r]; + } + if (fits) return true; + } + return false; + } + /// /// True when row , which did not fit the area, can be cut between its /// lines: the caller supplied the fresh boxes, the row would fit neither of them whole, nothing diff --git a/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs new file mode 100644 index 000000000..5b67a94a2 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs @@ -0,0 +1,225 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements.Table; +using VellumPdf.Layout.Rendering.Table; +using VellumPdf.TestSupport; + +namespace VellumPdf.Layout.Tests; + +/// +/// A table that 2.3.3 refused stays refused, and a table that would need more page continuations +/// than one element may take with its breaks is laid out as 2.3.3 laid it out. "As 2.3.3 laid it +/// out" is the table measured with every cell as one line, which the tests reach through +/// . +/// +public sealed class TableMainRefusalTests +{ + private static TextStyle Helvetica(double size = 10) => new() + { + FontRef = new FontReference(Standard14.Helvetica), + FontSize = size, + }; + + private static string W(int n) => new('W', n); + + private static byte[] Save(Document doc) + { + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + private static int PageCount(byte[] pdf) => + Regex.Matches(Encoding.Latin1.GetString(pdf), @"/Type\s*/Page\b").Count; + + private static string[] Dropped(Document doc) => + [.. doc.Diagnostics + .Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped) + .Select(d => Regex.Match(d.Message, @"row \d+, cell \d+").Value) + .OrderBy(m => int.Parse(Regex.Match(m, @"\d+").Value, CultureInfo.InvariantCulture)) + .ThenBy(m => m, StringComparer.Ordinal)]; + + private static void RequireDejaVu() + { + if (!File.Exists(TableRandomDocuments.DejaVu)) + OracleGate.Unavailable("DejaVuSans.ttf", "DejaVu Sans is needed for an embedded font."); + } + + // ── A table that was refused stays refused ────────────────────────────────── + + /// + /// Two fixed columns of 100pt and an automatic one on a 400x300pt page. The group of rows 0 and + /// 1 holds the 100pt cell that is tall when its column is narrow, and the cell of the automatic + /// column in row 2 is a line of the given width and a break and a short line. Read unbroken + /// that cell is as wide as both lines together, which leaves the fixed columns narrower, so the + /// group is taller than a page leaves; with the break read, the widest line is shorter and the + /// group fits. + /// + private static Document GroupTippedByTheWidthOfAnotherRow(int width) + { + var doc = new Document { PageSize = new PdfRectangle(0, 0, 400, 300), Margins = new EdgeInsets(10) }; + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(100, 100); + t.AddRow().AddCell(new Cell("lorem ipsum dolor sit amet consectetur") { RowSpan = 2 }).AddCell("a"); + t.AddRow().AddCell("b"); + t.AddRow().AddCell("c").AddCell("d").AddCell(W(width) + "\n" + W(4)); + doc.Add(t); + return doc; + } + + private static string RefusalOf(Func build, bool measuredAsOneLine) + { + using var doc = build(); + TableMeasureProbe.Current = new TableMeasureProbe { ReadEveryCellUnbroken = measuredAsOneLine }; + try + { + Save(doc); + return "saved"; + } + catch (InvalidOperationException ex) + { + return ex.Message; + } + finally + { + TableMeasureProbe.Current = null; + } + } + + /// + /// A table that is refused when every cell is measured as one line is refused with the same + /// message, though its breaks, read, leave the group room: the cell of the automatic column is + /// as wide as both its lines together measured as one, which leaves the fixed columns + /// narrower and the group taller than the 280pt a page leaves. + /// + [Theory] + [InlineData(31)] + [InlineData(32)] + [InlineData(34)] + public void ATableThatIsRefusedMeasuredAsOneLineIsRefusedWithTheSameMessage(int width) + { + var oneLine = RefusalOf(() => GroupTippedByTheWidthOfAnotherRow(width), measuredAsOneLine: true); + var decided = RefusalOf(() => GroupTippedByTheWidthOfAnotherRow(width), measuredAsOneLine: false); + + Assert.Contains("RowSpan", oneLine, StringComparison.Ordinal); + Assert.Equal(oneLine, decided); + } + + /// + /// The tables next to those saved measured as one line, and a table with a cell that has to + /// give up its breaks is saved with it reported. + /// + [Theory] + [InlineData(30, 0)] + [InlineData(35, 1)] + [InlineData(38, 1)] + [InlineData(39, 0)] + public void ATableThatSavesMeasuredAsOneLineStillSaves(int width, int reported) + { + using var doc = GroupTippedByTheWidthOfAnotherRow(width); + TableMeasureProbe.Current = new TableMeasureProbe { ReadEveryCellUnbroken = true }; + try + { + Save(doc); + } + finally + { + TableMeasureProbe.Current = null; + } + + using var decided = GroupTippedByTheWidthOfAnotherRow(width); + var bytes = Save(decided); + + Assert.Equal(1, PageCount(bytes)); + Assert.Equal(reported, Dropped(decided).Length); + } + + /// + /// The decision measures a table with every cell as one line to see whether it is refused, and + /// drops that measurement when it is not. A tab measured in an embedded font would add glyph 0 + /// to its subset, and its ToUnicode map would list it, though no tab is drawn. + /// + [Fact] + public void AMeasurementThatIsDroppedAddsNothingToAnEmbeddedFont() + { + RequireDejaVu(); + using var doc = new Document + { + PageSize = new PdfRectangle(0, 0, 300, 400), + Margins = new EdgeInsets(10), + }; + var font = doc.UseTrueTypeFont(File.ReadAllBytes(TableRandomDocuments.DejaVu)); + var t = new TableElement { DefaultCellStyle = new TextStyle { FontRef = font, FontSize = 12 } } + .SetColumnWidths(100, 100); + t.AddRow().AddCell("A\tB").AddCell("line1\nline2"); + doc.Add(t); + + var content = PdfTestUtil.DecompressAllFlatStreams(Save(doc)); + + Assert.DoesNotContain("<0000> ", content, StringComparison.Ordinal); + Assert.Empty(Dropped(doc)); + } + + private static Document Shaped(int seed) + { + var rng = new Random(seed); + var doc = new Document { PageSize = new PdfRectangle(0, 0, 400, 300), Margins = new EdgeInsets(10) }; + var t = new TableElement { DefaultCellStyle = Helvetica() }; + _ = rng.Next(3) switch + { + 0 => t.SetColumnWidths(100, 100), + 1 => t.SetColumnWidths(rng.Next(60, 140), 0, 0), + _ => t.SetColumnWidths(rng.Next(60, 140), rng.Next(60, 140), 0), + }; + var header = rng.Next(3) == 0; + var spanText = string.Join(rng.Next(4) == 0 ? "\n" : " ", Enumerable.Repeat("lorem ipsum", rng.Next(1, 5))); + var row0 = t.AddRow(header); + row0.AddCell(header ? new Cell(spanText) : new Cell(spanText) { RowSpan = 2 }).AddCell("a"); + t.AddRow().AddCell("b"); + var sep = rng.Next(3) switch { 0 => "\n", 1 => "\t", _ => "\r\n" }; + t.AddRow().AddCell("c").AddCell("d").AddCell(W(rng.Next(0, 45)) + sep + W(rng.Next(0, 12))); + if (rng.Next(2) == 0) t.AddRow().AddCell("e\nf").AddCell(W(rng.Next(0, 30)) + "\n" + W(rng.Next(0, 30))); + doc.Add(t); + return doc; + } + + /// + /// A document that is refused with every cell measured as one line is refused: over shaped + /// tables, where most of one family is refused and the other saves, and over the long random + /// tables of header rows, spans and fixed, automatic, zero, negative and NaN widths. + /// + [Fact] + public void ADocumentThatIsRefusedMeasuredAsOneLineIsRefused() + { + RequireDejaVu(); + var refusedShaped = 0; + for (var seed = 0; seed < 600; seed++) + { + var s = seed; + var oneLine = RefusalOf(() => Shaped(s), measuredAsOneLine: true); + if (oneLine == "saved") continue; + refusedShaped++; + Assert.Equal(oneLine, RefusalOf(() => Shaped(s), measuredAsOneLine: false)); + } + + var refusedLong = 0; + for (var seed = 0; seed < 250; seed++) + { + var s = seed; + var oneLine = RefusalOf(() => TableRandomDocuments.Long(s), measuredAsOneLine: true); + if (oneLine == "saved") continue; + refusedLong++; + Assert.Equal(oneLine, RefusalOf(() => TableRandomDocuments.Long(s), measuredAsOneLine: false)); + } + + // The property is not vacuous: each family has tables that are refused measured as one line. + Assert.True(refusedShaped > 20, $"only {refusedShaped} shaped tables are refused measured as one line"); + Assert.True(refusedLong > 20, $"only {refusedLong} long tables are refused measured as one line"); + } +} From cba8e647eb78b48985bb202154e144ed856de84a Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 12:36:09 +0100 Subject: [PATCH 29/48] fix(layout): lay a table out unbroken when its breaks would pass the page limit One element may take 50,000 page continuations. Reading a cell's line feeds as breaks turns a cell into one line per page where the table used to take a few hundred pages, so a table that saved before could stop at the limit. After its first layout the table gives the document a bound on its continuations. Where the bound allows the limit to be reached the document places the element once without drawing, with the keep rules' save and restore of the cursor, and when that reaches the limit it places a table that reads every cell unbroken instead. That table is saved or refused as it was before breaks were read, and each cell it leaves unbroken is reported through CellWhiteSpaceDropped with the reason. --- CHANGELOG.md | 18 +- src/VellumPdf.Layout/Elements/Table/Cell.cs | 15 +- .../Elements/Table/TableElement.cs | 12 +- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 6 +- .../Rendering/DocumentRenderer.cs | 65 +++++++ .../Rendering/IContinuationGuard.cs | 32 +++ .../Rendering/Table/TableRenderer.cs | 92 ++++++++- .../TableMainRefusalTests.cs | 183 ++++++++++++++++++ 8 files changed, 398 insertions(+), 25 deletions(-) create mode 100644 src/VellumPdf.Layout/Rendering/IContinuationGuard.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index ba11f8516..7b7f1cd48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -91,7 +91,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **`LayoutDiagnosticCode.CellWhiteSpaceDropped` (301).** A table cell was wrapped at spaces alone and sized from its whole text, and its tabs and line breaks were left out of what is drawn, because reading its line breaks, or its other control white space as spaces, would have left a - repeated header row or rows joined by a `RowSpan` no room on a page. A warning, so `StrictDiagnostics` saves: the + repeated header row or rows joined by a `RowSpan` no room on a page, or would have taken the table + more page continuations than one element may take. A warning, so `StrictDiagnostics` saves: the text stays, and the words those characters separated run together in the drawing and in extracted text. `Count` is the number of pages on which the cell was drawn from its first line, so a repeated @@ -641,11 +642,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). room with its breaks read. The cells give up their breaks only to save a table that measurement saves. A release that measures the columns a `RowSpan` occupies as they are drawn can save some of these tables. - - A cell with a very large number of lines can be refused where 2.3.3 saved it, because 2.3.3 - drew its line feeds inside one line. One cell of 2,500,000 two-letter words joined by LF, on a - 2000 x 600 pt page in a 1900 pt column, saved in 314 pages on 2.3.3 and now stops at the limit - of 50,000 page continuations with the `InvalidOperationException` that names it. The same cell - of 2,350,047 words saves, in 50,001 pages, and one of 2,350,048 is refused. + - **A table whose breaks would take more than 50,000 page continuations is laid out with every + cell unbroken.** One element may take at most 50,000 page continuations, and reading a cell's + line feeds as breaks can take a table past that where measuring each cell as one line does + not. The table is placed once without drawing when a bound says it could reach the limit. + When it would, every cell that holds control white space is laid out unbroken from the first + page, as the table was measured before breaks were honoured, and the save lists each as + `CellWhiteSpaceDropped`. The table then saves in the pages that measurement takes, or is + refused with the limit's message when that takes more. One cell of 2,350,047 two-letter words + joined by LF, on a 2000 x 600 pt page in a 1900 pt column, keeps its breaks, in 50,001 + pages; one of 2,350,048 is laid out unbroken, in 295, and one of 2,500,000 in 314. - **A repeated header row, or rows joined by a `RowSpan`, keep the one-line layout of their cells when reading the cells' breaks would leave them no room on a page.** Those rows are never cut between their lines, so reading the breaks would turn a table that saved into a too-tall diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 73a31998a..d6ae8f0ad 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -42,8 +42,9 @@ public sealed class Cell /// . /// A cell has no tab stops, so a tab is one space. /// A cell is laid out unbroken, with its tabs and line breaks left out of what is - /// drawn, when reading them would leave a row that cannot be cut no room on a page. This - /// is the one place that states the rule; the other members that mention it point here. The + /// drawn, when reading them would leave a row that cannot be cut no room on a page, or would + /// take the table more page continuations than one element may take. This is the one + /// place that states the rule; the other members that mention it point here. The /// rows that are never cut between their lines are the repeated header rows and the rows /// joined by a . The header rows have no room when they do not fit a /// page, or when they leave a row below them less than one line of one of its cells. A span @@ -82,6 +83,16 @@ public sealed class Cell /// change other rows: the column's width is shared with every row that has a cell in it. The /// groups after it are judged on the heights that result, so every group is judged on the /// heights the decisions before it leave, however many groups the table has. + /// The limit is the 50,000 page continuations of . A table + /// whose line breaks, read, would take more lays every cell out unbroken from its first page, + /// as it was measured before breaks were honoured. It is saved in the pages that measurement + /// takes, and refused with the limit's message when that takes more than the limit too. The + /// save lists each cell that holds control white space as + /// . The count + /// depends on where the table starts: a table that keeps its breaks at the top of a page can + /// give them up when it starts lower and first moves to the next page. Do not pass a + /// cell with more lines than a document can hold and expect them drawn: shorten the text or + /// split the table. /// A table that is refused when every cell is measured as one line is refused, with /// the message that measurement gives. /// throws , the too-tall exception, though every header diff --git a/src/VellumPdf.Layout/Elements/Table/TableElement.cs b/src/VellumPdf.Layout/Elements/Table/TableElement.cs index 2a8819715..c383b2816 100644 --- a/src/VellumPdf.Layout/Elements/Table/TableElement.cs +++ b/src/VellumPdf.Layout/Elements/Table/TableElement.cs @@ -18,7 +18,9 @@ namespace VellumPdf.Layout.Elements.Table; /// rows are all headers has no repeatable header and draws each row once; see /// . /// The table is one element for the page limit described on : a -/// table that needs more than 50,000 page continuations makes the save throw. +/// table that needs more than 50,000 page continuations makes the save throw. A table whose +/// line breaks, read, would need more is laid out with every cell unbroken instead, as +/// says, and the save throws only when it then needs more. /// A row that does not fit the room left on a page, and fits neither box a fresh page /// offers, is cut between its lines and continues on the next page. Those boxes are the page's /// content area under the repeated header rows and inside , so a row that @@ -31,10 +33,10 @@ namespace VellumPdf.Layout.Elements.Table; /// page is a TD, or a TH in a header row, and a cell with no line on the page is an /// empty TD, also in a header row. /// A carriage return or line feed in a cell ends a line, so it makes the row taller. A -/// repeated header row, or rows joined by a , can lose the breaks and -/// tabs of some cells, those of a cell in an automatically sized column among them, and the save -/// lists each as ; -/// says when and which. +/// table can make some cells give up their breaks and tabs, among them cells in rows that are +/// neither header rows nor joined by a , and the save lists each as +/// ; says when +/// and which. /// Every group is judged on the heights the groups before it leave. A header row, or /// a group in an automatically sized column, that gives up a cell can change the width of a /// column the next group is judged by, so the next group is judged on the widths that result, diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index 468995039..9fb5ed24c 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -119,7 +119,8 @@ public enum LayoutDiagnosticCode /// /// A table cell holds a tab, a line break or another control white-space character, and the /// save left it out of what it drew, because reading it would have left a row that cannot be - /// cut no room on a page. + /// cut no room on a page, or would have taken the table more page continuations than one + /// element may take. /// is the number of pages on which the cell was drawn from /// its first line, so a header row that repeats on every page counts once per page, and any /// other cell counts once, however many pages a cut row spans. The message names the row and @@ -131,7 +132,8 @@ public enum LayoutDiagnosticCode /// A cell that keeps its breaks is not reported. /// says which rows, when, and which cells. Do not pass a repeated header row or a span /// group that has no room on a page: put the breaks in rows that can be cut, or shorten the - /// text. + /// text. A cell with more lines than a document can hold is the other case: shorten the text + /// or split the table. /// CellWhiteSpaceDropped = 301, diff --git a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs index 15a8361d8..42fd86511 100644 --- a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs @@ -698,6 +698,15 @@ private void FinishCurrentPage(int totalPages) private int _simFirstPage; private int _keepResolvedUntil; + // An element whose layout may need more page continuations than one element may is placed + // once without drawing to see whether it does (ReachesContinuationLimit). _guarding is set + // while that runs, and _limitReached when the loop it runs would have thrown for the limit. + // The answer depends on the renderer and on the area its first call is offered, so it is kept + // for both passes and for the simulations of the keep rules. + private bool _guarding; + private bool _limitReached; + private Dictionary<(IRenderer Renderer, double Height, bool AtTop), bool>? _continuationVerdicts; + // Set when a run was dropped in the drawing pass; the report is made once its first element is // placed (ReportPendingKeepWithNext). private bool _keepRelaxedPending; @@ -1202,6 +1211,42 @@ private bool RunHolds(int first, int end, bool fromFreshPage) } } + // Places the element on a copy of the cursor, from where the loop is, and answers whether the + // loop would throw for the continuation limit. Nothing is drawn, reported or kept. Anything + // else the placement throws is left for the placement that follows, which throws it again. + private bool ReachesContinuationLimit(IRenderer renderer, double height, bool atTop) + { + var key = (renderer, height, atTop); + if (_continuationVerdicts is not null && _continuationVerdicts.TryGetValue(key, out var known)) + return known; + + var saved = (_measuring, _measureArea, _measureY, _pageIndex, _placedOnPage, _simulating, _simFirstOnly, _simFirstPage, _guarding, _limitReached); + var cursor = Cursor; + var reached = false; + try + { + _measuring = true; + _simulating = true; + _simFirstOnly = false; + _guarding = true; + _limitReached = false; + _measureArea = ContentArea; + _measureY = cursor; + PlaceRenderer(renderer, 0); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + reached = _limitReached; + } + finally + { + (_measuring, _measureArea, _measureY, _pageIndex, _placedOnPage, _simulating, _simFirstOnly, _simFirstPage, _guarding, _limitReached) = saved; + } + + (_continuationVerdicts ??= [])[key] = reached; + return reached; + } + private void PlaceRenderer(IRenderer renderer, int totalPages) { var continuations = 0; @@ -1211,6 +1256,7 @@ private void PlaceRenderer(IRenderer renderer, int totalPages) var keepTogether = renderer is IKeepSource { KeepTogether: true }; var lineCounts = renderer is ParagraphRenderer; var split = false; + var guard = _guarding ? null : renderer as IContinuationGuard; while (true) { if (!_measuring) EnsurePage(); @@ -1220,6 +1266,23 @@ private void PlaceRenderer(IRenderer renderer, int totalPages) var result = CallLayout(renderer, availableArea, lineCounts, atTop: atTop); + // Asked once, after the first call has given the renderer what it needs to bound the + // continuations: an element that fits where it is has none to count. One that would + // reach the limit the way it lays itself out is laid out the other way, from this + // first call on, so it is refused or saved as it was before it had the first. + if (guard is not null) + { + var asked = guard; + guard = null; + if (result.Status != LayoutResult.Outcome.Full + && asked.ContinuationBound > MaxContinuationsPerElement + && ReachesContinuationLimit(renderer, availableArea.Height, atTop)) + { + renderer = asked.WithoutBreaks(); + result = CallLayout(renderer, availableArea, lineCounts, atTop: atTop); + } + } + // Checked on every call until the element has split once, not only on the first: a // Nothing moves the element to the top of the next page, and a keep-together element // that cannot be placed whole there splits there, which is reported the same way. @@ -1292,6 +1355,8 @@ private void PlaceRenderer(IRenderer renderer, int totalPages) if (++continuations > MaxContinuationsPerElement) { + if (_guarding) _limitReached = true; + // 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 diff --git a/src/VellumPdf.Layout/Rendering/IContinuationGuard.cs b/src/VellumPdf.Layout/Rendering/IContinuationGuard.cs new file mode 100644 index 000000000..348fe30b5 --- /dev/null +++ b/src/VellumPdf.Layout/Rendering/IContinuationGuard.cs @@ -0,0 +1,32 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using VellumPdf.Layout.Core; + +namespace VellumPdf.Layout.Rendering; + +/// +/// A renderer with two layouts: the one it uses, which can take more page continuations than one +/// element may, and a second that takes what the table took before the first existed. After the +/// first call the document asks for a bound on the continuations of the first. When the bound +/// allows it to reach the limit, the document places the element once without drawing, and if +/// that reaches the limit it uses the second layout instead. +/// +/// +/// Implement it explicitly. The built-in renderers are public classes, so an implicit +/// implementation would be a new public member. +/// +internal interface IContinuationGuard +{ + /// + /// An upper bound on the page continuations that placing the renderer needs, known once it has + /// been laid out for the first time in the area the document offers. Zero when it knows none. + /// + long ContinuationBound { get; } + + /// + /// A renderer that lays the same element out in the second way, from the first area on. It + /// carries nothing the first layout decided. + /// + IRenderer WithoutBreaks(); +} diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index d6fb316b7..0f343fa45 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -33,7 +33,7 @@ namespace VellumPdf.Layout.Rendering.Table; /// is tagged as a header cell. A table that has a row that is not a header after its leading /// header rows repeats those header rows on every page. /// -public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IPlacementSource +public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IPlacementSource, IContinuationGuard { private readonly TableElement _table; private readonly int _startRow; // first data row index (0-based) @@ -68,6 +68,16 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IP // goes with it. private bool _allUnbroken; + // True for a renderer the document made because laying the table out with its breaks read + // would take more page continuations than one element may: it reads every cell unbroken from + // the start, as the table was measured before breaks were honoured, and says so in the + // diagnostics. Copies carry it. + private bool _readsUnbrokenForTheLimit; + + // An upper bound on the page continuations the decision's layout needs, set where the decision + // is made; see ContinuationBoundOf. + private long _continuationBound; + // What the decision under way has measured of each cell; null outside it. private TableMeasureCache? _measured; @@ -166,6 +176,12 @@ void IPlacementSource.ReportPlacements(PlacementSink sink) internal TableElement Element => _table; + // Explicit, as above. + long IContinuationGuard.ContinuationBound => _continuationBound; + + IRenderer IContinuationGuard.WithoutBreaks() => + new TableRenderer(_table, _startRow) { _continuation = _continuation, _readsUnbrokenForTheLimit = true }; + /// Resolves column widths and row heights, fitting as many rows as possible and splitting at row boundaries on overflow, or between the lines of a row that fits no fresh page. /// /// Overflow splits at a row boundary. A row that does not fit the area is cut between its @@ -184,9 +200,9 @@ void IPlacementSource.ReportPlacements(PlacementSink sink) /// cut keeps cutting under such a context only at the width it was cut at. At another width /// the saved lines are dropped and the row is laid out again from its first line, which /// under a context without the box is not cut. - /// A carriage return or line feed in a cell ends a line. A repeated header row, or rows - /// joined by a , can lose the breaks of some cells, those of a cell - /// in an automatically sized column among them, and the save reports each as + /// A carriage return or line feed in a cell ends a line. A table can make some cells give + /// up their breaks, among them cells in rows that are neither header rows nor joined by a + /// , and the save reports each as /// ; /// says when and which. A context built with the public /// constructor of keeps every break. @@ -296,8 +312,10 @@ public LayoutResult Layout(LayoutContext context) var passesNeeded = !decided && fresh is not null && AnyControlSpace(rows); // A test measures the table as it was before breaks were honoured: every cell as - // one line, with nothing to decide. - if (passesNeeded && TableMeasureProbe.Current is { ReadEveryCellUnbroken: true }) + // one line, with nothing to decide. So does the renderer made for a table whose + // breaks would take it past the limit of page continuations. + if (_readsUnbrokenForTheLimit + || (passesNeeded && TableMeasureProbe.Current is { ReadEveryCellUnbroken: true })) { _allUnbroken = true; passesNeeded = false; @@ -352,6 +370,7 @@ public LayoutResult Layout(LayoutContext context) _measured = null; _content = null; _decidedFor = key; + if (fresh is not null && !_readsUnbrokenForTheLimit) _continuationBound = ContinuationBoundOf(fresh); } } @@ -454,10 +473,11 @@ public LayoutResult Layout(LayoutContext context) _tailSlice = tail, _oneLine = _oneLine, _allUnbroken = _allUnbroken, + _readsUnbrokenForTheLimit = _readsUnbrokenForTheLimit, _decidedFor = _decidedFor, }; var overflow = tail is null - ? new TableRenderer(_table, lastFit + 1) { _continuation = true, _colWidths = _colWidths, _rowHeights = _rowHeights, _oneLine = _oneLine, _allUnbroken = _allUnbroken, _decidedFor = _decidedFor } + ? new TableRenderer(_table, lastFit + 1) { _continuation = true, _colWidths = _colWidths, _rowHeights = _rowHeights, _oneLine = _oneLine, _allUnbroken = _allUnbroken, _readsUnbrokenForTheLimit = _readsUnbrokenForTheLimit, _decidedFor = _decidedFor } : new TableRenderer(_table, tail.Row) { _continuation = true, @@ -467,6 +487,7 @@ public LayoutResult Layout(LayoutContext context) _resumeFrom = tail.Next(), _oneLine = _oneLine, _allUnbroken = _allUnbroken, + _readsUnbrokenForTheLimit = _readsUnbrokenForTheLimit, _decidedFor = _decidedFor, }; return LayoutResult.Partial(_occupied, split, overflow); @@ -1181,6 +1202,51 @@ private static bool FitsFresh(LayoutBox[] fresh, double headerHeight, double hei return false; } + /// + /// An upper bound on the page continuations that laying the table out from + /// _rowHeights and _colWidths takes, over every page. + /// + /// + /// A continuation is a layout call that answers Partial, or Nothing and is retried on the next + /// page. Every Partial takes at least one row, or at least one line of a row cut between its + /// lines, so the Partials number at most the units less one, where a row is one unit unless + /// it fits neither fresh box, when it is cut and counts a unit for each of its lines. A + /// Nothing is followed by a call that makes progress, which is a Partial or the last call, so + /// the Nothings number at most the Partials and one. Together at most twice the units less + /// one. + /// + private long ContinuationBoundOf(LayoutBox[] fresh) + { + var rows = _table.Rows; + var header = FindHeaderRowIndices(rows); + var headerHeight = 0.0; + foreach (var i in header) headerHeight += _rowHeights[i]; + var style = _table.DefaultCellStyle ?? TextStyle.Default; + + var units = 0L; + for (var r = Math.Max(_startRow, header.Count > 0 ? header[^1] + 1 : 0); r < rows.Count; r++) + { + if (FitsFresh(fresh, headerHeight, _rowHeights[r])) + { + units++; + continue; + } + + var lines = 0L; + var cells = rows[r].Cells; + var col = 0; + for (var c = 0; c < cells.Count && col < _colWidths.Length; c++) + { + var cell = cells[c]; + var innerW = ColSpanWidth(col, cell.ColSpan) - cell.Padding.Horizontal; + lines += WordWrapCount(cell.Content, cell.Style ?? style, Math.Max(1, innerW), HonoursBreaks(r, c)); + col += cell.ColSpan; + } + units += Math.Max(1, lines); + } + return (2 * units) - 1; + } + /// /// True when laying the table out from _rowHeights and _colWidths, page after /// page, ends with a page that answers from the top @@ -1443,6 +1509,14 @@ private static string RowRange(int first, int last) => return (first, last); } + private static string DroppedForRoom(long subject) => string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"Table row {subject >> 32}, cell {subject & 0xFFFFFFFF} holds a tab, a line break or another control white-space character that is left out of what is drawn, because reading its line breaks, or its other control white space as spaces, would leave a row that cannot be cut no room on a page. The words it separated run together."); + + private static string DroppedForTheLimit(long subject) => string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"Table row {subject >> 32}, cell {subject & 0xFFFFFFFF} holds a tab, a line break or another control white-space character that is left out of what is drawn, because reading the table's line breaks would take it more page continuations than one element may take. The words it separated run together."); + /// Draws cell backgrounds, borders and text (repeating header rows) and builds the tagged Table struct tree when tagging is enabled. /// /// See . @@ -1745,9 +1819,7 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, ctx.Diagnostics?.Report( LayoutDiagnosticCode.CellWhiteSpaceDropped, ((long)rowIndex << 32) | (uint)cellIndex, - static subject => string.Create( - System.Globalization.CultureInfo.InvariantCulture, - $"Table row {subject >> 32}, cell {subject & 0xFFFFFFFF} holds a tab, a line break or another control white-space character that is left out of what is drawn, because reading its line breaks, or its other control white space as spaces, would leave a row that cannot be cut no room on a page. The words it separated run together."), + _readsUnbrokenForTheLimit ? DroppedForTheLimit : DroppedForRoom, perElement: true); } diff --git a/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs index 5b67a94a2..b93eb3748 100644 --- a/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs @@ -7,6 +7,7 @@ using VellumPdf.Document; using VellumPdf.Fonts; using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; using VellumPdf.Layout.Elements.Table; using VellumPdf.Layout.Rendering.Table; using VellumPdf.TestSupport; @@ -166,6 +167,188 @@ public void AMeasurementThatIsDroppedAddsNothingToAnEmbeddedFont() Assert.Empty(Dropped(doc)); } + // ── A table that would need more page continuations than one element may ──── + + private static readonly DateTimeOffset s_pin = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + private static readonly byte[] s_pinId = [.. Enumerable.Range(1, 16).Select(i => (byte)i)]; + + private static string Words(int n) => string.Join("\n", Enumerable.Repeat("ab", n)); + + /// + /// One cell of two-letter words joined by line feeds, on a page whose + /// content is one line of the cell tall. Read with its breaks the cell is a line to a page, and + /// a page is a continuation. Measured as one line the text is wrapped at the column's width, + /// which is a few hundred words to a line, and the cell takes a few hundred pages. + /// + private static Document OnePageALine(int words, bool footer = false, bool paragraphFirst = false, double columnWidth = 1900) + { + var doc = new Document + { + PageSize = new PdfRectangle(0, 0, 2000, footer ? 60 : 40), + Margins = new EdgeInsets(10), + Timestamp = s_pin, + DocumentId = s_pinId, + }; + if (footer) doc.SetFooter("{page}", new TextStyle { FontRef = new FontReference(Standard14.Helvetica), FontSize = 8 }); + if (paragraphFirst) doc.Add(new Paragraph("x", Helvetica())); + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(columnWidth); + t.AddRow().AddCell(Words(words)); + doc.Add(t); + return doc; + } + + private static byte[] SaveMeasuredAsOneLine(Func build) + { + using var doc = build(); + TableMeasureProbe.Current = new TableMeasureProbe { ReadEveryCellUnbroken = true }; + try + { + return Save(doc); + } + finally + { + TableMeasureProbe.Current = null; + } + } + + /// + /// A cell that takes the limit of 50,000 page continuations exactly keeps its breaks: a page + /// to a line, 50,001 pages, and nothing is given up. + /// + [Fact] + public void ATableThatTakesExactlyTheLimitKeepsItsBreaks() + { + using var doc = OnePageALine(50_001); + + var bytes = Save(doc); + + Assert.Equal(50_001, PageCount(bytes)); + Assert.Empty(Dropped(doc)); + } + + /// + /// A cell that would take one more is laid out as it was when every cell was measured as one + /// line: the same bytes that measurement saves, and the cell is reported with the reason. + /// + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + public void ATableThatWouldTakeOneContinuationTooManyIsLaidOutAsOneLine(bool footer, bool paragraphFirst) + { + // After a paragraph that leaves no room for a line, the table moves to the next page, + // which is a continuation of its own, so 50,001 lines are one too many there. + var words = paragraphFirst ? 50_001 : 50_002; + using var doc = OnePageALine(words, footer, paragraphFirst); + + var bytes = Save(doc); + + var expected = SaveMeasuredAsOneLine(() => OnePageALine(words, footer, paragraphFirst)); + Assert.Equal(expected, bytes); + Assert.True(PageCount(bytes) < 1000, $"{PageCount(bytes)} pages"); + Assert.Equal(["row 0, cell 0"], Dropped(doc)); + var report = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped); + Assert.Contains("more page continuations than one element may take", report.Message, StringComparison.Ordinal); + } + + /// + /// The same cell measured as one line takes the page continuations too, and is refused with the + /// message that names the limit, as it is when it is measured as one line. + /// + [Fact] + public void ATableThatTakesTooManyContinuationsMeasuredAsOneLineIsRefusedWithThatMessage() + { + // A column 30pt wide wraps the text into lines of three characters. + var oneLine = RefusalOf(() => OnePageALine(120_000, columnWidth: 30), measuredAsOneLine: true); + var decided = RefusalOf(() => OnePageALine(120_000, columnWidth: 30), measuredAsOneLine: false); + + Assert.Contains("more than 50000 page continuations", oneLine, StringComparison.Ordinal); + Assert.Equal(oneLine, decided); + } + + /// + /// The cell of 2,350,048 two-letter words in a 1900pt column on a 2000 x 600pt page, which + /// saved in 295 pages as one line and takes more than 50,000 pages with its breaks. + /// + [Fact] + public void ALargeCellThatWouldTakeMoreThanTheLimitIsLaidOutAsOneLine() + { + using var doc = new Document + { + PageSize = new PdfRectangle(0, 0, 2000, 600), + Margins = new EdgeInsets(10), + Timestamp = s_pin, + DocumentId = s_pinId, + }; + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(1900); + t.AddRow().AddCell(Words(2_350_048)); + doc.Add(t); + + var bytes = Save(doc); + + Assert.Equal(295, PageCount(bytes)); + Assert.Equal(["row 0, cell 0"], Dropped(doc)); + } + + /// + /// The bound the document asks for is never below the continuations a table takes: over random + /// tables on short pages, where rows are cut between their lines, and rows and groups move to + /// the next page. + /// + [Fact] + public void TheContinuationBoundIsNeverBelowTheContinuationsATableTakes() + { + var most = 0L; + for (var seed = 0; seed < 400; seed++) + { + var rng = new Random(seed); + var area = new LayoutBox(10, 10, rng.Next(150, 500), rng.Next(60, 200)); + var t = new TableElement { DefaultCellStyle = Helvetica() }; + var cols = rng.Next(1, 4); + if (rng.Next(2) == 0) t.SetColumnWidths([.. Enumerable.Range(0, cols).Select(_ => (double)rng.Next(30, 120))]); + for (var r = rng.Next(1, 30); r > 0; r--) + { + var row = t.AddRow(isHeader: r == 1 && rng.Next(4) == 0); + for (var c = 0; c < cols; c++) + { + var lines = rng.Next(1, rng.Next(6) == 0 ? 40 : 4); + var text = string.Join("\n", Enumerable.Range(0, lines).Select(_ => "w" + W(rng.Next(1, 12)))); + row.AddCell(new Cell(text) { RowSpan = rng.Next(8) == 0 ? 2 : 1 }); + } + } + + // Laid out the way the document does: a Partial each time, the overflow in the area of + // the next page. + var ctx = new LayoutContext(area) { FreshPageArea = area }; + IRenderer renderer = new TableRenderer(t); + var continuations = 0L; + long bound; + try + { + var result = renderer.Layout(ctx); + bound = ((Rendering.IContinuationGuard)renderer).ContinuationBound; + while (result.Status == LayoutResult.Outcome.Partial) + { + continuations++; + renderer = result.OverflowRenderer!; + result = renderer.Layout(ctx); + } + + if (result.Status == LayoutResult.Outcome.Nothing) continue; + } + catch (InvalidOperationException) + { + continue; + } + + Assert.True(bound >= continuations, $"seed {seed}: bound {bound}, continuations {continuations}"); + most = Math.Max(most, continuations); + } + + // Not vacuous: tables here take many pages. + Assert.True(most > 10, $"the most continuations over the tables was {most}"); + } + private static Document Shaped(int seed) { var rng = new Random(seed); From c7babb59f91598f8ad460a67335eece41adec0eb Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 12:36:52 +0100 Subject: [PATCH 30/48] docs(layout): say which headers and groups the last step makes as tall as before The last step lays out every cell in an automatic column that holds control white space unbroken, which gives each header or group that still had no room the width and height it had when every cell was one line. A group that fits keeps its breaks, so it can be taller than that; the sentences said the header and the groups were as tall. --- CHANGELOG.md | 3 ++- src/VellumPdf.Layout/Elements/Table/Cell.cs | 6 +++--- src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs | 3 ++- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b7f1cd48..cc89df231 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -671,7 +671,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). or a group that still has no room once those cells have given up their breaks makes every cell in an automatic column that holds control white space give up its breaks as well, because the width of every column follows from those cells. With those cells unbroken the columns are - as wide as 2.3.3 made them, and the header and the groups as tall. In a table with two 100pt + as wide as 2.3.3 made them, and each header or group that still had no room is as tall as + 2.3.3 made it; a group that fits keeps its breaks. In a table with two 100pt columns and an automatic one, a group of two rows is 424pt tall on a page that leaves 280pt while a cell of the automatic column in a third row keeps its line break, and 100pt without it. A span declared in a header row makes no group of the data rows under it, because a page may diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index d6ae8f0ad..e4526b7db 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -76,9 +76,9 @@ public sealed class Cell /// cells of the automatic columns, whichever rows they are in, so a cell in a column that no /// cell of the group is in can still have narrowed the group's columns by the width its /// breaks leave. With all of those cells unbroken every column is as wide as when the table - /// measured each cell as one line, and the header rows and the groups are as tall as that - /// measured them, so one of them is refused only if it was too tall measured so. A cell no - /// step reaches keeps its breaks. + /// measured each cell as one line, and each header or group that still had no room is as tall + /// as that measured it, so one of them is refused only if it was too tall measured so. A + /// group that fits keeps its breaks, and so does a cell no step reaches. /// A header row, or a group in an automatically sized column, that gives up a cell can /// change other rows: the column's width is shared with every row that has a cell in it. The /// groups after it are judged on the heights that result, so every group is judged on the diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 0f343fa45..822c10260 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -999,7 +999,8 @@ void Reach(int from, int to) // that is reached can be what made the columns too narrow: the widest line of it is // narrower than its whole text, so reading its breaks leaves less to share out than 2.3.3 // measured. The last step reads every such cell unbroken (see Cell.Content), which gives - // the widths, and so the heights, 2.3.3 measured for the header and the groups. + // the widths 2.3.3 measured, and the heights it measured for each header or group that + // still has no room. A group that fits keeps its breaks, so it can be taller than that. return found ?? (exhausted ? CollectAutoColumnControlSpace() : null); } From e163283338ff38eb3f3bcc9618cb155079f2e2b5 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 12:36:57 +0100 Subject: [PATCH 31/48] docs(changelog): say what the raised column widths decide The widths kept for the pass, raised by a step, decide whether the step moves a column. A step that ends the pass is followed by a measurement of the whole table from what the cells kept, and a fixed column's step computes none. --- CHANGELOG.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc89df231..1aaf79e6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -681,9 +681,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **Every group is judged in order, and the decision keeps what each cell measures.** A table that gives up cells in several groups keeps each cell's widest word and widest line per mode and its line count with the interval of column widths it holds over, a word broken at its - characters included. After a step it takes the column widths from the widths kept for the - pass, which the step raises. A step that gives up only cells in the group's own rows, and - leaves every column width as it was, does not end the pass, and a table resolves its grid + characters included. To decide whether a step that gives up cells in an automatic column + moves a column, it raises the widths kept for the pass by what the step's cells contribute, + and measures the table again when a cell would contribute less. A step that gives up only + cells in the group's own rows, and leaves every column width as it was, does not end the + pass. A step that does move a column, or reaches a row outside the group, ends it, and the + next pass measures the whole table from what the cells measured. A table resolves its grid once for all its pages. No limit on the number of measurements applies, so a group is judged on the heights the groups before it leave whatever their number. Measured in Release on net10.0, one run each, against 2.3.3 on the same tables: 400 groups that each change the From 71cc3c5806905cd30cc648c2cffec06f681f4977 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 12:48:47 +0100 Subject: [PATCH 32/48] perf(layout): keep a table of short rows out of the continuation check The bound on a table's page continuations counted two for every unit, so a table of 26,000 ordinary rows was placed twice to find out that it takes a few thousand pages. When no row is cut, two pieces in a row are taller together than what a page leaves under the header, so the bound also follows from the rows' heights, and the check runs only for tables that can reach the limit. --- .../Rendering/Table/TableRenderer.cs | 24 ++++- .../TableMainRefusalTests.cs | 102 ++++++++++++------ 2 files changed, 90 insertions(+), 36 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 822c10260..98d8012b4 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -1215,6 +1215,13 @@ private static bool FitsFresh(LayoutBox[] fresh, double headerHeight, double hei /// Nothing is followed by a call that makes progress, which is a Partial or the last call, so /// the Nothings number at most the Partials and one. Together at most twice the units less /// one. + /// When no row is cut, each page but the first is filled until the next row, or run of + /// rows that is never split, does not fit, so two pieces in a row are taller together than + /// what a page leaves under the header rows. Over the pieces after the first that gives at + /// most 2H / A pieces more than one, where H is the height of all the rows and + /// A what the smaller fresh box leaves under the header, so at most + /// 3 + 4H / A continuations. A table of many short rows takes far fewer than its + /// units. /// private long ContinuationBoundOf(LayoutBox[] fresh) { @@ -1225,14 +1232,18 @@ private long ContinuationBoundOf(LayoutBox[] fresh) var style = _table.DefaultCellStyle ?? TextStyle.Default; var units = 0L; + var height = 0.0; + var cutAny = false; for (var r = Math.Max(_startRow, header.Count > 0 ? header[^1] + 1 : 0); r < rows.Count; r++) { if (FitsFresh(fresh, headerHeight, _rowHeights[r])) { units++; + height += _rowHeights[r]; continue; } + cutAny = true; var lines = 0L; var cells = rows[r].Cells; var col = 0; @@ -1245,7 +1256,18 @@ private long ContinuationBoundOf(LayoutBox[] fresh) } units += Math.Max(1, lines); } - return (2 * units) - 1; + + var bound = (2 * units) - 1; + if (!cutAny) + { + var room = Math.Min(fresh[0].Bottom - fresh[0].Y, fresh[1].Bottom - fresh[1].Y) - headerHeight - 0.001; + if (room > 0 && double.IsFinite(height)) + { + var byHeight = Math.Ceiling(3 + (4 * height / room)); + if (byHeight < bound) bound = (long)byHeight; + } + } + return bound; } /// diff --git a/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs index b93eb3748..bfef6a1ba 100644 --- a/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs @@ -290,65 +290,97 @@ public void ALargeCellThatWouldTakeMoreThanTheLimitIsLaidOutAsOneLine() Assert.Equal(["row 0, cell 0"], Dropped(doc)); } + /// + /// What a table that is laid out page by page takes: the bound the renderer reports after its + /// first layout, and the continuations of laying it out the way the document does, a Partial + /// each time with the overflow in the area of the next page. Null when the table is refused. + /// + private static (long Bound, long Continuations)? BoundAndContinuations(TableElement t, LayoutBox area) + { + var ctx = new LayoutContext(area) { FreshPageArea = area }; + IRenderer renderer = new TableRenderer(t); + var continuations = 0L; + try + { + var result = renderer.Layout(ctx); + var bound = ((Rendering.IContinuationGuard)renderer).ContinuationBound; + while (result.Status == LayoutResult.Outcome.Partial) + { + continuations++; + renderer = result.OverflowRenderer!; + result = renderer.Layout(ctx); + } + + return result.Status == LayoutResult.Outcome.Nothing ? null : (bound, continuations); + } + catch (InvalidOperationException) + { + return null; + } + } + /// /// The bound the document asks for is never below the continuations a table takes: over random - /// tables on short pages, where rows are cut between their lines, and rows and groups move to - /// the next page. + /// tables on short pages, where rows are cut between their lines and rows and groups move to + /// the next page, and over tables of short rows on taller ones, where none is cut and the + /// bound follows the heights. /// - [Fact] - public void TheContinuationBoundIsNeverBelowTheContinuationsATableTakes() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void TheContinuationBoundIsNeverBelowTheContinuationsATableTakes(bool shortRows) { var most = 0L; - for (var seed = 0; seed < 400; seed++) + var checkedTables = 0; + for (var seed = 0; seed < 500; seed++) { var rng = new Random(seed); - var area = new LayoutBox(10, 10, rng.Next(150, 500), rng.Next(60, 200)); + var area = shortRows + ? new LayoutBox(10, 10, rng.Next(150, 500), rng.Next(150, 500)) + : new LayoutBox(10, 10, rng.Next(150, 500), rng.Next(60, 200)); var t = new TableElement { DefaultCellStyle = Helvetica() }; var cols = rng.Next(1, 4); if (rng.Next(2) == 0) t.SetColumnWidths([.. Enumerable.Range(0, cols).Select(_ => (double)rng.Next(30, 120))]); - for (var r = rng.Next(1, 30); r > 0; r--) + for (var r = rng.Next(1, shortRows ? 400 : 30); r > 0; r--) { var row = t.AddRow(isHeader: r == 1 && rng.Next(4) == 0); for (var c = 0; c < cols; c++) { - var lines = rng.Next(1, rng.Next(6) == 0 ? 40 : 4); + var lines = rng.Next(1, shortRows ? 3 : rng.Next(6) == 0 ? 40 : 4); var text = string.Join("\n", Enumerable.Range(0, lines).Select(_ => "w" + W(rng.Next(1, 12)))); row.AddCell(new Cell(text) { RowSpan = rng.Next(8) == 0 ? 2 : 1 }); } } - // Laid out the way the document does: a Partial each time, the overflow in the area of - // the next page. - var ctx = new LayoutContext(area) { FreshPageArea = area }; - IRenderer renderer = new TableRenderer(t); - var continuations = 0L; - long bound; - try - { - var result = renderer.Layout(ctx); - bound = ((Rendering.IContinuationGuard)renderer).ContinuationBound; - while (result.Status == LayoutResult.Outcome.Partial) - { - continuations++; - renderer = result.OverflowRenderer!; - result = renderer.Layout(ctx); - } - - if (result.Status == LayoutResult.Outcome.Nothing) continue; - } - catch (InvalidOperationException) - { - continue; - } - - Assert.True(bound >= continuations, $"seed {seed}: bound {bound}, continuations {continuations}"); - most = Math.Max(most, continuations); + if (BoundAndContinuations(t, area) is not { } taken) continue; + checkedTables++; + Assert.True(taken.Bound >= taken.Continuations, $"seed {seed}: bound {taken.Bound}, continuations {taken.Continuations}"); + most = Math.Max(most, taken.Continuations); } - // Not vacuous: tables here take many pages. + // Not vacuous: a good share of the tables here are laid out, and take many pages. + Assert.True(checkedTables > 100, $"only {checkedTables} tables were laid out"); Assert.True(most > 10, $"the most continuations over the tables was {most}"); } + /// + /// A table of 30,000 rows that takes a few thousand pages is far below the limit, and the + /// bound says so, so the document does not place it a second time to find out. + /// + [Fact] + public void TheBoundOfAManyRowTableThatTakesFewPagesIsBelowTheLimit() + { + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(100, 100); + for (var i = 0; i < 30_000; i++) t.AddRow().AddCell("a\nb").AddCell("c"); + var area = new LayoutBox(10, 10, 580, 780); + + var taken = BoundAndContinuations(t, area); + + Assert.NotNull(taken); + Assert.InRange(taken.Value.Continuations, 1_000, 5_000); + Assert.InRange(taken.Value.Bound, taken.Value.Continuations, 50_000); + } + private static Document Shaped(int seed) { var rng = new Random(seed); From 8733447a0f6e7bc4babe925e2b01e083a5d2299f Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 13:16:12 +0100 Subject: [PATCH 33/48] refactor(layout): carry a table's decision to later pages in one place The three renderers a layout hands on each copied the decision field by field, and a copy that missed one went unnoticed. The continuation verdict is asked again rather than kept: it depends on where the element starts, and a key that said so had no test that could tell it from a wrong one. The refusal property now draws tall header rows too. --- .../Rendering/DocumentRenderer.cs | 14 ++----- .../Rendering/Table/TableRenderer.cs | 37 ++++++++++--------- .../TableMainRefusalTests.cs | 2 +- 3 files changed, 25 insertions(+), 28 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs index 42fd86511..7af8597ed 100644 --- a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs @@ -701,11 +701,10 @@ private void FinishCurrentPage(int totalPages) // An element whose layout may need more page continuations than one element may is placed // once without drawing to see whether it does (ReachesContinuationLimit). _guarding is set // while that runs, and _limitReached when the loop it runs would have thrown for the limit. - // The answer depends on the renderer and on the area its first call is offered, so it is kept - // for both passes and for the simulations of the keep rules. + // The answer is asked again by each pass and by each simulation of the keep rules, because it + // depends on where the element starts. private bool _guarding; private bool _limitReached; - private Dictionary<(IRenderer Renderer, double Height, bool AtTop), bool>? _continuationVerdicts; // Set when a run was dropped in the drawing pass; the report is made once its first element is // placed (ReportPendingKeepWithNext). @@ -1214,12 +1213,8 @@ private bool RunHolds(int first, int end, bool fromFreshPage) // Places the element on a copy of the cursor, from where the loop is, and answers whether the // loop would throw for the continuation limit. Nothing is drawn, reported or kept. Anything // else the placement throws is left for the placement that follows, which throws it again. - private bool ReachesContinuationLimit(IRenderer renderer, double height, bool atTop) + private bool ReachesContinuationLimit(IRenderer renderer) { - var key = (renderer, height, atTop); - if (_continuationVerdicts is not null && _continuationVerdicts.TryGetValue(key, out var known)) - return known; - var saved = (_measuring, _measureArea, _measureY, _pageIndex, _placedOnPage, _simulating, _simFirstOnly, _simFirstPage, _guarding, _limitReached); var cursor = Cursor; var reached = false; @@ -1243,7 +1238,6 @@ private bool ReachesContinuationLimit(IRenderer renderer, double height, bool at (_measuring, _measureArea, _measureY, _pageIndex, _placedOnPage, _simulating, _simFirstOnly, _simFirstPage, _guarding, _limitReached) = saved; } - (_continuationVerdicts ??= [])[key] = reached; return reached; } @@ -1276,7 +1270,7 @@ private void PlaceRenderer(IRenderer renderer, int totalPages) guard = null; if (result.Status != LayoutResult.Outcome.Full && asked.ContinuationBound > MaxContinuationsPerElement - && ReachesContinuationLimit(renderer, availableArea.Height, atTop)) + && ReachesContinuationLimit(renderer)) { renderer = asked.WithoutBreaks(); result = CallLayout(renderer, availableArea, lineCounts, atTop: atTop); diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 98d8012b4..78f5a8812 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -463,36 +463,39 @@ public LayoutResult Layout(LayoutContext context) return LayoutResult.Full(_occupied); // Partial - var split = new TableRenderer(_table, _startRow) + var split = Carrying(new TableRenderer(_table, _startRow) { _continuation = _continuation, - _colWidths = _colWidths, - _rowHeights = _rowHeights, _occupied = _occupied, _headSlice = head, _tailSlice = tail, - _oneLine = _oneLine, - _allUnbroken = _allUnbroken, - _readsUnbrokenForTheLimit = _readsUnbrokenForTheLimit, - _decidedFor = _decidedFor, - }; + }); var overflow = tail is null - ? new TableRenderer(_table, lastFit + 1) { _continuation = true, _colWidths = _colWidths, _rowHeights = _rowHeights, _oneLine = _oneLine, _allUnbroken = _allUnbroken, _readsUnbrokenForTheLimit = _readsUnbrokenForTheLimit, _decidedFor = _decidedFor } - : new TableRenderer(_table, tail.Row) + ? Carrying(new TableRenderer(_table, lastFit + 1) { _continuation = true }) + : Carrying(new TableRenderer(_table, tail.Row) { _continuation = true, - _colWidths = _colWidths, - _rowHeights = _rowHeights, _resumeLines = tail.Source, _resumeFrom = tail.Next(), - _oneLine = _oneLine, - _allUnbroken = _allUnbroken, - _readsUnbrokenForTheLimit = _readsUnbrokenForTheLimit, - _decidedFor = _decidedFor, - }; + }); return LayoutResult.Partial(_occupied, split, overflow); } + /// + /// Gives a renderer for a later page what this layout decided: the grid, the heights, the + /// cells read unbroken and the reason they are, with the key they were decided for. + /// + private TableRenderer Carrying(TableRenderer next) + { + next._colWidths = _colWidths; + next._rowHeights = _rowHeights; + next._oneLine = _oneLine; + next._allUnbroken = _allUnbroken; + next._readsUnbrokenForTheLimit = _readsUnbrokenForTheLimit; + next._decidedFor = _decidedFor; + return next; + } + /// /// Resolves the column widths and every row's height, reading the breaks of the cells in /// _oneLine unbroken. The checks run in the order the exceptions are documented in. diff --git a/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs index bfef6a1ba..e9d321b10 100644 --- a/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs @@ -393,7 +393,7 @@ private static Document Shaped(int seed) _ => t.SetColumnWidths(rng.Next(60, 140), rng.Next(60, 140), 0), }; var header = rng.Next(3) == 0; - var spanText = string.Join(rng.Next(4) == 0 ? "\n" : " ", Enumerable.Repeat("lorem ipsum", rng.Next(1, 5))); + var spanText = string.Join(rng.Next(4) == 0 ? "\n" : " ", Enumerable.Repeat("lorem ipsum", rng.Next(1, header ? 60 : 5))); var row0 = t.AddRow(header); row0.AddCell(header ? new Cell(spanText) : new Cell(spanText) { RowSpan = 2 }).AddCell("a"); t.AddRow().AddCell("b"); From ce86ce7cde2df988f2d8fd638a75718adca32a27 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 13:18:03 +0100 Subject: [PATCH 34/48] refactor(layout): drop a header check the run check already makes Header rows that do not fit a page leave every run of rows without room, so the refusal check needs no test of its own for them; no test could tell the two apart. --- src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 78f5a8812..f6cdb7386 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -1281,11 +1281,11 @@ private long ContinuationBoundOf(LayoutBox[] fresh) /// /// The layout answers Nothing where no row fits the page it is given and the first row cannot /// be cut. It is given a fresh page after every break, and a break falls only where - /// allows one, so the layout is refused exactly when - /// the header rows do not fit a page, or a run of rows it never breaks inside does not fit - /// one, and the run is not a single row that can be cut between its lines. Fitting is the fit - /// loop's own test, row by row on the running height, on each of the two boxes a fresh page - /// can offer. + /// allows one, so the layout is refused exactly when a + /// run of rows it never breaks inside does not fit a page under the header rows, and the run + /// is not a single row that can be cut between its lines. Header rows that do not fit a page + /// leave every run without room and are the same case. Fitting is the fit loop's own test, + /// row by row on the running height, on each of the two boxes a fresh page can offer. /// private bool RefusedOnAFreshPage(LayoutBox[] fresh, TextStyle style) { @@ -1297,7 +1297,6 @@ private bool RefusedOnAFreshPage(LayoutBox[] fresh, TextStyle style) var first = Math.Max(_startRow, lastHeaderRow); if (first >= rows.Count) return false; - if (header.Count > 0 && !FitsFresh(fresh, 0, headerHeight)) return true; var blocked = BuildRowspanBlockedSet(rows, lastHeaderRow); var ctx = new RefusalContext(fresh, header, headerHeight, lastHeaderRow); From 1bbe9d38cc20dac526bf17fea098bc490cfb156c Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 20:52:55 +0100 Subject: [PATCH 35/48] fix(layout): decide a table's limit fallback through the shared mechanism The table now reports a bound to the document and the document decides, instead of the table running its own placement. The bound is the larger of the grid that keeps the breaks and the grid that reads every cell unbroken, so a table whose unbroken layout alone reaches the limit stays refused with the message that layout gives, as it was in 2.3.3. A table laid out under a context the document did not address to it (a caller's renderer that forwards here, WithArea, the public constructor) is its own twin: it reads every cell unbroken and reports nothing, so the document's limit holds however the table is reached. Its Draw and ReportPlacements forward to the twin that laid it out, and the fallback is reported only for a twin the document chose. The guard interface, the probe and the two fields in DocumentRenderer are gone; the mechanism's limit and verdict memo replace them. The public XML documentation of IRenderer.Layout, TableRenderer.Layout, TableElement, Cell.Content and LayoutContext.WithArea says what a table you lay out yourself does. The Kernel method that measures without registering has a direct test, and four comment lines are rewrapped. --- CHANGELOG.md | 26 ++- src/VellumPdf.Layout/Core/IRenderer.cs | 7 + src/VellumPdf.Layout/Core/LayoutContext.cs | 4 +- src/VellumPdf.Layout/Elements/BandTemplate.cs | 4 +- src/VellumPdf.Layout/Elements/RunningBand.cs | 9 +- src/VellumPdf.Layout/Elements/Table/Cell.cs | 11 +- .../Elements/Table/TableElement.cs | 6 + .../Rendering/IContinuationGuard.cs | 32 --- .../Rendering/Table/TableMeasureCache.cs | 4 +- .../Rendering/Table/TableRenderer.cs | 119 +++++++++-- .../PeekGlyphIdTests.cs | 21 ++ .../ContinuationSupport.cs | 3 +- .../TableCellBreakTests.cs | 33 ++- .../TableContinuationLimitTests.cs | 196 ++++++++++++++++++ .../TableMainRefusalTests.cs | 20 +- 15 files changed, 409 insertions(+), 86 deletions(-) delete mode 100644 src/VellumPdf.Layout/Rendering/IContinuationGuard.cs create mode 100644 tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index be93aecf5..3f4b1fa88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -690,13 +690,25 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **A table whose breaks would take more than 50,000 page continuations is laid out with every cell unbroken.** One element may take at most 50,000 page continuations, and reading a cell's line feeds as breaks can take a table past that where measuring each cell as one line does - not. The table is placed once without drawing when a bound says it could reach the limit. - When it would, every cell that holds control white space is laid out unbroken from the first - page, as the table was measured before breaks were honoured, and the save lists each as - `CellWhiteSpaceDropped`. The table then saves in the pages that measurement takes, or is - refused with the limit's message when that takes more. One cell of 2,350,047 two-letter words - joined by LF, on a 2000 x 600 pt page in a 1900 pt column, keeps its breaks, in 50,001 - pages; one of 2,350,048 is laid out unbroken, in 295, and one of 2,500,000 in 314. + not. The table reports an upper bound on its continuations to the document, over both ways of + laying it out: with its breaks read, and with every cell unbroken. When that bound could reach + the limit, the document places the table without drawing in each way, and the verdict is kept + for each place the table starts, so each start is tried once however many passes and keep + rules ask. When the unbroken layout reaches the limit the table is refused with the message + that layout gives, as it was in 2.3.3, though its breaks would take fewer pages; when the + layout that reads the breaks would, every cell that holds control white space is laid out + unbroken from the first page, as the table was measured before breaks were honoured, and the + save lists each as `CellWhiteSpaceDropped`. The table then saves in the pages that measurement + takes, or is refused with the limit's message when that takes more. One cell of 2,350,047 + two-letter words joined by LF, on a 2000 x 600 pt page in a 1900 pt column, keeps its breaks, + in 50,001 pages; one of 2,350,048 is laid out unbroken, in 295, and one of 2,500,000 in 314. + - **A table is laid out with its breaks read only where the document lays it out.** A + `TableRenderer` that a renderer of yours holds and forwards `Layout` to, or that you lay out + with a `LayoutContext` you build or narrow with `WithArea`, reads every cell unbroken and + reports nothing, as the table did before breaks were honoured, so its pages and its refusals + are those of that layout and not of the document's, however many lines its cells hold. Such a + renderer's `Draw` must forward to the same table. `IRenderer.Layout`, `TableRenderer.Layout` and + `TableElement` say so. - **A repeated header row, or rows joined by a `RowSpan`, keep the one-line layout of their cells when reading the cells' breaks would leave them no room on a page.** Those rows are never cut between their lines, so reading the breaks would turn a table that saved into a too-tall diff --git a/src/VellumPdf.Layout/Core/IRenderer.cs b/src/VellumPdf.Layout/Core/IRenderer.cs index ad8e3b2ef..7c043083e 100644 --- a/src/VellumPdf.Layout/Core/IRenderer.cs +++ b/src/VellumPdf.Layout/Core/IRenderer.cs @@ -50,6 +50,13 @@ public interface IRenderer /// that returns Nothing for exactly the content area's height and fits the one step /// shorter was saved by an earlier build on a geometry where the shorter height was offered /// first; the save now throws for it. + /// A built-in renderer you call from yours lays out as it did before a fix that + /// would change the continuation limit's verdict. A + /// reads the breaks of its + /// cells only when the document called it, so one that your forwards to + /// reads every cell unbroken (#679); see + /// . Your must + /// forward to the same renderer. /// /// /// Raised from and the other diff --git a/src/VellumPdf.Layout/Core/LayoutContext.cs b/src/VellumPdf.Layout/Core/LayoutContext.cs index 30f497b7b..09e2513ec 100644 --- a/src/VellumPdf.Layout/Core/LayoutContext.cs +++ b/src/VellumPdf.Layout/Core/LayoutContext.cs @@ -164,7 +164,9 @@ public LayoutContext(LayoutBox area, double contentTop = 0) /// the public constructor. The two flags the document sets for its own paragraphs, that the area /// is a page top and that a paragraph reads its line counts, are not copied: a smaller area is /// not known to be a page top, and a renderer that wraps a paragraph renderer places as many - /// lines as fit. + /// lines as fit. A built-in renderer that lays out differently when the document lays it out, + /// such as , lays out as it did + /// before that fix under the copy; see . /// public LayoutContext WithArea(LayoutBox area) => new(area, ContentTop) { FreshPageArea = FreshPageArea }; } diff --git a/src/VellumPdf.Layout/Elements/BandTemplate.cs b/src/VellumPdf.Layout/Elements/BandTemplate.cs index aa11172bc..ea61d5051 100644 --- a/src/VellumPdf.Layout/Elements/BandTemplate.cs +++ b/src/VellumPdf.Layout/Elements/BandTemplate.cs @@ -191,8 +191,8 @@ internal sealed class BandText internal void Reset(int pageNumber, int totalPages, string? pageLabel = null, string? chapter = null) { // The label is caller text, so a tab, a line break or a form feed in it is a space, as it - // is in the template's own text; the replacement keeps the length, so what is measured is what - // is drawn. + // is in the template's own text; the replacement keeps the length, so what is measured is + // what is drawn. _values[(int)BandToken.Page] = pageLabel is null ? pageNumber.ToString(System.Globalization.CultureInfo.InvariantCulture) : LayoutText.ControlSpacesToSpaces(pageLabel); diff --git a/src/VellumPdf.Layout/Elements/RunningBand.cs b/src/VellumPdf.Layout/Elements/RunningBand.cs index 1002ba305..2cbbd2320 100644 --- a/src/VellumPdf.Layout/Elements/RunningBand.cs +++ b/src/VellumPdf.Layout/Elements/RunningBand.cs @@ -81,9 +81,9 @@ public sealed class RunningBand /// character reaches the font from it. The same holds for the text a /// prints for {page}. A control character that is not white /// space, such as U+0001, is written as it is. - /// Not checked when it is set: the constructor stores a null template, and the save throws - /// where the band is first drawn. A template that does not - /// fit the content box is truncated, and refused only in strict mode; + /// Not checked when it is set: the constructor stores a null template, and the save + /// throws where the band is first drawn. A template that + /// does not fit the content box is truncated, and refused only in strict mode; /// says when it /// counts as not fitting. The cut is reported through Document.BandTruncations, /// DocumentRenderer.BandTruncations and, with error severity, as @@ -294,7 +294,8 @@ public RunningBand(string template, TextStyle? style = null, HorizontalAlignment /// The string returned is not always what a save draws. A tab, a line break, a /// form feed or another white-space control character in the template, and in a page label, is /// returned as written, where a save draws each as one space; see . - /// A caller that compares this string with the text of a drawn band sees that difference. + /// A caller that compares this string with the text of a drawn band sees that + /// difference. /// This builds the whole text, so its cost is the template's length. A save does not call /// it: the save resolves a template as it draws, and its cost per page follows the characters /// that fit the content width, as describes. diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index e4526b7db..185a3db77 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -58,8 +58,9 @@ public sealed class Cell /// measured at the width its font gives it and left out of what is drawn. The words they /// separated run together in the drawing and in extracted text, and no line is wider than it /// was measured, though a glyph wider than its column can still extend past it, as in any - /// cell. The save lists the cell as , a - /// warning that saves. + /// cell. The save lists the cell as + /// , a warning that + /// saves. /// Which cells give them up is decided in order: the header rows are judged first, then /// each group of rows joined by a , each on the heights the decisions /// before it leave. A group is relieved in three steps, each taken only while the group still @@ -106,8 +107,10 @@ public sealed class Cell /// fit; a table whose rows are all headers repeats none of them, so its rows are cut like any /// other. Do not pass a line break in a repeated header row or a span group that has no /// room and expect the lines to be drawn: move the text to a row that can be cut, or shorten - /// it. A renderer you lay out without the document, through a built - /// with the public constructor, knows no page and keeps every break. + /// it. A table you lay out without the document, through a built + /// with the public constructor or narrowed with , or from a + /// renderer of yours that forwards to its , reads no + /// cell's breaks; see . /// /// public string Content { get; } diff --git a/src/VellumPdf.Layout/Elements/Table/TableElement.cs b/src/VellumPdf.Layout/Elements/Table/TableElement.cs index c383b2816..8fb5e33d3 100644 --- a/src/VellumPdf.Layout/Elements/Table/TableElement.cs +++ b/src/VellumPdf.Layout/Elements/Table/TableElement.cs @@ -56,6 +56,12 @@ namespace VellumPdf.Layout.Elements.Table; /// row that began under the document's context keeps cutting in the overflow renderer when that /// is laid out under a plain context at the width the row was cut at. At another width the row is /// laid out again from its first line, and without the box it is not cut. +/// A table is laid out with its cells' breaks read only when the document lays it out. A +/// under a context you build with the public +/// constructor of or narrow with +/// , or one that a renderer of yours holds and forwards +/// to, reads every cell unbroken, as it did before the breaks +/// were read (#679). See . /// public sealed class TableElement { diff --git a/src/VellumPdf.Layout/Rendering/IContinuationGuard.cs b/src/VellumPdf.Layout/Rendering/IContinuationGuard.cs deleted file mode 100644 index 348fe30b5..000000000 --- a/src/VellumPdf.Layout/Rendering/IContinuationGuard.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright © Timothy van der Ham (@Tim81) -// SPDX-License-Identifier: Apache-2.0 - -using VellumPdf.Layout.Core; - -namespace VellumPdf.Layout.Rendering; - -/// -/// A renderer with two layouts: the one it uses, which can take more page continuations than one -/// element may, and a second that takes what the table took before the first existed. After the -/// first call the document asks for a bound on the continuations of the first. When the bound -/// allows it to reach the limit, the document places the element once without drawing, and if -/// that reaches the limit it uses the second layout instead. -/// -/// -/// Implement it explicitly. The built-in renderers are public classes, so an implicit -/// implementation would be a new public member. -/// -internal interface IContinuationGuard -{ - /// - /// An upper bound on the page continuations that placing the renderer needs, known once it has - /// been laid out for the first time in the area the document offers. Zero when it knows none. - /// - long ContinuationBound { get; } - - /// - /// A renderer that lays the same element out in the second way, from the first area on. It - /// carries nothing the first layout decided. - /// - IRenderer WithoutBreaks(); -} diff --git a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs index 9e131cc40..a83d469da 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs @@ -101,7 +101,9 @@ public static TableMeasureProbe? Current /// Cells whose line count a measurement wrapped. public int WrapMisses { get; set; } - /// Cells whose longest word and widest line a resolution took from the cache. + /// + /// Cells whose longest word and widest line a resolution took from the cache. + /// public int WidthHits { get; set; } /// Cells whose longest word and widest line a resolution measured. diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index f6cdb7386..b14889409 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -33,7 +33,7 @@ namespace VellumPdf.Layout.Rendering.Table; /// is tagged as a header cell. A table that has a row that is not a header after its leading /// header rows repeats those header rows on every page. /// -public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IPlacementSource, IContinuationGuard +public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IPlacementSource, IContinuationTwin { private readonly TableElement _table; private readonly int _startRow; // first data row index (0-based) @@ -68,15 +68,33 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IP // goes with it. private bool _allUnbroken; - // True for a renderer the document made because laying the table out with its breaks read - // would take more page continuations than one element may: it reads every cell unbroken from - // the start, as the table was measured before breaks were honoured, and says so in the - // diagnostics. Copies carry it. + // True for the table's twin (IContinuationTwin): it reads every cell unbroken from the start, + // as the table was laid out before breaks were honoured. The document chooses it when the + // layout with breaks would take more page continuations than one element may where this one + // would not, and a table laid out under a context the document did not address to it is the + // twin too. Copies carry it. A 2.x compatibility device, removed in 3.0 (#688). private bool _readsUnbrokenForTheLimit; - // An upper bound on the page continuations the decision's layout needs, set where the decision - // is made; see ContinuationBoundOf. - private long _continuationBound; + // The twin this renderer lays out as when it is not addressed (see Layout), made once so that + // every call reaches the same object and a later page reuses its decision. Removed in 3.0 + // (#688). + private TableRenderer? _twin; + + // Set while the last Layout call went to the twin, because Draw and ReportPlacements then + // belong to it: the document draws the instance it called, and only the twin holds what the + // layout decided. Removed in 3.0 (#688). + private TableRenderer? _laidOutBy; + + // What the decision reports to the document: an upper bound on the continuations of the + // placement in either layout, over the grid that keeps the breaks and the grid that reads every + // cell unbroken, which is the twin's. Where the decision leaves no cell its breaks the two are + // one grid. Removed in 3.0 (#688). + private long _reportBound; + + // True for a twin the document chose, and for the pieces it makes: only then is the fallback + // reported. A twin that a caller's renderer holds, or one laid out under a context the caller + // built, reports nothing, as the table did before breaks were honoured. Removed in 3.0 (#688). + private bool _placedAsTwin; // What the decision under way has measured of each cell; null outside it. private TableMeasureCache? _measured; @@ -170,17 +188,24 @@ public TableRenderer(TableElement table, int startRow = 0) // the top and reports nothing either. void IPlacementSource.ReportPlacements(PlacementSink sink) { + if (_laidOutBy is { } twin) + { + ((IPlacementSource)twin).ReportPlacements(sink); + return; + } + if (!_continuation && _startRow == 0 && _table.Anchor is { } anchor) sink.ReportAnchor(_table, anchor, _occupied); } internal TableElement Element => _table; - // Explicit, as above. - long IContinuationGuard.ContinuationBound => _continuationBound; - - IRenderer IContinuationGuard.WithoutBreaks() => - new TableRenderer(_table, _startRow) { _continuation = _continuation, _readsUnbrokenForTheLimit = true }; + // Explicit, as above. The twin reads every cell unbroken from this renderer's start row, which + // is what the table did before breaks were honoured. Removed in 3.0 (#688). + IRenderer IContinuationTwin.Twin() => + _readsUnbrokenForTheLimit + ? this + : _twin ??= new TableRenderer(_table, _startRow) { _continuation = _continuation, _readsUnbrokenForTheLimit = true }; /// Resolves column widths and row heights, fitting as many rows as possible and splitting at row boundaries on overflow, or between the lines of a row that fits no fresh page. /// @@ -204,8 +229,18 @@ IRenderer IContinuationGuard.WithoutBreaks() => /// up their breaks, among them cells in rows that are neither header rows nor joined by a /// , and the save reports each as /// ; - /// says when and which. A context built with the public - /// constructor of keeps every break. + /// says when and which. + /// A table that you lay out, and not the document, reads no cell's breaks. + /// Under a context you build with the public constructor of or + /// narrow with , and from a renderer of yours that holds a + /// and forwards to it, every cell is wrapped + /// at spaces alone and measured with its control characters, and drawn without them, as the + /// table was laid out before the breaks were read (#679). Nothing is reported for it, and the + /// two layouts can take a different number of pages. Do not pass a table to a renderer + /// of yours in the expectation that its line breaks are drawn: add it with + /// . A renderer of yours that forwards + /// must forward to the same table as well. 3.0 lays a + /// table out one way under every context. /// These are refused with the too-tall exception, extended with a sentence naming the /// rows or the cell, and are never cut: the repeated header rows when they do not fit a page; /// a row that declares a above one, or lies under one; a row with a @@ -241,6 +276,20 @@ IRenderer IContinuationGuard.WithoutBreaks() => /// public LayoutResult Layout(LayoutContext context) { + // The new layout, which reads the breaks of the cells, runs only for the instance the + // document called, in a placement it has not decided for the twin. Under any other context + // (a caller's renderer that forwards here, WithArea, the public constructor) the table is + // laid out as it was before breaks were honoured, by its twin. Removed in 3.0 (#688). + var mode = context.ModeFor(this); + _laidOutBy = null; + if (mode == ContinuationMode.Twin && !_readsUnbrokenForTheLimit) + { + _laidOutBy = (TableRenderer)((IContinuationTwin)this).Twin(); + return _laidOutBy.Layout(context); + } + + if (_readsUnbrokenForTheLimit) _placedAsTwin = context.IsPlacedAsTwin(this); + var area = context.Area.Deflate(_table.Margins); if (area.Width <= 0) return LayoutResult.Nothing(); @@ -293,6 +342,8 @@ public LayoutResult Layout(LayoutContext context) } else { + var oneLineBound = 0L; + // Before the grid resolves: a ColSpan of zero gives a column count of zero, so // Resolve returns no widths and Layout gives up below, and the caller was told the // table was too tall to fit (#481). Checking here names the cell instead. @@ -342,8 +393,8 @@ public LayoutResult Layout(LayoutContext context) // A table that 2.3.3 refused stays refused: the decision above keeps the breaks // of the cells that left every header and group room, and that can leave the - // table fit where it measures every cell as one line and is refused. Cell.Content - // says why. + // table fit where it measures every cell as one line and is refused. + // Cell.Content says why. if (AnyControlSpaceKeepsItsBreaks(rows)) { var (widths, heights) = (_colWidths, _rowHeights); @@ -362,6 +413,11 @@ public LayoutResult Layout(LayoutContext context) } if (!RefusedOnAFreshPage(fresh!, style)) { + // The table keeps some breaks, so its layout differs from the twin's + // and the bound must cover both: the grid read unbroken, which is the + // twin's, and the grid that keeps the breaks, taken below. A table + // that is refused here is laid out unbroken, which is the twin's. + oneLineBound = ContinuationBoundOf(fresh!); _allUnbroken = false; (_colWidths, _rowHeights) = (widths, heights); } @@ -370,8 +426,16 @@ public LayoutResult Layout(LayoutContext context) _measured = null; _content = null; _decidedFor = key; - if (fresh is not null && !_readsUnbrokenForTheLimit) _continuationBound = ContinuationBoundOf(fresh); + if (fresh is not null && !_readsUnbrokenForTheLimit) + _reportBound = Math.Max(oneLineBound, ContinuationBoundOf(fresh)); } + + // Every first call of a placement reports, not only the call that made the decision: + // the document places this instance again for each pass and each simulation of the + // keep rules, and a decision it carries would otherwise read as a call with no report, + // which fixes the twin. + if (fresh is not null && mode == ContinuationMode.Undecided) + context.Session!.Report(this, _reportBound); } // The repeatable header is the leading contiguous run of IsHeader rows — see @@ -492,6 +556,8 @@ private TableRenderer Carrying(TableRenderer next) next._oneLine = _oneLine; next._allUnbroken = _allUnbroken; next._readsUnbrokenForTheLimit = _readsUnbrokenForTheLimit; + next._placedAsTwin = _placedAsTwin; + next._reportBound = _reportBound; next._decidedFor = _decidedFor; return next; } @@ -711,7 +777,9 @@ private static string RuneString(System.Text.Rune rune) => /// private bool HonoursBreaks(int row, int cell) => !_allUnbroken && _oneLine?.Contains((row, cell)) != true; - /// True when some cell holds control white space and the table reads its breaks. + /// + /// True when some cell holds control white space and the table reads its breaks. + /// private bool AnyControlSpaceKeepsItsBreaks(IReadOnlyList rows) { for (var r = 0; r < rows.Count; r++) @@ -1161,7 +1229,8 @@ private bool LeavesNoRoomForALine(LayoutBox[] fresh, double headerHeight, int fi if (headerReach < firstDataRow) return groups; - // The data rows under a header span that no group holds, each alone, in order with the rest. + // The data rows under a header span that no group holds, each alone, in order with the + // rest. var all = new List<(int First, int Last)>(groups.Count + headerReach - firstDataRow + 1); var next = 0; for (var r = firstDataRow; r <= headerReach; r++) @@ -1569,6 +1638,13 @@ private static string DroppedForTheLimit(long subject) => string.Create( /// public void Draw(DrawContext ctx) { + // Laid out by the twin, which holds what was decided. + if (_laidOutBy is { } twin) + { + twin.Draw(ctx); + return; + } + // Layout already deflated context.Area by _table.Margins and stored the result in // _occupied; deflating again here took the table's own margin out of the box twice. The // vertical half was the one that lost content rather than merely shifting it: _occupied's @@ -1838,7 +1914,8 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, // A cell the table laid out unbroken is reported where it is first drawn: once per page for // a repeated header row, and from its first slice for a cut row. Only a cell that holds a // control character loses anything by it, which is the separation its words had. - if (!HonoursBreaks(rowIndex, cellIndex) && LayoutText.HasControlSpace(cell.Content) + if ((!_readsUnbrokenForTheLimit || _placedAsTwin) + && !HonoursBreaks(rowIndex, cellIndex) && LayoutText.HasControlSpace(cell.Content) && (slice is null || slice.First[cellIndex] == 0)) { ctx.Diagnostics?.Report( diff --git a/tests/VellumPdf.Kernel.Tests/PeekGlyphIdTests.cs b/tests/VellumPdf.Kernel.Tests/PeekGlyphIdTests.cs index 2bf7c6058..41b6b0644 100644 --- a/tests/VellumPdf.Kernel.Tests/PeekGlyphIdTests.cs +++ b/tests/VellumPdf.Kernel.Tests/PeekGlyphIdTests.cs @@ -77,4 +77,25 @@ public void Handle_peekLeavesTheSubsetAsItWas() Assert.Equal(gid, handle.GetGlyphId('A')); Assert.NotEqual(before, Written(handle.Embedder)); } + + /// + /// The width measured without registering equals MeasureString's on another embedder, + /// for text with no glyph in the font, a tab, a line feed and the two spaces the font + /// synthesizes, and leaves what the embedder writes as it was. + /// + [Theory] + [MemberData(nameof(Fonts))] + public void MeasureStringWithoutRegistering_equalsMeasureString_andRegistersNothing(string file) + { + string[] texts = ["Hello", "a\tb\nc", "x\u202Fy\u2007z", "\u4E00 and \u0000", "\U0001F600", ""]; + var measurer = Embed(file); + var before = Written(measurer); + var widths = texts.Select(t => measurer.MeasureStringWithoutRegistering(t, 12)).ToArray(); + + Assert.Equal(before, Written(measurer)); + + var registering = Embed(file); + Assert.Equal(texts.Select(t => registering.MeasureString(t, 12)), widths); + Assert.NotEqual(before, Written(registering)); + } } diff --git a/tests/VellumPdf.Layout.Tests/ContinuationSupport.cs b/tests/VellumPdf.Layout.Tests/ContinuationSupport.cs index 3232e6a50..45d4fcd29 100644 --- a/tests/VellumPdf.Layout.Tests/ContinuationSupport.cs +++ b/tests/VellumPdf.Layout.Tests/ContinuationSupport.cs @@ -431,6 +431,7 @@ public void Draw(DrawContext context) { } internal sealed record Setup { + internal double PageWidth { get; init; } = 200; internal double PageHeight { get; init; } = 100; internal bool Footer { get; init; } internal bool Mirror { get; init; } @@ -457,7 +458,7 @@ internal static Outcome Run(Setup setup, Log log, params IRenderer[] elements) { var pdf = PlacementLoopSupport.NewPdf(); var margins = setup.Margins ?? (setup.Mirror ? new EdgeInsets(10, 5, 10, 25) : new EdgeInsets(10)); - var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, setup.PageHeight), margins) + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, setup.PageWidth, setup.PageHeight), margins) { ContinuationLimit = setup.Limit, MirrorMargins = setup.Mirror, diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index 73a73983c..9f8e99d41 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -9,6 +9,7 @@ using VellumPdf.Layout.Core; using VellumPdf.Layout.Elements; using VellumPdf.Layout.Elements.Table; +using VellumPdf.Layout.Rendering; using VellumPdf.Layout.Rendering.Table; using VellumPdf.TestSupport; @@ -870,11 +871,13 @@ public void ATabThatWouldTipARowSpanGroupOverThePageIsLaidOutUnbroken() /// /// A renderer laid out without the document, through a context built with the public - /// constructor, knows no page: it keeps every break, and a header that is then too tall is - /// the same refusal as before. The document supplies the page and lays the cell out unbroken. + /// constructor, is the table as it was laid out before the breaks were read: every cell is one + /// line, so the header of 60 lines is one line of 20pt and the table fits. The document, which + /// the table addresses, reads the breaks and lays the cell out unbroken only because the + /// header would leave no room. /// [Fact] - public void WithoutThePageTheBreaksAreKept() + public void WithoutTheDocumentEveryCellIsReadUnbroken() { var t = Wide10(1900); t.AddRow(isHeader: true).AddCell(Words(60)); @@ -882,9 +885,21 @@ public void WithoutThePageTheBreaksAreKept() var result = new TableRenderer(t).Layout(new LayoutContext(new LayoutBox(10, 10, 1980, 580))); - Assert.Equal(LayoutResult.Outcome.Nothing, result.Status); + Assert.Equal(LayoutResult.Outcome.Full, result.Status); + Assert.Equal(40.0, result.OccupiedArea!.Value.Height, 0.001); } + /// + /// The context the document makes for the renderer it calls, in the mode it decided for a + /// table that reports nothing: the page the caller names, and the new layout. + /// + private static LayoutContext FromTheDocument(IRenderer called, LayoutBox area, LayoutBox fresh) => + new(area) + { + FreshPageArea = fresh, + Session = new ContinuationSession(ContinuationMode.New) { Called = called }, + }; + /// /// Strict diagnostics saves a table whose cell is laid out unbroken: the report is a warning, /// because the text stays and only the separation of its words is lost. @@ -1392,8 +1407,9 @@ public void ADecisionIsNotReusedForAFreshPageOfAnotherHeight() var small = new LayoutBox(10, 10, 1980, 580); var tall = new LayoutBox(10, 10, 1980, 700); - var first = new TableRenderer(t).Layout(new LayoutContext(new LayoutBox(10, 10, 1980, 60)) { FreshPageArea = small }); - var second = first.OverflowRenderer!.Layout(new LayoutContext(tall) { FreshPageArea = tall }); + var renderer = new TableRenderer(t); + var first = renderer.Layout(FromTheDocument(renderer, new LayoutBox(10, 10, 1980, 60), small)); + var second = first.OverflowRenderer!.Layout(FromTheDocument(first.OverflowRenderer!, tall, tall)); Assert.Equal(LayoutResult.Outcome.Partial, first.Status); Assert.Equal(60.0, first.OccupiedArea!.Value.Height, 0.001); @@ -1413,8 +1429,9 @@ public void ADecisionIsReusedForAFreshPageOfTheSameHeight() for (var i = 0; i < 3; i++) t.AddRow().AddCell("x"); var small = new LayoutBox(10, 10, 1980, 580); - var first = new TableRenderer(t).Layout(new LayoutContext(new LayoutBox(10, 10, 1980, 60)) { FreshPageArea = small }); - var second = first.OverflowRenderer!.Layout(new LayoutContext(small) { FreshPageArea = small }); + var renderer = new TableRenderer(t); + var first = renderer.Layout(FromTheDocument(renderer, new LayoutBox(10, 10, 1980, 60), small)); + var second = first.OverflowRenderer!.Layout(FromTheDocument(first.OverflowRenderer!, small, small)); Assert.Equal(40.0, second.OccupiedArea!.Value.Height, 0.001); } diff --git a/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs b/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs new file mode 100644 index 000000000..ed07d7f94 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs @@ -0,0 +1,196 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements.Table; +using VellumPdf.Layout.Rendering.Table; +using static VellumPdf.Layout.Tests.ContinuationSupport; + +namespace VellumPdf.Layout.Tests; + +/// +/// A table that keeps its cells' breaks is laid out the way the table was laid out before the breaks +/// were read where the document, run at a limit of 300 page continuations, would otherwise refuse +/// it (#679 through the shared mechanism of #686). A table that main refused stays refused, with +/// the same exception, and a table that a caller's renderer holds, or that is laid out under any +/// context the document did not address to it, is laid out as main does. +/// +public sealed class TableContinuationLimitTests +{ + private static TextStyle Helvetica() => new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = 10 }; + + /// + /// A first row of mmmmmmmm words joined by line feeds and a short cell, then rows of a + /// letter and a two-word paragraph, on a page that holds two rows of the second kind when the + /// first row's breaks are read and one when they are not: read unbroken the first row is one + /// long word, so the first column is wide and the paragraphs wrap into two lines. + /// + private static TableElement TwoLineRowsWhenTheFirstRowIsUnbroken(int rows) + { + var t = new TableElement { DefaultCellStyle = Helvetica() }; + t.AddRow().AddCell(string.Join("\n", Enumerable.Repeat("mmmmmmmm", 6))).AddCell("s"); + for (var i = 0; i < rows; i++) t.AddRow().AddCell("a").AddCell("lorem lorem"); + return t; + } + + private static Setup Sixty { get; } = new() { PageWidth = 400, PageHeight = 60 }; + + /// One cell of lines on a page one line of it tall. + private static TableElement OneCellOfLines(int lines) + { + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(1900); + t.AddRow().AddCell(string.Join("\n", Enumerable.Repeat("ab", lines))); + return t; + } + + private static Setup Wide { get; } = new() { PageWidth = 2000, PageHeight = 40 }; + + private static Outcome Run(Setup setup, IRenderer element, bool measuredAsOneLine = false) + { + TableMeasureProbe.Current = measuredAsOneLine ? new TableMeasureProbe { ReadEveryCellUnbroken = true } : null; + try + { + return ContinuationSupport.Run(setup, new Log(), element); + } + finally + { + TableMeasureProbe.Current = null; + } + } + + private static int Dropped(Outcome outcome) => + outcome.Renderer.Diagnostics.Count(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped); + + /// + /// A table whose first row read unbroken takes more continuations than the limit is refused, as + /// it was when the table was laid out unbroken, though it takes half as many with its breaks + /// read. The same table with one row fewer is saved, with its breaks. + /// + [Fact] + public void ATableWhoseUnbrokenLayoutReachesTheLimit_isRefusedWithTheMessageThatLayoutGives() + { + var oneLine = Run(Sixty, new TableRenderer(TwoLineRowsWhenTheFirstRowIsUnbroken(Limit + 1)), measuredAsOneLine: true); + var decided = Run(Sixty, new TableRenderer(TwoLineRowsWhenTheFirstRowIsUnbroken(Limit + 1))); + + Assert.True(IsLimitRefusal(oneLine.Error), "the measurement must be refused for the test to mean anything"); + Assert.True(IsLimitRefusal(decided.Error), decided.Error?.Message ?? "saved"); + Assert.Equal(oneLine.Error!.GetType(), decided.Error!.GetType()); + Assert.Equal(oneLine.Error.Message, decided.Error.Message); + Assert.True(decided.Probes > 0, "the document must have asked"); + } + + /// + /// One row fewer: both layouts are within the limit, so the table keeps its breaks, in about + /// half the pages the unbroken layout takes. + /// + [Fact] + public void ATableWhoseUnbrokenLayoutIsWithinTheLimit_keepsItsBreaks() + { + var oneLine = Run(Sixty, new TableRenderer(TwoLineRowsWhenTheFirstRowIsUnbroken(Limit)), measuredAsOneLine: true); + var decided = Run(Sixty, new TableRenderer(TwoLineRowsWhenTheFirstRowIsUnbroken(Limit))); + + Assert.Null(oneLine.Error); + Assert.Null(decided.Error); + Assert.True(decided.Pages < oneLine.Pages, $"{decided.Pages} pages against {oneLine.Pages}"); + Assert.Equal(0, Dropped(decided)); + } + + /// + /// A cell whose breaks, read, take more continuations than the limit is laid out unbroken, in + /// the bytes of the table as it was laid out unbroken, and the fallback is reported. + /// + [Fact] + public void ACellThatWouldTakeMoreThanTheLimitIsLaidOutUnbroken_andReported() + { + var oneLine = Run(Wide, new TableRenderer(OneCellOfLines(Limit + 2)), measuredAsOneLine: true); + var decided = Run(Wide, new TableRenderer(OneCellOfLines(Limit + 2))); + + Assert.Null(decided.Error); + Assert.Equal(oneLine.Bytes, decided.Bytes); + Assert.Equal(1, Dropped(decided)); + Assert.Contains(decided.Renderer.Diagnostics, d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped + && d.Message.Contains("more page continuations than one element may take", StringComparison.Ordinal)); + } + + /// + /// A caller's renderer that forwards to a public TableRenderer never asks the document + /// to decide, so the table is laid out as it was before its breaks were read, however it + /// forwards: a cell that the document would give the limit's fallback saves in the same bytes, + /// and nothing is reported, because no decision chose it. + /// + [Theory] + [InlineData((int)WrapKind.PassThrough)] + [InlineData((int)WrapKind.WithArea)] + [InlineData((int)WrapKind.CachedByArea)] + public void ATableAWrapperHolds_isLaidOutAsBeforeItsBreaksWereRead(int wrapKind) + { + var oneLine = Run(Wide, new TableRenderer(OneCellOfLines(Limit + 2)), measuredAsOneLine: true); + var wrapped = Run(Wide, new Wrapper(new TableRenderer(OneCellOfLines(Limit + 2)), (WrapKind)wrapKind)); + + Assert.Null(wrapped.Error); + Assert.Equal(oneLine.Bytes, wrapped.Bytes); + Assert.Equal(0, Dropped(wrapped)); + Assert.Equal(0, wrapped.Probes); + } + + /// + /// A wrapper that lays the table out under a context it builds knows no fresh page, so the + /// table cuts no row, as the table did before its breaks were read: the cell that does not fit + /// a page is refused as too tall, not as a limit. + /// + [Fact] + public void ATableAWrapperLaysOutUnderAContextItBuilds_cutsNoRow() + { + var wrapped = Run(Wide, new Wrapper(new TableRenderer(OneCellOfLines(Limit + 2)), WrapKind.PublicConstructor)); + + Assert.IsType(wrapped.Error); + Assert.Contains("too tall", wrapped.Error.Message, StringComparison.Ordinal); + Assert.Equal(0, wrapped.Probes); + } + + /// + /// The same wrapper around a table that takes the page count as it was: a table of rows is + /// laid out in the pages main laid it out in, not in the pages its breaks would take, since + /// the breaks are not read where the document did not call the table. + /// + [Theory] + [InlineData((int)WrapKind.PassThrough)] + [InlineData((int)WrapKind.WithArea)] + [InlineData((int)WrapKind.PublicConstructor)] + public void ATableAWrapperHolds_takesTheUnbrokenLayoutsPages(int wrapKind) + { + var oneLine = Run(Sixty, new TableRenderer(TwoLineRowsWhenTheFirstRowIsUnbroken(Limit)), measuredAsOneLine: true); + var wrapped = Run(Sixty, new Wrapper(new TableRenderer(TwoLineRowsWhenTheFirstRowIsUnbroken(Limit)), (WrapKind)wrapKind)); + + Assert.Null(wrapped.Error); + Assert.Equal(oneLine.Bytes, wrapped.Bytes); + } + + /// + /// A wrapper around a table whose unbroken layout reaches the limit is refused as main refuses + /// it, whether or not the document would have given the table's breaks up. + /// + [Fact] + public void ATableAWrapperHolds_whoseUnbrokenLayoutReachesTheLimit_isRefusedAsBefore() + { + var oneLine = Run(Sixty, new TableRenderer(TwoLineRowsWhenTheFirstRowIsUnbroken(Limit + 1)), measuredAsOneLine: true); + var wrapped = Run(Sixty, new Wrapper(new TableRenderer(TwoLineRowsWhenTheFirstRowIsUnbroken(Limit + 1)), WrapKind.PassThrough)); + + Assert.True(IsLimitRefusal(wrapped.Error), wrapped.Error?.Message ?? "saved"); + Assert.Equal(oneLine.Error!.Message, wrapped.Error!.Message); + } + + /// + /// A table the document lays out, with the same cell, keeps reading its breaks: the wrapper + /// is the only difference, so the pages differ where the layouts do. + /// + [Fact] + public void TheSameTableWithoutAWrapperKeepsItsBreaks() + { + var direct = Run(Sixty, new TableRenderer(TwoLineRowsWhenTheFirstRowIsUnbroken(Limit))); + var wrapped = Run(Sixty, new Wrapper(new TableRenderer(TwoLineRowsWhenTheFirstRowIsUnbroken(Limit)), WrapKind.PassThrough)); + + Assert.NotEqual(direct.Pages, wrapped.Pages); + } +} diff --git a/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs index e9d321b10..5c314226b 100644 --- a/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs @@ -297,21 +297,31 @@ public void ALargeCellThatWouldTakeMoreThanTheLimitIsLaidOutAsOneLine() /// private static (long Bound, long Continuations)? BoundAndContinuations(TableElement t, LayoutBox area) { - var ctx = new LayoutContext(area) { FreshPageArea = area }; + // The context the document makes: addressed to the instance it calls, undecided for the + // first call, which is where the table reports, and decided for the new layout after it. + var session = new Rendering.ContinuationSession(); + LayoutContext Context(IRenderer called) + { + session.Called = called; + return new LayoutContext(area) { FreshPageArea = area, Session = session }; + } + IRenderer renderer = new TableRenderer(t); var continuations = 0L; try { - var result = renderer.Layout(ctx); - var bound = ((Rendering.IContinuationGuard)renderer).ContinuationBound; + var result = renderer.Layout(Context(renderer)); + var reported = session.Reported; + var bound = session.Bound; + session.Mode = Rendering.ContinuationMode.New; while (result.Status == LayoutResult.Outcome.Partial) { continuations++; renderer = result.OverflowRenderer!; - result = renderer.Layout(ctx); + result = renderer.Layout(Context(renderer)); } - return result.Status == LayoutResult.Outcome.Nothing ? null : (bound, continuations); + return result.Status == LayoutResult.Outcome.Nothing || !reported ? null : (bound, continuations); } catch (InvalidOperationException) { From e8944ec32d5b6495a908a6cdb6413aaf327cbb25 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 21:09:28 +0100 Subject: [PATCH 36/48] test(layout): pin the table's report in every pass and its twin's identity A table that keeps its breaks keeps them in the drawing pass of a document with a footer, which lays the table out a second time from the decision the first one carried. The twin is one object for the life of the renderer. A delegating table no longer forwards its anchor: the document reports one only for a renderer it placed, so the forward was never reached. --- .../Rendering/Table/TableRenderer.cs | 13 +++----- .../TableContinuationLimitTests.cs | 33 +++++++++++++++++++ 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index b14889409..d87721e25 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -80,9 +80,10 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IP // (#688). private TableRenderer? _twin; - // Set while the last Layout call went to the twin, because Draw and ReportPlacements then - // belong to it: the document draws the instance it called, and only the twin holds what the - // layout decided. Removed in 3.0 (#688). + // Set while the last Layout call went to the twin, because Draw then belongs to it: the + // document draws the instance it called, and only the twin holds what the layout decided. The + // anchor is not forwarded: a delegating instance is one a caller's renderer holds, and the + // document reports an anchor only for a renderer it placed. Removed in 3.0 (#688). private TableRenderer? _laidOutBy; // What the decision reports to the document: an upper bound on the continuations of the @@ -188,12 +189,6 @@ public TableRenderer(TableElement table, int startRow = 0) // the top and reports nothing either. void IPlacementSource.ReportPlacements(PlacementSink sink) { - if (_laidOutBy is { } twin) - { - ((IPlacementSource)twin).ReportPlacements(sink); - return; - } - if (!_continuation && _startRow == 0 && _table.Anchor is { } anchor) sink.ReportAnchor(_table, anchor, _occupied); } diff --git a/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs b/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs index ed07d7f94..9e2a3d005 100644 --- a/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs @@ -193,4 +193,37 @@ public void TheSameTableWithoutAWrapperKeepsItsBreaks() Assert.NotEqual(direct.Pages, wrapped.Pages); } + + /// + /// The document asks about the table in every pass: with a footer it lays the table out twice, + /// and the second, drawing pass keeps the breaks the first measured, so a table within the + /// limit takes the pages its breaks give and not the pages of the unbroken layout. + /// + [Fact] + public void ATableThatKeepsItsBreaks_keepsThemInEveryPass() + { + var setup = Sixty with { Footer = true, PageHeight = 80 }; + var oneLine = Run(setup, new TableRenderer(TwoLineRowsWhenTheFirstRowIsUnbroken(Limit / 2)), measuredAsOneLine: true); + var decided = Run(setup, new TableRenderer(TwoLineRowsWhenTheFirstRowIsUnbroken(Limit / 2))); + + Assert.Null(decided.Error); + Assert.True(decided.Pages < oneLine.Pages, $"{decided.Pages} pages against {oneLine.Pages}"); + Assert.Equal(0, Dropped(decided)); + } + + /// + /// The twin is one object for the life of the renderer, so a caller's renderer that lays the + /// table out under a context it built reaches the same one each time, and so is the twin of the + /// twin. + /// + [Fact] + public void TheTwinIsTheSameObjectOnEveryCall() + { + var renderer = new TableRenderer(OneCellOfLines(2)); + var twin = ((Rendering.IContinuationTwin)renderer).Twin(); + + Assert.NotSame(renderer, twin); + Assert.Same(twin, ((Rendering.IContinuationTwin)renderer).Twin()); + Assert.Same(twin, ((Rendering.IContinuationTwin)twin).Twin()); + } } From c78522dbc54ab7f4bf9a21eb93ff52a76300f0ea Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 21:18:40 +0100 Subject: [PATCH 37/48] test(layout): pin the unbroken bound, a wrapped single page and a start row A table whose bound with its breaks read is within the limit and whose unbroken layout reaches it is refused as before, which only holds when the reported bound covers the unbroken grid. A wrapped table that fits one page is drawn by its twin. A table started at a row, under a context the caller built, is its twin from that row. --- .../TableContinuationLimitTests.cs | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs b/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs index 9e2a3d005..562bf6a14 100644 --- a/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs @@ -226,4 +226,98 @@ public void TheTwinIsTheSameObjectOnEveryCall() Assert.Same(twin, ((Rendering.IContinuationTwin)renderer).Twin()); Assert.Same(twin, ((Rendering.IContinuationTwin)twin).Twin()); } + + /// + /// A first row of ten mmmmmmmm words joined by line feeds, then rows of a letter and + /// eight words, on a page 400 wide and 200 tall. Read unbroken the first row is one long word + /// that takes the width of the page, so the paragraph is one word to a line and a row fills a + /// page; with the breaks read a page holds nine rows. The bound over the grid that keeps the + /// breaks is about a sixth of the rows, so it is within the limit where the unbroken layout is + /// not. + /// + private static TableElement OneRowAPageWhenTheFirstRowIsUnbroken(int rows) + { + var t = new TableElement { DefaultCellStyle = Helvetica() }; + t.AddRow().AddCell(string.Join("\n", Enumerable.Repeat("mmmmmmmm", 10))).AddCell("s"); + var paragraph = string.Join(" ", Enumerable.Repeat("lorem", 8)); + for (var i = 0; i < rows; i++) t.AddRow().AddCell("a").AddCell(paragraph); + return t; + } + + private static Setup TwoHundred { get; } = new() { PageWidth = 400, PageHeight = 200 }; + + /// + /// A table whose bound with its breaks read is within what is left of the limit, and whose + /// unbroken layout reaches it, is refused with the message that layout gives: the bound the + /// table reports covers both layouts, so the document places it twice instead of trusting the + /// smaller. + /// + [Fact] + public void ATableWhoseBreaksBoundIsWithinTheLimit_butWhoseUnbrokenLayoutReachesIt_isRefused() + { + var oneLine = Run(TwoHundred, new TableRenderer(OneRowAPageWhenTheFirstRowIsUnbroken(Limit + 2)), measuredAsOneLine: true); + var decided = Run(TwoHundred, new TableRenderer(OneRowAPageWhenTheFirstRowIsUnbroken(Limit + 2))); + + Assert.True(IsLimitRefusal(oneLine.Error), "the measurement must be refused for the test to mean anything"); + Assert.True(IsLimitRefusal(decided.Error), decided.Error?.Message ?? "saved"); + Assert.Equal(oneLine.Error!.Message, decided.Error!.Message); + Assert.True(decided.Probes > 0, "the document must have asked"); + } + + /// + /// The same table with its unbroken layout one continuation short of the limit keeps its breaks. + /// + [Fact] + public void ATableWhoseUnbrokenLayoutTakesTheLimitExactly_keepsItsBreaks() + { + var oneLine = Run(TwoHundred, new TableRenderer(OneRowAPageWhenTheFirstRowIsUnbroken(Limit)), measuredAsOneLine: true); + var decided = Run(TwoHundred, new TableRenderer(OneRowAPageWhenTheFirstRowIsUnbroken(Limit))); + + Assert.Null(oneLine.Error); + Assert.Null(decided.Error); + Assert.True(decided.Pages * 5 < oneLine.Pages, $"{decided.Pages} pages against {oneLine.Pages}"); + Assert.Equal(0, Dropped(decided)); + } + + /// + /// A wrapped table that fits one page is laid out by the twin on the first call and drawn by + /// the wrapper's Draw, which has to reach the twin: the document draws the instance it + /// called, and only the twin holds the layout. The bytes are those of the unbroken layout. + /// + [Fact] + public void ATableAWrapperHolds_thatFitsOnePage_isDrawnByItsTwin() + { + TableElement Small() + { + var t = new TableElement { DefaultCellStyle = Helvetica() }; + t.AddRow().AddCell("one\ntwo").AddCell("a\tb"); + t.AddRow().AddCell("x").AddCell("y"); + return t; + } + + var oneLine = Run(new Setup(), new TableRenderer(Small()), measuredAsOneLine: true); + var wrapped = Run(new Setup(), new Wrapper(new TableRenderer(Small()), WrapKind.PassThrough)); + + Assert.Null(wrapped.Error); + Assert.Equal(1, wrapped.Pages); + Assert.Equal(oneLine.Bytes, wrapped.Bytes); + } + + /// + /// A table that starts at a row, laid out under a context the caller built, is its twin from + /// that row: the rows before it are not drawn. + /// + [Fact] + public void ATableStartedAtARow_laidOutUnderAContextTheCallerBuilt_startsThere() + { + var t = new TableElement { DefaultCellStyle = Helvetica() }; + for (var i = 0; i < 3; i++) t.AddRow().AddCell("row " + i); + var area = new LayoutBox(10, 10, 380, 500); + + var all = new TableRenderer(t).Layout(new LayoutContext(area)); + var fromTheSecond = new TableRenderer(t, 1).Layout(new LayoutContext(area)); + + Assert.Equal(LayoutResult.Outcome.Full, fromTheSecond.Status); + Assert.Equal(all.OccupiedArea!.Value.Height * 2 / 3, fromTheSecond.OccupiedArea!.Value.Height, 0.001); + } } From b4a698cefa51618c70c53a8c117b643a30042604 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 21:21:14 +0100 Subject: [PATCH 38/48] docs(layout): mark the table's twin paths for removal in 3.0 Each comment that belongs to the twin, the report and the delegation names 3.0 and #688, as the shared mechanism's own comments do. --- src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index d87721e25..16d01eb68 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -412,6 +412,7 @@ public LayoutResult Layout(LayoutContext context) // and the bound must cover both: the grid read unbroken, which is the // twin's, and the grid that keeps the breaks, taken below. A table // that is refused here is laid out unbroken, which is the twin's. + // Removed in 3.0 (#688). oneLineBound = ContinuationBoundOf(fresh!); _allUnbroken = false; (_colWidths, _rowHeights) = (widths, heights); @@ -428,7 +429,7 @@ public LayoutResult Layout(LayoutContext context) // Every first call of a placement reports, not only the call that made the decision: // the document places this instance again for each pass and each simulation of the // keep rules, and a decision it carries would otherwise read as a call with no report, - // which fixes the twin. + // which fixes the twin. Removed in 3.0 (#688). if (fresh is not null && mode == ContinuationMode.Undecided) context.Session!.Report(this, _reportBound); } @@ -1633,7 +1634,7 @@ private static string DroppedForTheLimit(long subject) => string.Create( /// public void Draw(DrawContext ctx) { - // Laid out by the twin, which holds what was decided. + // Laid out by the twin, which holds what was decided. Removed in 3.0 (#688). if (_laidOutBy is { } twin) { twin.Draw(ctx); @@ -1909,6 +1910,8 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, // A cell the table laid out unbroken is reported where it is first drawn: once per page for // a repeated header row, and from its first slice for a cut row. Only a cell that holds a // control character loses anything by it, which is the separation its words had. + // A twin reports it only where the document chose the twin (#688); one a caller holds is + // the table as it was before breaks were honoured, which reports nothing. if ((!_readsUnbrokenForTheLimit || _placedAsTwin) && !HonoursBreaks(rowIndex, cellIndex) && LayoutText.HasControlSpace(cell.Content) && (slice is null || slice.First[cellIndex] == 0)) From 8e901280b105399baa87d83832b6b56f43894807 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 21:54:33 +0100 Subject: [PATCH 39/48] test(layout): count the placement loop's frames, not the wrapper that starts it The stack-depth probes counted PlaceRenderer frames. PlaceRenderer is now a small method that starts PlaceLoop, and the JIT inlines it once it is hot, so on net11.0 a run that placed 50,000 pages before the probes (the table limit tests do) read zero frames. PlaceLoop holds the loop, is not inlined, and is on the stack exactly once per Layout call. --- tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs b/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs index 24205ad27..70f82d20a 100644 --- a/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs +++ b/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs @@ -74,9 +74,11 @@ public void MeasuringPass_manyContinuations_stackDepthStaysFlat() /// private static void AssertFlat(IReadOnlyList samples) { - // 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 + // The count is of PlaceLoop frames on the stack at each Layout call. PlaceRenderer is a + // small method that starts the loop, and the JIT inlines it once it is hot (a table test + // that places 50,000 pages before this one runs is enough on net11.0), so counting its + // frames read 0. Both passes run PlaceLoop, so the count 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()); @@ -97,7 +99,7 @@ private static StackDepthProbeRenderer Paginate(StackDepthProbeRenderer probe, b } /// - /// Splits a fixed number of times, recording how many PlaceRenderer frames are on the stack at + /// Splits a fixed number of times, recording how many PlaceLoop 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. @@ -120,7 +122,7 @@ private StackDepthProbeRenderer(int remaining, List samples) public LayoutResult Layout(LayoutContext context) { var frames = new StackTrace(false).GetFrames() ?? []; - _samples.Add(frames.Count(f => f.GetMethod()?.Name == "PlaceRenderer")); + _samples.Add(frames.Count(f => f.GetMethod()?.Name == "PlaceLoop")); var occupied = context.Area.WithHeight(0); return _remaining > 0 From 6773a13b851ff578ca1bcc032a45e839ea67af0f Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 22:38:15 +0100 Subject: [PATCH 40/48] docs(layout): wrap the table test comments that ran past 100 columns --- .../PaginationDepthTests.cs | 6 +-- .../TableCellBreakTests.cs | 38 ++++++++++++------- .../TableContinuationLimitTests.cs | 13 ++++--- .../TableMainRefusalTests.cs | 3 +- .../TableMeasureCacheTests.cs | 7 +++- 5 files changed, 41 insertions(+), 26 deletions(-) diff --git a/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs b/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs index 70f82d20a..be077a481 100644 --- a/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs +++ b/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs @@ -78,9 +78,9 @@ private static void AssertFlat(IReadOnlyList samples) // small method that starts the loop, and the JIT inlines it once it is hot (a table test // that places 50,000 pages before this one runs is enough on net11.0), so counting its // frames read 0. Both passes run PlaceLoop, so the count 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. + // 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()); } diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs index 9f8e99d41..17e3495e8 100644 --- a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -150,7 +150,9 @@ public void Standard14_aLineFeedBreaksTheLine() AssertNoControlCharacter(placements); } - /// A carriage return and line feed pair is one break, and a lone carriage return is one. + /// + /// A carriage return and line feed pair is one break, and a lone carriage return is one. + /// [Theory] [InlineData("cr1\r\ncr2")] [InlineData("cr1\rcr2")] @@ -328,7 +330,9 @@ public void AnAutoColumn_hasItsMinimumFromTheWordsOfEachLine() // ── Null text ──────────────────────────────────────────────────────────── - /// A null cell text with explicit widths still saves and draws nothing, as before. + /// + /// A null cell text with explicit widths still saves and draws nothing, as before. + /// [Fact] public void ANullText_withExplicitWidths_drawsNothing() { @@ -342,7 +346,9 @@ public void ANullText_withExplicitWidths_drawsNothing() Assert.Equal(["x"], Texts(content)); } - /// A null cell text in an automatically sized column is still refused, naming content. + /// + /// A null cell text in an automatically sized column is still refused, naming content. + /// [Fact] public void ANullText_inAnAutoColumn_isStillRefused() { @@ -569,9 +575,9 @@ public void ABandCutsAtTheSpaceAFormFeedBecame() } /// - /// The text a page label prints reaches a band's {page} as a value, not as template text, - /// so it is read the same way: a tab and a line break in the label prefix are spaces, in the - /// drawing and in the width the band is cut to. + /// The text a page label prints reaches a band's {page} as a value, not as template + /// text, so it is read the same way: a tab and a line break in the label prefix are spaces, in + /// the drawing and in the width the band is cut to. /// [Fact] public void ABandDrawsAControlSpaceInAPageLabelAsASpace() @@ -619,11 +625,15 @@ public void ABandWithAControlSpaceInAPageLabelIsPdfA2uClean() // ── Rows that cannot be cut ────────────────────────────────────────────── - /// The diagnostic a cell that is laid out unbroken is reported with, or null. + /// + /// The diagnostic a cell that is laid out unbroken is reported with, or null. + /// private static LayoutDiagnostic? CellReport(Document doc) => doc.Diagnostics.SingleOrDefault(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped); - /// The cells reported as laid out unbroken, as "row r, cell c", in row order. + /// + /// The cells reported as laid out unbroken, as "row r, cell c", in row order. + /// private static string[] Dropped(Document doc) => [ .. doc.Diagnostics @@ -635,9 +645,9 @@ .. doc.Diagnostics /// /// A header row whose breaks, honoured, leave no room under it for the row below: 2.3.3 drew - /// the cell on one line. The cell is drawn as one line, without its breaks, and reported as a warning. - /// A header of 46 lines is 560pt and leaves 20pt, which holds the 20pt row below, so its - /// breaks are kept. + /// the cell on one line. The cell is drawn as one line, without its breaks, and reported as a + /// warning. A header of 46 lines is 560pt and leaves 20pt, which holds the 20pt row below, so + /// its breaks are kept. /// [Theory] [InlineData(46, false)] @@ -693,9 +703,9 @@ public void AHeaderTallerThanAPageIsLaidOutUnbroken() } /// - /// Rows joined by a RowSpan are never cut, so when their breaks, honoured, make the group taller - /// than a page, the cells that hold them are laid out unbroken. A group of 46 lines plus a - /// 20pt row is 580pt, which fits; 47 lines does not. + /// Rows joined by a RowSpan are never cut, so when their breaks, honoured, make the group + /// taller than a page, the cells that hold them are laid out unbroken. A group of 46 lines plus + /// a 20pt row is 580pt, which fits; 47 lines does not. /// [Theory] [InlineData(46, false)] diff --git a/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs b/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs index 562bf6a14..4e12c448d 100644 --- a/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs @@ -10,11 +10,11 @@ namespace VellumPdf.Layout.Tests; /// -/// A table that keeps its cells' breaks is laid out the way the table was laid out before the breaks -/// were read where the document, run at a limit of 300 page continuations, would otherwise refuse -/// it (#679 through the shared mechanism of #686). A table that main refused stays refused, with -/// the same exception, and a table that a caller's renderer holds, or that is laid out under any -/// context the document did not address to it, is laid out as main does. +/// A table that keeps its cells' breaks is laid out the way the table was laid out before the +/// breaks were read where the document, run at a limit of 300 page continuations, would otherwise +/// refuse it (#679 through the shared mechanism of #686). A table that main refused stays refused, +/// with the same exception, and a table that a caller's renderer holds, or that is laid out under +/// any context the document did not address to it, is laid out as main does. /// public sealed class TableContinuationLimitTests { @@ -265,7 +265,8 @@ public void ATableWhoseBreaksBoundIsWithinTheLimit_butWhoseUnbrokenLayoutReaches } /// - /// The same table with its unbroken layout one continuation short of the limit keeps its breaks. + /// The same table with its unbroken layout one continuation short of the limit keeps its + /// breaks. /// [Fact] public void ATableWhoseUnbrokenLayoutTakesTheLimitExactly_keepsItsBreaks() diff --git a/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs index 5c314226b..3d12e15c6 100644 --- a/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs @@ -443,7 +443,8 @@ public void ADocumentThatIsRefusedMeasuredAsOneLineIsRefused() Assert.Equal(oneLine, RefusalOf(() => TableRandomDocuments.Long(s), measuredAsOneLine: false)); } - // The property is not vacuous: each family has tables that are refused measured as one line. + // The property is not vacuous: each family has tables that are refused measured as one + // line. Assert.True(refusedShaped > 20, $"only {refusedShaped} shaped tables are refused measured as one line"); Assert.True(refusedLong > 20, $"only {refusedLong} long tables are refused measured as one line"); } diff --git a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs index 68e4c1123..17c944336 100644 --- a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs @@ -49,7 +49,9 @@ [.. doc.Diagnostics .OrderBy(m => int.Parse(Regex.Match(m, @"\d+").Value, CultureInfo.InvariantCulture)) .ThenBy(m => m, StringComparer.Ordinal)]; - /// Runs with a probe on this thread, and returns the probe. + /// + /// Runs with a probe on this thread, and returns the probe. + /// private static TableMeasureProbe Probed(Action save) { var probe = new TableMeasureProbe(); @@ -284,7 +286,8 @@ public void EveryCachedLineCountEqualsAFreshWrap() /// /// A cell read unbroken and the same cell with its breaks kept are two entries: the count of /// one is not the count of the other. The header of 60 lines is 728pt and the page holds 580pt, - /// so it is read unbroken; the next table keeps its breaks at 60 lines in a row that can be cut. + /// so it is read unbroken; the next table keeps its breaks at 60 lines in a row that can be + /// cut. /// [Fact] public void TheModeOfACellIsPartOfItsEntry() From a17baf05d80895d5c1d8cbbfd84e792602926295 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 23:48:09 +0100 Subject: [PATCH 41/48] test(layout): keep PlaceLoop out of line so the depth probes can count it The stack-depth probes counted PlaceRenderer frames, and in a full run of the suite in sequence the count read 0, so both probes failed with Expected: 1, Actual: 0. PlaceRenderer only starts the placement loop and is small enough for the JIT to inline into its caller. PlaceLoop is the method that recurses if the loop regresses, and a recursion into it puts a second frame on the stack. Marking it NoInlining keeps the frame the probes count, and the count stays 1 for a renderer that does not report. --- .../Rendering/DocumentRenderer.cs | 1 + .../PaginationDepthTests.cs | 18 +++++++++++------- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs index f9cc84f82..98f8f58b4 100644 --- a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs @@ -1428,6 +1428,7 @@ private void PlaceRenderer(IRenderer renderer, int totalPages) PlaceLoop(renderer, totalPages, keepTogether, lineCounts, session, 0); } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private void PlaceLoop(IRenderer renderer, int totalPages, bool keepTogether, bool lineCounts, ContinuationSession session, int continuations) { var split = false; diff --git a/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs b/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs index be077a481..fecea6d33 100644 --- a/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs +++ b/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs @@ -74,13 +74,17 @@ public void MeasuringPass_manyContinuations_stackDepthStaysFlat() /// private static void AssertFlat(IReadOnlyList samples) { - // The count is of PlaceLoop frames on the stack at each Layout call. PlaceRenderer is a - // small method that starts the loop, and the JIT inlines it once it is hot (a table test - // that places 50,000 pages before this one runs is enough on net11.0), so counting its - // frames read 0. Both passes run PlaceLoop, so the count 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. + // The count is of PlaceLoop frames on the stack at each Layout call. It is 1 for this + // renderer, which never reports, in either pass, and a recursion regression makes it grow + // with the continuation count. A renderer that reports has two on the stack during a + // continuation probe, because the probe calls PlaceLoop from inside PlaceLoop. + // PlaceRenderer, which only starts the loop, was counted before. Its count read 0 on + // net10.0 in a full run of the whole suite in sequence (-parallel none), and the same run + // on net11.0 did not. The likely cause is that the JIT inlined it into its caller, which + // was not confirmed with a JIT dump. PlaceLoop is marked NoInlining so that it keeps a + // frame of its own. 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()); } From 5d03735dbc4ff4a6412f8fbd1675406f6390997c Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sun, 22 Nov 2026 23:50:58 +0100 Subject: [PATCH 42/48] fix(layout): write no empty show for a cell line that control white space emptied A cell the table lays out unbroken leaves its tabs and line breaks out of what it draws, so a line made only of them came out empty and was written as an empty string shown with Tj, which draws nothing. A blank line between two line breaks in a cell that keeps its breaks was written the same way. Neither writes a show now. A cell that holds no control white space is not touched, so a table without any keeps its bytes, an empty cell and a cell of spaces alone included. A table reports its bound whether or not a cell holds control white space, and a test pins why: with no report the document lays the rest of the placement out as the twin, a new renderer without the lines a cut row carries, and the row is drawn again from its first line. The message for a cell given up for the continuation limit and the test hook that measures every cell unbroken now say that 3.0 removes them. --- .../Rendering/Table/TableMeasureCache.cs | 3 +- .../Rendering/Table/TableRenderer.cs | 13 ++++- .../TableContinuationLimitTests.cs | 54 +++++++++++++++++++ 3 files changed, 68 insertions(+), 2 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs index a83d469da..47b4dc82a 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs @@ -91,7 +91,8 @@ public static TableMeasureProbe? Current /// /// When set, a table that holds control white space is measured with every cell as one line - /// and no decision, as it was measured before breaks were honoured. + /// and no decision, as it was measured before breaks were honoured. A compatibility device, + /// removed in 3.0 (#688), with the twin it stands in for. /// public bool ReadEveryCellUnbroken { get; init; } diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 16d01eb68..1479c5d31 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -1603,6 +1603,8 @@ private static string DroppedForRoom(long subject) => string.Create( System.Globalization.CultureInfo.InvariantCulture, $"Table row {subject >> 32}, cell {subject & 0xFFFFFFFF} holds a tab, a line break or another control white-space character that is left out of what is drawn, because reading its line breaks, or its other control white space as spaces, would leave a row that cannot be cut no room on a page. The words it separated run together."); + // The message for a cell the document gave up for the continuation limit. Removed in 3.0 + // (#688), with the twin that reports it. private static string DroppedForTheLimit(long subject) => string.Create( System.Globalization.CultureInfo.InvariantCulture, $"Table row {subject >> 32}, cell {subject & 0xFFFFFFFF} holds a tab, a line break or another control white-space character that is left out of what is drawn, because reading the table's line breaks would take it more page continuations than one element may take. The words it separated run together."); @@ -1912,8 +1914,9 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, // control character loses anything by it, which is the separation its words had. // A twin reports it only where the document chose the twin (#688); one a caller holds is // the table as it was before breaks were honoured, which reports nothing. + var holdsControlSpace = LayoutText.HasControlSpace(cell.Content); if ((!_readsUnbrokenForTheLimit || _placedAsTwin) - && !HonoursBreaks(rowIndex, cellIndex) && LayoutText.HasControlSpace(cell.Content) + && !HonoursBreaks(rowIndex, cellIndex) && holdsControlSpace && (slice is null || slice.First[cellIndex] == 0)) { ctx.Diagnostics?.Report( @@ -1953,6 +1956,14 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, for (var lineIdx = 0; lineIdx < lineCount; lineIdx++) { var line = wrappedLines[firstLine + lineIdx]; + + // A line that is empty because of control white space writes no text: an empty string + // would only be a show operator that draws nothing. That is the line of control + // characters a cell laid out unbroken leaves out, and the blank line between two line + // breaks. A cell that holds none of them is not touched, so a table without control + // white space keeps its bytes, an empty cell and one of spaces alone included. + if (line.Length == 0 && holdsControlSpace) continue; + var lineW = cs.FontRef.MeasureString(line, cs.FontSize); // Floored at the cell's own left edge (#473), the same clamp #472 applied to a diff --git a/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs b/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs index 4e12c448d..9579b1ead 100644 --- a/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs @@ -1,10 +1,12 @@ // Copyright © Timothy van der Ham (@Tim81) // SPDX-License-Identifier: Apache-2.0 +using System.Text.RegularExpressions; using VellumPdf.Fonts; using VellumPdf.Layout.Core; using VellumPdf.Layout.Elements.Table; using VellumPdf.Layout.Rendering.Table; +using VellumPdf.TestSupport; using static VellumPdf.Layout.Tests.ContinuationSupport; namespace VellumPdf.Layout.Tests; @@ -134,6 +136,58 @@ public void ATableAWrapperHolds_isLaidOutAsBeforeItsBreaksWereRead(int wrapKind) Assert.Equal(0, wrapped.Probes); } + /// + /// A line that is empty because of control white space writes no show operator: the line of + /// control characters alone that a table laid out unbroken leaves out, and the blank line a + /// trailing line break leaves in a table that keeps its breaks. A cell that is empty as + /// written still writes its one empty string, as a table without control white space always + /// has, and so does a cell of spaces alone. + /// + [Theory] + [InlineData(false, "(x y)")] + [InlineData(true, "(xy)")] + public void ALineThatIsEmptyBecauseOfControlWhiteSpace_writesNoEmptyShow(bool heldByAWrapper, string expected) + { + var t = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(100, 100, 100, 100); + t.AddRow().AddCell("\t\n").AddCell("").AddCell("x\ty").AddCell(" "); + IRenderer element = heldByAWrapper ? new Wrapper(new TableRenderer(t), WrapKind.PassThrough) : new TableRenderer(t); + + var outcome = Run(TwoHundred, element); + + Assert.Null(outcome.Error); + var content = PdfTestUtil.DecompressAllFlatStreams(outcome.Bytes!); + Assert.Single(Regex.Matches(content, "(?m)^" + Regex.Escape(expected) + " Tj$")); + + // The cell that is empty as written and the cell of spaces alone each write their empty + // string, in both layouts, as they do in a table that holds no control white space. + var empties = Regex.Matches(content, @"(?m)^\(\) Tj$").Count; + Assert.Equal(2, empties); + } + + /// + /// A table that holds no control white space reports its bound as every other table does, + /// though its two layouts are one. A call that reports nothing makes the document lay out the + /// rest of the placement as the twin, a new renderer that has none of the lines a cut row + /// carried, so the row would be drawn again from its first line on the next page. + /// + [Fact] + public void ATableWithNoControlWhiteSpace_drawsEachLineOfARowCutBetweenItsLinesOnce() + { + var table = new TableElement { DefaultCellStyle = Helvetica() }.SetColumnWidths(100, 100); + table.AddRow().AddCell(string.Join(" ", Enumerable.Range(0, 80).Select(i => "w" + i))).AddCell("side"); + table.AddRow().AddCell("after").AddCell("row"); + var page = new Setup { PageWidth = 400, PageHeight = 100 }; + + var kept = Run(page, new TableRenderer(table)); + var oneLine = Run(page, new TableRenderer(table), measuredAsOneLine: true); + + Assert.Null(kept.Error); + var words = Regex.Matches(PdfTestUtil.DecompressAllFlatStreams(kept.Bytes!), @"\bw[0-9]+\b"); + Assert.Equal(80, words.Count); + Assert.Equal(80, words.Select(m => m.Value).Distinct().Count()); + Assert.Equal(oneLine.Bytes, kept.Bytes); + } + /// /// A wrapper that lays the table out under a context it builds knows no fresh page, so the /// table cuts no row, as the table did before its breaks were read: the cell that does not fit From d0b12fcd4c015ecb35874cbf12ffe1929a62d07b Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 23 Nov 2026 00:02:28 +0100 Subject: [PATCH 43/48] test(layout): pin that a control character in a cell is not a strict refusal A tab, a line break or another control white-space character in a cell reaches no font, so the save lists no NotdefGlyph or UnencodableCharacter for it and StrictDiagnostics does not refuse the cell. That holds for a table the document lays out and for one a caller's renderer holds, which draws the character as nothing, and a PDF/A-2u file made that way passes veraPDF. A control character that is not white space is still refused. The XML documentation of Cell.Content and TableRenderer.Layout and the CHANGELOG now say so, and list the output change of a table a caller's renderer holds, which leaves the control characters out of the drawing, and the position of a centred band that holds a tab. --- CHANGELOG.md | 33 +++- src/VellumPdf.Layout/Elements/Table/Cell.cs | 17 +- .../Rendering/Table/TableRenderer.cs | 6 +- .../TableStrictDiagnosticsTests.cs | 172 ++++++++++++++++++ 4 files changed, 213 insertions(+), 15 deletions(-) create mode 100644 tests/VellumPdf.Layout.Tests/TableStrictDiagnosticsTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f4b1fa88..7d9585086 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -666,8 +666,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). template and in the text a page label prints for `{page}`, so a CR LF pair is two spaces, the form feed of #613 item 34 is a space there too, and a band's text is measured and cut as drawn. **Deliberate output changes:** - - `AB` in a cell is `(A B)` in Standard 14 and a space glyph between the two letters in an - embedded font (glyph 3 in DejaVu Sans), with no `<0000>` entry in the ToUnicode map. + - `AB` in a cell of a table the document lays out is `(A B)` in Standard 14 and a space + glyph between the two letters in an embedded font (glyph 3 in DejaVu Sans), with no `<0000>` + entry in the ToUnicode map. A table that a renderer of yours holds is the next item. - `line1line2` is two show strings, the second one leading lower, in a row 14.4 + 14.4 + 8 pt tall at 12 pt, where it was one. A table whose cell holds a line break gets taller rows and different automatic column widths. A table that holds none of tab, carriage return, line feed, @@ -679,7 +680,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). width for that character, zero in Helvetica, and now measures each as one space. A band that fit can therefore be cut: `A` followed by 120 tabs and `B` in Helvetica 10 on a 300 pt page saved with no truncation, and now draws 1 of its 122 characters and reports `BandTruncated`, - which `StrictDiagnostics` refuses. + which `StrictDiagnostics` refuses. A centred band that holds a tab is placed by that width + too: it moves by half the difference between the width its font gave the tab and the width of + a space, and a right-aligned one by the whole difference. `Page {page}of {total}` at 8 pt + in Helvetica, where the tab measured 0, starts 1.112 pt further left centred and 2.224 pt + further left right-aligned. In DejaVu Sans, where the glyph 0 the tab was written as is wider + than a space, it starts 1.128 pt and 2.256 pt further right. A left-aligned band does not + move. - **A table that is refused when every cell is measured as one line stays refused.** That is how 2.3.3 measured a table. Reading a cell's line breaks can leave a column wider or narrower than that measurement does, and so tip a `RowSpan` group the other way. Such a table is @@ -705,10 +712,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **A table is laid out with its breaks read only where the document lays it out.** A `TableRenderer` that a renderer of yours holds and forwards `Layout` to, or that you lay out with a `LayoutContext` you build or narrow with `WithArea`, reads every cell unbroken and - reports nothing, as the table did before breaks were honoured, so its pages and its refusals - are those of that layout and not of the document's, however many lines its cells hold. Such a - renderer's `Draw` must forward to the same table. `IRenderer.Layout`, `TableRenderer.Layout` and - `TableElement` say so. + reports nothing, as the table did before breaks were honoured, so its pages and what it refuses + for room or for the continuation limit are those of that layout and not of the document's, + however many lines its cells hold. Such a renderer's `Draw` must forward to the same table. + `IRenderer.Layout`, `TableRenderer.Layout` and `TableElement` say so. + **Deliberate output change:** that table leaves each tab, line break and other control + white-space character out of what it draws, where a table laid out before wrote glyph 0 or a + raw control byte for it. `AB` is `(AB)`, a DejaVu Sans cell holds no glyph 0 and no + `<0000>` entry in the ToUnicode map, and the save lists no `NotdefGlyph` or + `UnencodableCharacter` for it. The table does not read the character as a space, because that + would draw it wider than the layout measured it. + - **`StrictDiagnostics` does not refuse a control character in a cell.** A tab, a line break + or another control white-space character in a cell reaches no font, so the save lists no + `NotdefGlyph` (102) or `UnencodableCharacter` (103) for it, in a table the document lays out + and in one a renderer of yours holds. A document whose only error items were those reports + saves with the switch on. Any other error item still refuses it, and with the switch off + nothing a table refuses changes. - **A repeated header row, or rows joined by a `RowSpan`, keep the one-line layout of their cells when reading the cells' breaks would leave them no room on a page.** Those rows are never cut between their lines, so reading the breaks would turn a table that saved into a too-tall diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 185a3db77..3c47d8e5f 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -27,13 +27,16 @@ public sealed class Cell /// here, where a draws one. Runs of spaces are kept as /// written, where a paragraph collapses them. Every other white-space control character, which /// is a tab, a form feed, a line tabulation, a next-line character, U+2028 and U+2029, is one - /// space, so it reaches no font as a control character. The no-break spaces are written as they - /// are, as in a paragraph. The other space separators, such as U+2003, are written as they are - /// too, where a paragraph reads them as spaces. A column sized automatically takes its minimum - /// from the widest word and its maximum from the widest line, each line of the cell measured on - /// its own, where 2.3.3 measured the whole text as one line. The width the column is then - /// given is shared out among the columns as it was, and can be more than the maximum or less - /// than the minimum. + /// space, so it reaches no font as a control character. None of these characters is reported + /// as or + /// , so + /// does not refuse a cell for one. The no-break + /// spaces are written as they are, as in a paragraph. The other space separators, such as + /// U+2003, are written as they are too, where a paragraph reads them as spaces. A column sized + /// automatically takes its minimum from the widest word and its maximum from the widest line, + /// each line of the cell measured on its own, where 2.3.3 measured the whole text as one line. + /// The width the column is then given is shared out among the columns as it was, and can be + /// more than the maximum or less than the minimum. /// A control character that is not white space, such as U+0001, is written as it is: in a /// standard-14 font as its WinAnsi code, and in an embedded font as whatever glyph the font's /// character map gives it, which is .notdef (glyph 0) when the map has no entry. The save lists diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 1479c5d31..b4d1ad7b3 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -231,7 +231,11 @@ IRenderer IContinuationTwin.Twin() => /// and forwards to it, every cell is wrapped /// at spaces alone and measured with its control characters, and drawn without them, as the /// table was laid out before the breaks were read (#679). Nothing is reported for it, and the - /// two layouts can take a different number of pages. Do not pass a table to a renderer + /// characters it leaves out are listed as neither + /// nor + /// , so + /// does not refuse the table for them. The two + /// layouts can take a different number of pages. Do not pass a table to a renderer /// of yours in the expectation that its line breaks are drawn: add it with /// . A renderer of yours that forwards /// must forward to the same table as well. 3.0 lays a diff --git a/tests/VellumPdf.Layout.Tests/TableStrictDiagnosticsTests.cs b/tests/VellumPdf.Layout.Tests/TableStrictDiagnosticsTests.cs new file mode 100644 index 000000000..a9fa008ab --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableStrictDiagnosticsTests.cs @@ -0,0 +1,172 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements.Table; +using VellumPdf.Layout.Rendering.Table; +using VellumPdf.TestSupport; +using static VellumPdf.Layout.Tests.ContinuationSupport; + +namespace VellumPdf.Layout.Tests; + +/// +/// A tab, a line break or another control white-space character in a table cell reaches no font, +/// so the save lists no NotdefGlyph or UnencodableCharacter for it and +/// does not refuse the cell (#611). That holds for a +/// table the document lays out and for one that a caller's renderer holds, which draws the +/// character as nothing. A control character that is not white space is still reported and +/// refused. +/// +public sealed class TableStrictDiagnosticsTests : IDisposable +{ + private static readonly string DejaVu = Path.Combine(AppContext.BaseDirectory, "Fonts", "DejaVuSans.ttf"); + + private readonly string _tempDir; + + public TableStrictDiagnosticsTests() + { + _tempDir = Path.Combine(Path.GetTempPath(), $"vellumstrictcell_{Guid.NewGuid():N}"); + Directory.CreateDirectory(_tempDir); + } + + public void Dispose() + { + try { Directory.Delete(_tempDir, recursive: true); } + catch (IOException) { /* best-effort cleanup */ } + catch (UnauthorizedAccessException) { /* best-effort cleanup */ } + } + + private static void RequireDejaVu() + { + if (!File.Exists(DejaVu)) + OracleGate.Unavailable("DejaVuSans.ttf", "DejaVu Sans is needed for an embedded font."); + } + + private static Document StrictDocument(PdfConformance conformance = PdfConformance.None) => new() + { + PageSize = new PdfRectangle(0, 0, 400, 400), + Margins = new EdgeInsets(10), + Conformance = conformance, + StrictDiagnostics = true, + }; + + private static void AddTable(Document doc, TableElement table, bool heldByAWrapper) + { + if (heldByAWrapper) + doc.Add(new Wrapper(new TableRenderer(table), WrapKind.PassThrough)); + else + doc.Add(table); + } + + private static byte[] Save(Document doc) + { + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + private static string[] Reported(Document doc) => + [.. doc.Diagnostics.Where(d => d.Code is LayoutDiagnosticCode.NotdefGlyph or LayoutDiagnosticCode.UnencodableCharacter) + .Select(d => d.Message)]; + + /// + /// An embedded font has no glyph for a tab, a line feed, a carriage return, a form feed or the + /// line separators, so each reaching the font would be glyph 0 and a refusal under the switch. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AnEmbeddedCellWithControlWhiteSpace_saves_underStrictDiagnostics(bool heldByAWrapper) + { + RequireDejaVu(); + using var doc = StrictDocument(); + var font = doc.UseTrueTypeFont(File.ReadAllBytes(DejaVu)); + var table = new TableElement { DefaultCellStyle = new TextStyle { FontRef = font, FontSize = 10 } } + .SetColumnWidths(90, 90, 90, 90); + table.AddRow().AddCell("A\tB").AddCell("line1\nline2").AddCell("cr1\r\ncr2").AddCell("ff\fx\u0085y\u2028z\u2029w"); + AddTable(doc, table, heldByAWrapper); + + var bytes = Save(doc); + + Assert.NotEmpty(bytes); + Assert.Empty(Reported(doc)); + } + + /// + /// A Standard 14 font cannot encode U+2028, which the table would otherwise write as a question + /// mark and report as UnencodableCharacter; a tab it would write as a raw 0x09 byte. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AStandard14CellWithControlWhiteSpace_saves_underStrictDiagnostics(bool heldByAWrapper) + { + using var doc = StrictDocument(); + var table = new TableElement + { + DefaultCellStyle = new TextStyle { FontRef = new FontReference(Standard14.Helvetica), FontSize = 10 }, + }.SetColumnWidths(90, 90, 90); + table.AddRow().AddCell("A\u2028B").AddCell("a\tb").AddCell("one\ntwo\u2029three"); + AddTable(doc, table, heldByAWrapper); + + var bytes = Save(doc); + + Assert.NotEmpty(bytes); + Assert.Empty(Reported(doc)); + } + + /// + /// A control character that is not white space still reaches the font, so the report and the + /// refusal stay: the switch refuses the cell for U+0001, whoever holds the table. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ACellWithAControlCharacterThatIsNotWhiteSpace_isStillRefused_underStrictDiagnostics(bool heldByAWrapper) + { + RequireDejaVu(); + using var doc = StrictDocument(); + var font = doc.UseTrueTypeFont(File.ReadAllBytes(DejaVu)); + var table = new TableElement { DefaultCellStyle = new TextStyle { FontRef = font, FontSize = 10 } } + .SetColumnWidths(90); + table.AddRow().AddCell("a\u0001b"); + AddTable(doc, table, heldByAWrapper); + + var ex = Assert.Throws(() => Save(doc)); + + Assert.Contains("NotdefGlyph", ex.Message, StringComparison.Ordinal); + Assert.Contains("U+0001", ex.Message, StringComparison.Ordinal); + } + + /// + /// The output the switch lets through is correct, which the oracle says: a PDF/A-2u document + /// with a table holding a tab and a line break, behind a renderer of the caller's, passes + /// veraPDF, where glyph 0 in the file fails clause 6.2.11.8. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AStrictPdfA2uDocumentWithControlWhiteSpaceInACell_passesVeraPdf(bool heldByAWrapper) + { + RequireDejaVu(); + using var doc = StrictDocument(PdfConformance.PdfA2u); + doc.Info.Title = "Strict cells"; + var font = doc.UseTrueTypeFont(File.ReadAllBytes(DejaVu)); + var table = new TableElement { DefaultCellStyle = new TextStyle { FontRef = font, FontSize = 10 } } + .SetColumnWidths(100, 100); + table.AddRow().AddCell("a\tb").AddCell("plain"); + table.AddRow().AddCell("line1\nline2").AddCell("c\td"); + AddTable(doc, table, heldByAWrapper); + var path = Path.Combine(_tempDir, heldByAWrapper ? "held.pdf" : "direct.pdf"); + File.WriteAllBytes(path, Save(doc)); + + ExternalTool.TryRun("verapdf", ["--flavour", "2u", path], + out var exit, out var report, out var err, out var timedOut, timeoutMs: 120_000); + + Assert.False(timedOut); + Assert.True(exit is 0 or 1, $"veraPDF exited {exit}\n{report}\n{err}"); + Assert.True(report.Contains("isCompliant=\"true\"", StringComparison.Ordinal), report); + } +} From 935c327702e4a98f40518f653f2d88dbe6768c43 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 23 Nov 2026 02:10:20 +0100 Subject: [PATCH 44/48] docs(layout): say what the depth probe's comment measured on main The comment gave one run's result as the general one. State the runs: both probes failed in four sequential runs on main, on net10.0 and on net11.0, and one net11.0 run passed. The inlining cause stays a likely cause, not an established one. --- .../PaginationDepthTests.cs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs b/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs index fecea6d33..549d44722 100644 --- a/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs +++ b/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs @@ -78,13 +78,14 @@ private static void AssertFlat(IReadOnlyList samples) // renderer, which never reports, in either pass, and a recursion regression makes it grow // with the continuation count. A renderer that reports has two on the stack during a // continuation probe, because the probe calls PlaceLoop from inside PlaceLoop. - // PlaceRenderer, which only starts the loop, was counted before. Its count read 0 on - // net10.0 in a full run of the whole suite in sequence (-parallel none), and the same run - // on net11.0 did not. The likely cause is that the JIT inlined it into its caller, which - // was not confirmed with a JIT dump. PlaceLoop is marked NoInlining so that it keeps a - // frame of its own. 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. + // PlaceRenderer, which only starts the loop, was counted before. Its count read 0 when + // the whole suite ran in sequence (-parallel none): on main at c44a516, both probes + // failed in four such runs, two on net10.0 and two on net11.0, and a fifth run, on + // net11.0, passed. The likely cause is that the JIT inlined PlaceRenderer into its + // caller; that was not confirmed with a JIT dump. PlaceLoop is marked NoInlining so that + // it keeps a frame of its own. 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()); } From b0a227448c868b6348062e4e94e16b89d21cef6c Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 23 Nov 2026 02:22:04 +0100 Subject: [PATCH 45/48] docs(layout): say which empty lines a cell with control white space skips The skip covers every empty line of a cell that holds control white space, a line of spaces alone included, not only a line the control characters emptied. --- src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index b4d1ad7b3..7a3761a3d 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -1961,11 +1961,12 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, { var line = wrappedLines[firstLine + lineIdx]; - // A line that is empty because of control white space writes no text: an empty string - // would only be a show operator that draws nothing. That is the line of control - // characters a cell laid out unbroken leaves out, and the blank line between two line - // breaks. A cell that holds none of them is not touched, so a table without control - // white space keeps its bytes, an empty cell and one of spaces alone included. + // Every empty line of a cell that holds control white space writes no text: an empty + // string would only be a show operator that draws nothing. Those are the line of + // control characters a cell laid out unbroken leaves out, the blank line between two + // line breaks, and a line of spaces alone in such a cell, which the wrap empties. A + // cell that holds no control white space is not touched, so a table without any keeps + // its bytes, an empty cell and one of spaces alone included. if (line.Length == 0 && holdsControlSpace) continue; var lineW = cs.FontRef.MeasureString(line, cs.FontSize); From 505a4afaac50029c202d66027d0943298815d0b5 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 23 Nov 2026 02:25:31 +0100 Subject: [PATCH 46/48] test(layout): pin that a band's control white space is not a strict refusal A tab, line break or form feed in a band template or a page label is drawn as a space, so StrictDiagnostics has nothing to refuse. A PDF/A-2u band passes veraPDF, and U+0001 in a band is still refused. --- .../TableStrictDiagnosticsTests.cs | 75 ++++++++++++++++++- 1 file changed, 73 insertions(+), 2 deletions(-) diff --git a/tests/VellumPdf.Layout.Tests/TableStrictDiagnosticsTests.cs b/tests/VellumPdf.Layout.Tests/TableStrictDiagnosticsTests.cs index a9fa008ab..30745bcc3 100644 --- a/tests/VellumPdf.Layout.Tests/TableStrictDiagnosticsTests.cs +++ b/tests/VellumPdf.Layout.Tests/TableStrictDiagnosticsTests.cs @@ -4,6 +4,7 @@ using VellumPdf.Document; using VellumPdf.Fonts; using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; using VellumPdf.Layout.Elements.Table; using VellumPdf.Layout.Rendering.Table; using VellumPdf.TestSupport; @@ -16,8 +17,9 @@ namespace VellumPdf.Layout.Tests; /// so the save lists no NotdefGlyph or UnencodableCharacter for it and /// does not refuse the cell (#611). That holds for a /// table the document lays out and for one that a caller's renderer holds, which draws the -/// character as nothing. A control character that is not white space is still reported and -/// refused. +/// character as nothing. A running band reads the same characters as spaces, in its template and +/// in a page label, so does not refuse a band for one +/// either. A control character that is not white space is still reported and refused. /// public sealed class TableStrictDiagnosticsTests : IDisposable { @@ -169,4 +171,73 @@ public void AStrictPdfA2uDocumentWithControlWhiteSpaceInACell_passesVeraPdf(bool Assert.True(exit is 0 or 1, $"veraPDF exited {exit}\n{report}\n{err}"); Assert.True(report.Contains("isCompliant=\"true\"", StringComparison.Ordinal), report); } + + /// + /// A band draws a tab, a line feed, a form feed or a line separator as a space, so a + /// Standard 14 band that holds them saves under the switch with nothing reported. The page + /// label's prefix is read the same way. + /// + [Fact] + public void AStandard14BandWithControlWhiteSpace_saves_underStrictDiagnostics() + { + using var doc = StrictDocument(); + var style = new TextStyle { FontRef = new FontReference(Standard14.Helvetica), FontSize = 10 }; + doc.PageLabel = new PageLabelRange(PdfPageLabelStyle.Decimal, "A\tB\u2028", 1); + doc.SetHeader("head\tline\nbreak\u2028", style); + doc.SetFooter("p\f{page}", style); + doc.Add(new Paragraph("body", style)); + + var bytes = Save(doc); + + Assert.NotEmpty(bytes); + Assert.Empty(Reported(doc)); + } + + /// + /// The band's output the switch lets through is correct, which the oracle says: a PDF/A-2u + /// document whose header, footer and page label hold a tab, a line break and a form feed passes + /// veraPDF. Glyph 0 in the file would fail clause 6.2.11.8. + /// + [Fact] + public void AStrictPdfA2uDocumentWithControlWhiteSpaceInABand_passesVeraPdf() + { + RequireDejaVu(); + using var doc = StrictDocument(PdfConformance.PdfA2u); + doc.Info.Title = "Strict bands"; + var font = doc.UseTrueTypeFont(File.ReadAllBytes(DejaVu)); + var style = new TextStyle { FontRef = font, FontSize = 10 }; + doc.PageLabel = new PageLabelRange(PdfPageLabelStyle.Decimal, "A\tB\n", 1); + doc.SetHeader("head\tline\nbreak", style); + doc.SetFooter("p\f{page}\tof {pages}", style); + doc.Add(new Paragraph("body", style)); + var path = Path.Combine(_tempDir, "band.pdf"); + File.WriteAllBytes(path, Save(doc)); + + Assert.Empty(Reported(doc)); + ExternalTool.TryRun("verapdf", ["--flavour", "2u", path], + out var exit, out var report, out var err, out var timedOut, timeoutMs: 120_000); + + Assert.False(timedOut); + Assert.True(exit is 0 or 1, $"veraPDF exited {exit}\n{report}\n{err}"); + Assert.True(report.Contains("isCompliant=\"true\"", StringComparison.Ordinal), report); + } + + /// + /// A control character that is not white space still reaches the font from a band, so the + /// switch refuses it: the band rule reads white space only. + /// + [Fact] + public void ABandWithAControlCharacterThatIsNotWhiteSpace_isStillRefused_underStrictDiagnostics() + { + RequireDejaVu(); + using var doc = StrictDocument(); + var font = doc.UseTrueTypeFont(File.ReadAllBytes(DejaVu)); + doc.SetHeader("a\u0001b", new TextStyle { FontRef = font, FontSize = 10 }); + doc.Add(new Paragraph("body", new TextStyle { FontRef = font, FontSize = 10 })); + + var ex = Assert.Throws(() => Save(doc)); + + Assert.Contains("NotdefGlyph", ex.Message, StringComparison.Ordinal); + Assert.Contains("U+0001", ex.Message, StringComparison.Ordinal); + } } From 77247f83672c790525822a549a911ecbe7afa590 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 23 Nov 2026 02:25:32 +0100 Subject: [PATCH 47/48] docs(layout): state the strict-mode rule for bands and name what a table wrote before RunningBand.Template and the CHANGELOG now say a control white-space character in a band no longer reports NotdefGlyph or UnencodableCharacter. The CHANGELOG also names what a table wrote for such a character before: glyph 0, a raw byte, ? or the font's own glyph. --- CHANGELOG.md | 22 +++++++++++--------- src/VellumPdf.Layout/Elements/RunningBand.cs | 8 +++++-- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d9585086..d186fb1ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -717,17 +717,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). however many lines its cells hold. Such a renderer's `Draw` must forward to the same table. `IRenderer.Layout`, `TableRenderer.Layout` and `TableElement` say so. **Deliberate output change:** that table leaves each tab, line break and other control - white-space character out of what it draws, where a table laid out before wrote glyph 0 or a - raw control byte for it. `AB` is `(AB)`, a DejaVu Sans cell holds no glyph 0 and no - `<0000>` entry in the ToUnicode map, and the save lists no `NotdefGlyph` or - `UnencodableCharacter` for it. The table does not read the character as a space, because that + white-space character out of what it draws, where a table laid out before wrote glyph 0, a raw + control byte, `?` or the font's own glyph for it. `AB` is `(AB)`, a DejaVu Sans cell + holds no glyph 0 and no `<0000>` entry in the ToUnicode map, and the save lists no + `NotdefGlyph` or `UnencodableCharacter` for it. The table does not read the character as a space, because that would draw it wider than the layout measured it. - - **`StrictDiagnostics` does not refuse a control character in a cell.** A tab, a line break - or another control white-space character in a cell reaches no font, so the save lists no - `NotdefGlyph` (102) or `UnencodableCharacter` (103) for it, in a table the document lays out - and in one a renderer of yours holds. A document whose only error items were those reports - saves with the switch on. Any other error item still refuses it, and with the switch off - nothing a table refuses changes. + - **`StrictDiagnostics` does not refuse a control white-space character in a cell or in a + running band.** A tab, a line break or another control white-space character there reaches + no font, so the save lists no `NotdefGlyph` (102) or `UnencodableCharacter` (103) for it, in + a table the document lays out, in one a renderer of yours holds, in a band template and in + the text a page label prints. A document whose only error items were those reports saves + with the switch on. A control character that is not white space, such as U+0001, is reported + as before. Any other error item still refuses the document, and with the switch off nothing + a table refuses changes. - **A repeated header row, or rows joined by a `RowSpan`, keep the one-line layout of their cells when reading the cells' breaks would leave them no room on a page.** Those rows are never cut between their lines, so reading the breaks would turn a table that saved into a too-tall diff --git a/src/VellumPdf.Layout/Elements/RunningBand.cs b/src/VellumPdf.Layout/Elements/RunningBand.cs index 2cbbd2320..4c6baedc4 100644 --- a/src/VellumPdf.Layout/Elements/RunningBand.cs +++ b/src/VellumPdf.Layout/Elements/RunningBand.cs @@ -79,8 +79,12 @@ public sealed class RunningBand /// white-space control character in the template is drawn as one space and measured as one, /// so a carriage return and line feed pair is two spaces, and no white-space control /// character reaches the font from it. The same holds for the text a - /// prints for {page}. A control character that is not white - /// space, such as U+0001, is written as it is. + /// prints for {page}. None of these characters is reported + /// as or + /// , so + /// does not refuse a band for one. A control + /// character that is not white space, such as U+0001, is written as it is; + /// says when it is reported. /// Not checked when it is set: the constructor stores a null template, and the save /// throws where the band is first drawn. A template that /// does not fit the content box is truncated, and refused only in strict mode; From 7d6850807bdbbeaebfb1bde859125b9f18aa0e98 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Mon, 23 Nov 2026 02:34:19 +0100 Subject: [PATCH 48/48] docs(changelog): wrap the caller-held table entry at 100 columns --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d186fb1ca..abbf0981d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -720,8 +720,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). white-space character out of what it draws, where a table laid out before wrote glyph 0, a raw control byte, `?` or the font's own glyph for it. `AB` is `(AB)`, a DejaVu Sans cell holds no glyph 0 and no `<0000>` entry in the ToUnicode map, and the save lists no - `NotdefGlyph` or `UnencodableCharacter` for it. The table does not read the character as a space, because that - would draw it wider than the layout measured it. + `NotdefGlyph` or `UnencodableCharacter` for it. The table does not read the character as a + space, because that would draw it wider than the layout measured it. - **`StrictDiagnostics` does not refuse a control white-space character in a cell or in a running band.** A tab, a line break or another control white-space character there reaches no font, so the save lists no `NotdefGlyph` (102) or `UnencodableCharacter` (103) for it, in