diff --git a/CHANGELOG.md b/CHANGELOG.md index 15375aab..abbf0981 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,16 @@ 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 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, 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 + 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 @@ -391,8 +401,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 @@ -637,6 +647,133 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). start of a line. **Deliberate output change:** a justified embedded-font line that holds a leading space, or two spaces in a row (reachable through tab stops), is drawn with those spaces and a different spread. Every other document keeps its bytes. +- **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 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 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 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 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, + form feed, line tabulation, next-line character, U+2028 and U+2029 saves to the same bytes as + 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 + saved with no truncation, and now draws 1 of its 122 characters and reports `BandTruncated`, + 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 + 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 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 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 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, 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 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 + 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 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. 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 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 + 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 + 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 + 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.Kernel/Fonts/EmbeddedFontHandle.cs b/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs index ac3d70df..ac970d94 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 4b6ffdc4..cfc5736e 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 c4a1bb1e..c498e2c0 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/Core/IRenderer.cs b/src/VellumPdf.Layout/Core/IRenderer.cs index ad8e3b2e..7c043083 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 30f497b7..09e2513e 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/Core/LayoutText.cs b/src/VellumPdf.Layout/Core/LayoutText.cs new file mode 100644 index 00000000..3622efbe --- /dev/null +++ b/src/VellumPdf.Layout/Core/LayoutText.cs @@ -0,0 +1,107 @@ +// 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 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 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) => Replace(text, IsControlSpace); + + private static string Replace(string text, Func test) + { + var at = -1; + for (var i = 0; i < text.Length; i++) + { + if (test(text[i])) { at = i; break; } + } + if (at < 0) return text; + + 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 (state.test(span[i])) span[i] = ' '; + }); + } +} diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index dcf32ba1..868bf8f0 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -119,6 +119,8 @@ public Document() { } /// (mirroring ), /// (a preformatted line split with /// a marker; a warning, which saves), + /// (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/Elements/BandTemplate.cs b/src/VellumPdf.Layout/Elements/BandTemplate.cs index 50d56acf..ea61d505 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; /// @@ -184,12 +186,16 @@ 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) { - _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); _values[(int)BandToken.Chapter] = chapter ?? ""; @@ -212,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 @@ -275,7 +254,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 2f07b83c..4c6baedc 100644 --- a/src/VellumPdf.Layout/Elements/RunningBand.cs +++ b/src/VellumPdf.Layout/Elements/RunningBand.cs @@ -75,9 +75,19 @@ public sealed class RunningBand /// Text template — may contain {page} and/or {pages}, and {chapter} when /// is set. /// - /// 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; + /// 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}. 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; /// says when it /// counts as not fitting. The cut is reported through Document.BandTruncations, /// DocumentRenderer.BandTruncations and, with error severity, as @@ -85,17 +95,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 @@ -284,6 +295,11 @@ 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 433d5563..3c47d8e5 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -20,12 +20,100 @@ 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. 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, 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 + /// each such character as , and + /// refuses it; see + /// . + /// 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, 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 + /// group has no room when it is taller than what a page leaves under the repeated header + /// 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 + /// 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. + /// 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 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 + /// 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 + /// 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 + /// 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 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/Row.cs b/src/VellumPdf.Layout/Elements/Table/Row.cs index 21ca890b..9b6829e7 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 509828fe..8fb5e33d 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 @@ -30,6 +32,15 @@ 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 +/// 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, +/// 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 @@ -45,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/LayoutDiagnostic.cs b/src/VellumPdf.Layout/LayoutDiagnostic.cs index 5ad0b9c1..da5a719a 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.CellWhiteSpaceDropped => LayoutDiagnosticSeverity.Warning, LayoutDiagnosticCode.KeepWithNextRelaxed => LayoutDiagnosticSeverity.Warning, LayoutDiagnosticCode.KeepTogetherRelaxed => LayoutDiagnosticSeverity.Warning, LayoutDiagnosticCode.MinLinesRelaxed => LayoutDiagnosticSeverity.Warning, diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index c659bd22..9fb5ed24 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -23,10 +23,9 @@ 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, and one 7xx member for a link - // dropped from a cell or band under a PDF/UA claim. The rest of the 8xx block stays free for - // later pagination reports. + // ListEntriesCapped, 206 ListEntrySkipped (all Error), 302 SurplusCell (Error), 402 + // UnknownBandToken, and one 7xx member for a link dropped from a cell or band under a PDF/UA + // claim. The rest of the 8xx block stays free for later pagination reports. /// /// A with a null style that yields no word, so it saved without @@ -64,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 @@ -117,6 +116,27 @@ public enum LayoutDiagnosticCode /// TabStopBeyondWidth = 106, + /// + /// 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, 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 + /// 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. + /// 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. A cell with more lines than a document can hold is the other case: shorten the text + /// or split the table. + /// + CellWhiteSpaceDropped = 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 e705eb98..be3c4f41 100644 --- a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt +++ b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt @@ -100,6 +100,7 @@ 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.CellWhiteSpaceDropped = 301 -> VellumPdf.Layout.LayoutDiagnosticCode VellumPdf.Layout.LayoutElementKind.Preformatted = 11 -> VellumPdf.Layout.LayoutElementKind VellumPdf.Layout.Document.MirrorMargins.get -> bool VellumPdf.Layout.Document.MirrorMargins.set -> void diff --git a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs index 9529b3f7..98f8f58b 100644 --- a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs @@ -577,7 +577,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; } @@ -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/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs b/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs index 0b901ef1..f733ff13 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableGridResolver.cs @@ -30,8 +30,34 @@ 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; } + + /// + /// 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; } + + /// + /// 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 @@ -56,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; } @@ -156,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]; @@ -234,9 +267,9 @@ 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); + var (minW, maxW) = ContentOf(table, cols); // Distribute available width proportionally to max-content widths var totalMax = maxW.Sum(); @@ -272,31 +305,67 @@ 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 /// 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. 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) + { + (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; var share = cell.ColSpan; for (var s = 0; s < share && col + s < cols; s++) @@ -309,4 +378,23 @@ private static (double[] MinW, double[] MaxW) ContentWidths(TableElement table, } return (minW, maxW); } + + /// + /// The widest word and the widest line of a cell's text, each line measured on its own. + /// + internal 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 00000000..47b4dc82 --- /dev/null +++ b/src/VellumPdf.Layout/Rendering/Table/TableMeasureCache.cs @@ -0,0 +1,139 @@ +// 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 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, 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. +/// +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; + + /// True when and the interval that holds it are set. + public bool HasLines; + + /// 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 && From <= width && width < Below; +} + +/// +/// A hook for tests of the table caches: counts what the caches answered, and when +/// 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 +{ + [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; + } + + /// + /// When set, a cached line count is checked against a fresh wrap on every hit. + /// + 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. A compatibility device, + /// removed in 3.0 (#688), with the twin it stands in for. + /// + public bool ReadEveryCellUnbroken { 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; } + + /// 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; } + + /// + /// 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. + /// + 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 cec3f873..7a3761a3 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, IContinuationTwin { private readonly TableElement _table; private readonly int _startRow; // first data row index (0-based) @@ -56,6 +56,63 @@ public sealed class TableRenderer : IRenderer, IPageBreakSource, IKeepSource, IP 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 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; + + // 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; + + // 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; + + // 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 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 + // 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; + + // 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 + // 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; + /// The lines each cell of one row wraps into, at one table width. private sealed class RowLines(int row, double width, List?[] cells) { @@ -138,6 +195,13 @@ void IPlacementSource.ReportPlacements(PlacementSink sink) internal TableElement Element => _table; + // 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. /// /// Overflow splits at a row boundary. A row that does not fit the area is cut between its @@ -156,6 +220,26 @@ 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 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 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 + /// 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 + /// 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 @@ -191,6 +275,20 @@ void IPlacementSource.ReportPlacements(PlacementSink sink) /// 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(); @@ -211,58 +309,133 @@ 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; - // 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++) + // 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) { - var cells = _table.Rows[r].Cells; - for (var c = 0; c < cells.Count; c++) - LayoutValidation.ValidateCell(cells[c], r, c); + _oneLine = null; + _allUnbroken = false; } - LayoutValidation.ValidateLineWidthIsFinite(_table.BorderWidth, "A table"); + // 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) + { + if (TableMeasureProbe.Current is { } held) held.GridsReused++; + } + else + { + var oneLineBound = 0L; - var grid = new TableGridResolver(); - grid.Resolve(_table, area.Width); - _colWidths = grid.ColWidths; + // 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); + } - // #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); + LayoutValidation.ValidateLineWidthIsFinite(_table.BorderWidth, "A table"); - // Compute row heights - _rowHeights = new double[rows.Count]; + // 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); - 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) + // A test measures the table as it was before breaks were honoured: every cell as + // 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 })) { - 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; + _allUnbroken = true; + passesNeeded = false; } - _rowHeights[r] = maxH; + + 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; 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) + { + _oneLine ??= []; + _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)) + { + // 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. + // Removed in 3.0 (#688). + oneLineBound = ContinuationBoundOf(fresh!); + _allUnbroken = false; + (_colWidths, _rowHeights) = (widths, heights); + } + } + } + _measured = null; + _content = null; + _decidedFor = key; + 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. Removed in 3.0 (#688). + 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 @@ -278,10 +451,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; @@ -358,28 +527,726 @@ 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, - }; + }); var overflow = tail is null - ? new TableRenderer(_table, lastFit + 1) { _continuation = true, _colWidths = _colWidths, _rowHeights = _rowHeights } - : 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(), - }; + }); 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._placedAsTwin = _placedAsTwin; + next._reportBound = _reportBound; + 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. + /// + 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 = _allUnbroken ? EveryCell.Instance : _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 + // 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++) + _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; + 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; + + // 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); + 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; + } + 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); + entry.HasLines = true; + return entry.Lines; + } + + /// + /// The number of lines returns, without building them, and the + /// 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) + { + from = double.NegativeInfinity; + below = double.PositiveInfinity; + 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); + return total; + } + + private static int CountLine( + string text, TextStyle style, double maxWidth, ref double from, ref double below) + { + 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); + lines += CountHardBreakFragments(word, style, maxWidth, ref from, ref below); + 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. 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(RuneString(rune), style.FontSize); + if (open) + { + 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; + } + if (open) fragments++; + 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. + /// + 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) + { + 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 to lay out unbroken in the next pass, or null when there are none that are not + /// 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. 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. 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) + { + 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; + + // 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 + // 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; + + // 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; + + // 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(widths[i]) != BitConverter.DoubleToInt64Bits(_colWidths[i])) + return false; + if (TableMeasureProbe.Current is { } probe) probe.StepsKeptPassGoing++; + return true; + } + + // 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; } + } + + // 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++) + { + var cells = rows[r].Cells; + var col = 0; + for (var c = 0; c < cells.Count; c++) + { + var span = cells[c].ColSpan; + if (HonoursBreaks(r, c) && LayoutText.HasLineBreak(cells[c].Content) && (found ??= []).Add((r, c))) + { + added = true; + Note(r, c, col, span); + } + col += span; + } + } + 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)) + && (found ??= []).Add((r, c))) + { + added = true; + Note(r, c, col, span); + } + col += span; + } + } + 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))) + { + if (CollectBreaks(0, header[^1]) || CollectControlSpace(0, header[^1])) return found; + exhausted = true; + } + + foreach (var (first, last) in SpanGroups(lastHeaderRow)) + { + // 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) + { + 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, 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); + shared = false; + outside = false; + step.Clear(); + if (CollectBreaks(first, last)) + { + if (shared && !ColumnWidthsHold()) return found; + + // 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); + 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 + // 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; + } + } + 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 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); + } + + /// + /// 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 + /// 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 + /// 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. + /// + 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 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; + 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); + if (q < firstDataRow) + { + headerReach = Math.Max(headerReach, end); + continue; + } + + if (groups.Count > 0 && q <= groups[^1].Last) + groups[^1] = (groups[^1].First, Math.Max(groups[^1].Last, end)); + else + 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)); + } + while (next < groups.Count) all.Add(groups[next++]); + return all; + } + // ── Cutting a row between its lines ── /// What a layout call knows about the page a refused row would have to fit. @@ -408,6 +1275,131 @@ 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. + /// 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) + { + 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; + 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; + 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); + } + + 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; + } + + /// + /// 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 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) + { + 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; + + 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 @@ -474,7 +1466,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); @@ -611,6 +1603,16 @@ 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."); + + // 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."); + /// Draws cell backgrounds, borders and text (repeating header rows) and builds the tagged Table struct tree when tagging is enabled. /// /// See . @@ -638,6 +1640,13 @@ private static string RowRange(int first, int last) => /// public void Draw(DrawContext ctx) { + // Laid out by the twin, which holds what was decided. Removed in 3.0 (#688). + 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 @@ -900,10 +1909,27 @@ 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 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. + var holdsControlSpace = LayoutText.HasControlSpace(cell.Content); + if ((!_readsUnbrokenForTheLimit || _placedAsTwin) + && !HonoursBreaks(rowIndex, cellIndex) && holdsControlSpace + && (slice is null || slice.First[cellIndex] == 0)) + { + ctx.Diagnostics?.Report( + LayoutDiagnosticCode.CellWhiteSpaceDropped, + ((long)rowIndex << 32) | (uint)cellIndex, + _readsUnbrokenForTheLimit ? DroppedForTheLimit : DroppedForRoom, + 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) @@ -934,6 +1960,15 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, for (var lineIdx = 0; lineIdx < lineCount; lineIdx++) { var line = wrappedLines[firstLine + lineIdx]; + + // 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); // Floored at the cell's own left edge (#473), the same clamp #472 applied to a @@ -1059,8 +2094,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; + internal 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 @@ -1085,7 +2120,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; } @@ -1136,6 +2171,53 @@ 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, 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 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. + /// + internal 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.RemoveControlSpaces(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.Kernel.Tests/PeekGlyphIdTests.cs b/tests/VellumPdf.Kernel.Tests/PeekGlyphIdTests.cs index 2bf7c605..41b6b064 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 3232e6a5..45d4fcd2 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/PageBreakTests.cs b/tests/VellumPdf.Layout.Tests/PageBreakTests.cs index 6852728b..cc01e672 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_andAParagraphHeadingListItemCellAndBandDrawItAsASpace() { 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. 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); - 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/PaginationDepthTests.cs b/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs index 24205ad2..549d4472 100644 --- a/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs +++ b/tests/VellumPdf.Layout.Tests/PaginationDepthTests.cs @@ -74,10 +74,17 @@ 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 - // regression otherwise prints one near-identical failure block per sample — measured at + // 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 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()); @@ -97,7 +104,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 +127,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 diff --git a/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs new file mode 100644 index 00000000..17e3495e --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableCellBreakTests.cs @@ -0,0 +1,1622 @@ +// 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; +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 carriage return, a line feed and a pair of them each end a +/// 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 +/// 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: + /// "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" })] + [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 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 ACellAndAParagraphDrawOneMixedTextAsTheSameLines() + { + 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 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_aSpaceSeparatorIsLeftAlone() + { + using var doc = ShortPage(); + var t = Table12(); + t.AddRow().AddCell("a\u2003b").AddCell("c\u00A0d"); + t.AddRow().AddCell("j k").AddCell("l"); + doc.Add(t); + + var content = Content(Save(doc)); + + Assert.Equal(["a?b", "c\u00A0d", "j k", "l"], 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); + } + + /// + /// 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. + /// + [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")] + [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(); + 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); + } + + /// + /// 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. + /// + 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. 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 AHeaderThatWouldLeaveNoRoomForTheRowBelowIsLaidOutUnbroken(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 AHeaderTallerThanAPageIsLaidOutUnbroken() + { + 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 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 ARowSpanGroupThatWouldBeTallerThanAPageIsLaidOutUnbroken(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 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 ARowSpanGroupOfTwoRowsLaysEachBreakingCellOutUnbroken(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.CellWhiteSpaceDropped)); + 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 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 AHeaderLaidOutUnbrokenIsDrawnSoOnEveryPage() + { + 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 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. + /// + [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 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 AHeaderThatTakesTheRoomOfARowSpanGroupIsLaidOutUnbroken() + { + 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 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 left out of the drawing and the report naming the + /// cell. 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("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, 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 WithoutTheDocumentEveryCellIsReadUnbroken() + { + 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.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. + /// + [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 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 ATabInAHeaderThatFitsIsOneSpaceAndIsNotReported() + { + 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); + } + + // ── 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. 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. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AFallbackHeaderLeavesAnUnrelatedRowItsBreaks(bool autoColumns) + { + using var doc = WidePage(); + 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"); + 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); + } + + /// + /// 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. A column given the width 0 is an automatic + /// column, so setting both widths to 0 reads the same. + /// + [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"); + 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. 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. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AHeaderThatATabTipsIsLaidOutUnbroken(bool tabInFirstRow) + { + using var doc = WidePage(); + var t = Wide10(36, 36); + 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); + + 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(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 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 + /// 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); + } + + /// + /// 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")); + } + + /// + /// 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 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); + 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 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); + } + + /// + /// 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 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. + /// + [Fact] + public void TheCostOfGivingUpBreaksInFixedColumnsDoesNotGrowWithEachGroup() + { + static (long Bytes, int Reported) 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); + 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 < 1.5 * withSpaces.Bytes, $"{withBreaks.Bytes} bytes against {withSpaces.Bytes} without breaks"); + } + + /// + /// 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)); + } + + /// + /// 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 Bytes, int Reported) 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); + var bytes = GC.GetAllocatedBytesForCurrentThread() - before; + return (bytes, doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.CellWhiteSpaceDropped).Sum(d => d.Count)); + } + + Allocated(10, "ab ab"); + Allocated(10, "abab"); + var withTabs = Allocated(400, "ab ab"); + var withoutTabs = Allocated(400, "abab"); + + Assert.Equal(400, withTabs.Reported); + Assert.Equal(0, withoutTabs.Reported); + Assert.True(withTabs.Bytes < 1.5 * withoutTabs.Bytes, $"{withTabs.Bytes} bytes against {withoutTabs.Bytes} 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 + /// 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)); + } + + /// + /// 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 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))); + } + + /// + /// 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) + Assert.DoesNotContain(p.Text, ch => ch < 0x20); + } +} diff --git a/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs b/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs new file mode 100644 index 00000000..9579b1ea --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableContinuationLimitTests.cs @@ -0,0 +1,378 @@ +// 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; + +/// +/// 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 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 + /// 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); + } + + /// + /// 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()); + } + + /// + /// 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); + } +} diff --git a/tests/VellumPdf.Layout.Tests/TableLastStepTests.cs b/tests/VellumPdf.Layout.Tests/TableLastStepTests.cs new file mode 100644 index 00000000..a70d7f1a --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableLastStepTests.cs @@ -0,0 +1,340 @@ +// 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); + } + + // ── 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 ─────────────── + + /// + /// 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/TableMainRefusalTests.cs b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs new file mode 100644 index 00000000..3d12e15c --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableMainRefusalTests.cs @@ -0,0 +1,451 @@ +// 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 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)); + } + + // ── 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)); + } + + /// + /// 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) + { + // 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(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(Context(renderer)); + } + + return result.Status == LayoutResult.Outcome.Nothing || !reported ? 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, and over tables of short rows on taller ones, where none is cut and the + /// bound follows the heights. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void TheContinuationBoundIsNeverBelowTheContinuationsATableTakes(bool shortRows) + { + var most = 0L; + var checkedTables = 0; + for (var seed = 0; seed < 500; seed++) + { + var rng = new Random(seed); + 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, 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, 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 }); + } + } + + 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: 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); + 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, 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"); + 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"); + } +} diff --git a/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs new file mode 100644 index 00000000..17c94433 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableMeasureCacheTests.cs @@ -0,0 +1,607 @@ +// 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)); + const int cells = 4 * groups; + Assert.Equal(cells + groups, probe.WidthMisses); + 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); + } + + /// + /// 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"]; + + 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, 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)] + [InlineData(true)] + public void ACertificateCountsLikeTheWrapItStandsForAcrossItsInterval(bool honourBreaks) + { + var style = Helvetica(); + var rng = new Random(honourBreaks ? 1 : 2); + 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); + + Assert.Equal(TableRenderer.WordWrapCount(text, style, width, honourBreaks), lines); + 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)); + if (double.IsFinite(below)) + Assert.Equal(lines, TableRenderer.WordWrapCount(text, style, Math.BitDecrement(below), honourBreaks)); + } + + Assert.True(broken > 100, $"{broken} texts broke a word"); + } + + /// + /// 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 ACertificateHoldsOverARangeWhenAWordWasBroken() + { + var style = Helvetica(); + 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)); + } + + /// + /// 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); + 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)); + } + + /// + /// 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)); + } + + /// + /// 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); + } + + /// + /// 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); + } + + 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)); + } + + 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. 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 TheCostOfGivingUpBreaksInASharedAutoColumnStaysAFixedMultipleOfNotGivingThemUp() + { + Allocated(() => FillerDocument(10, "\n")); + Allocated(() => FillerDocument(10, " ")); + foreach (var groups in new[] { 400, 1600 }) + { + 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"); + } + } + + /// + /// 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 + /// 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 TheCostOfGroupsThatEachWidenTheColumnStaysUnderAFixedBound() + { + 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)) { RowSpan = 2 }) + .AddCell("lorem ipsum dolor sit amet " + i); + t.AddRow().AddCell("y"); + } + doc.Add(t); + return doc; + } + + Allocated(() => Build(10)); + var withBreaks = Allocated(() => Build(300)); + + Assert.Equal(300, withBreaks.Reported); + Assert.True(withBreaks.Bytes < 60_000_000L, $"{withBreaks.Bytes} bytes"); + } + + /// + /// 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() + { + 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; + } +} diff --git a/tests/VellumPdf.Layout.Tests/TableRandomDocuments.cs b/tests/VellumPdf.Layout.Tests/TableRandomDocuments.cs new file mode 100644 index 00000000..9744d386 --- /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; + } +} diff --git a/tests/VellumPdf.Layout.Tests/TableStrictDiagnosticsTests.cs b/tests/VellumPdf.Layout.Tests/TableStrictDiagnosticsTests.cs new file mode 100644 index 00000000..30745bcc --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/TableStrictDiagnosticsTests.cs @@ -0,0 +1,243 @@ +// 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; +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 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 +{ + 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); + } + + /// + /// 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); + } +} diff --git a/tests/VellumPdf.Layout.Tests/VellumPdf.Layout.Tests.csproj b/tests/VellumPdf.Layout.Tests/VellumPdf.Layout.Tests.csproj index bb0d992c..cf6484a6 100644 --- a/tests/VellumPdf.Layout.Tests/VellumPdf.Layout.Tests.csproj +++ b/tests/VellumPdf.Layout.Tests/VellumPdf.Layout.Tests.csproj @@ -10,6 +10,7 @@ +