diff --git a/CHANGELOG.md b/CHANGELOG.md index 754656a35..bf82c8709 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -600,6 +600,147 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **A list indent that leaves an entry no text width kept the marker and discarded the text + (#476).** `ParagraphRenderer` drops a paragraph whose width is zero or less, while the marker's + own paragraph has no margin, so a flat list whose `Indent` reached the list's area width saved as + a column of markers. A nested child lost its text from half that width, because the child gutter + is twice the indent, and nothing reported it. An entry whose gutter would leave its text no width + now gets one, so the text is drawn: the width of its widest word, or all the room right of its + marker's inset when the word is wider. The content starts at the area's right edge less that + width, and it can overprint the marker, which is never moved. + - **Deliberate output change**, only where the text width was zero or less: a flat list with an + `Indent` at or above the area width (positive infinity included), and a nested child whose + gutter is at or above it, which is an indent of half the area width or more. The item text is + now in the content stream. These keep their output: a width that is positive but short of the + widest word, so that a word is broken a glyph a line; an entry with no word that measures + wider than zero (white space only, font size 0, Symbol and ZapfDingbats), whose text is still + discarded; an entry with a run that holds text and has a non-finite font size or colour + channel, whose text is still discarded and which still saves, because a width would have made + the layout read that style and refuse it; and every entry of a list that is laid out as it was + before the clamp, which the #685 entry below lists. A nested list whose indent reaches the + area width still throws `InvalidOperationException`, with the same message. + - The clamp applies to a list the document lays out itself. A list that a renderer of yours lays + out through the context it was given, through `LayoutContext.WithArea` or through the public + `LayoutContext` constructor is laid out as it was: no gutter is narrowed and no entry moves + (#685), so the list itself saves, or is refused for the continuation limit, with the bytes and + the message it had. A list builds its entries at its first layout and keeps them, whole and at + the width that layout used, as it did. Where that layout was not the document's own call in this + save (you laid the list out before the save, another document did, or a renderer of yours that + holds the list did), the document lays the list out as it was, with those entries, and it + reports nothing unless it lays every list out as it was (below). That holds for a list changed + since: an item or a child added after that layout is not laid out or drawn. + `ListRenderer.Layout`, `IRenderer.Layout` and the `LayoutContext` constructor and + `WithArea` say so, with a "Do not rely on" paragraph: 3.0 lays a list out one way. + - An entry whose marker has no room at the top of a page is still refused: the save throws the + same "An element is too tall" `InvalidOperationException`. That entry fits no page, so its list + is placed as it was before (#685 below). The page-continuation limit is refused with its own + message, which begins "A single element needed more than 50000 page continuations". + - A list whose layout, with clamped text or with moved entries (see #685 below), would pass the + 50,000 page continuations one element may take is placed as it was before both, so a list that + saved still saves, and a list refused at that limit is still refused with the same message. + A list of 50,000 units or fewer, the sum over its entries of the larger of one and the entry's + wrapped lines, cannot reach the limit and is not probed. A larger one is laid out twice without + drawing, as it was and as it is now, and the new layout is kept only where neither reaches the + limit. The new `LayoutDiagnosticCode.ListIndentClampSkipped` (207, severity `Error`) reports + it, with the number of entries the clamp would have narrowed as `Count`, or 1 when it would + have narrowed none. The text of the entries the clamp would have narrowed is not drawn. The + message of a 207 names every cause that applied: the continuation limit, or any of a renderer + of yours, a font the document cannot draw, and an element after a list that comes near the + limit. + - A new `LayoutDiagnosticCode.ListIndentClamped` (203, severity `Error`) reports a clamped list + once, with the number of clamped entries as `Count`. `StrictDiagnostics` refuses it, and the + default saves. A list is reported when the document draws it from its first entry; a + `ListRenderer` you build to start at a later entry clamps and reports nothing. + - `ListElement.Indent` carries a "Do not pass" paragraph for an indent that leaves an entry's text + no width: 3.0 will refuse it. + +- **A list entry whose marker or text did not fit what was left of a page lost that part (#685).** + `ListRenderer` placed an entry when either its marker or its text was placed. An entry whose + marker fitted the rest of a page and whose text did not was drawn there with the text missing, + and one whose text fitted and whose marker did not was drawn with the marker missing, or with it + overprinting the line above; nothing reported either. An entry is now placed when both parts + are: otherwise it moves whole to the next page, as it already did when neither fitted, provided + a page of its own holds both. A marker that wrapped into more lines than the room left counts + as not placed. Text that has no width, which `ListElement.Indent` describes, is not a part that + did not fit. + - **Deliberate output change**, for a document with such an entry that is not at the top of a + page, and that holds no renderer of yours (below). The text that was missing is drawn, or the + same text is drawn at other positions. A moved entry also changes where a keep run ends and + what is drawn, so the `Count` or the items of an `UnembeddedFont` (601) report can change, and + a `KeepWithNextRelaxed` (801) or `KeepTogetherRelaxed` (802) report can appear or go. + - **A list that holds an entry no page holds is placed as it was before, whole.** An entry no + page holds is one whose marker has a line taller than a page, or whose text, at the width the + clamp of #476 would give it, has one. No entry of such a list is clamped or moved, so each is + where it fell and shows the lines that fit, and the new + `LayoutDiagnosticCode.ListEntryPartDropped` (208, severity `Error`) reports each of them, with + `Count` the number of such entries in the pieces drawn. `StrictDiagnostics` refuses it, and the + default saves. Other lists in the document keep both fixes. + - **Deliberate output change, text a list laid out as it was no longer shows after something + ahead of it moved.** A list laid out as it was before the clamp and the moving of entries + starts where the lists ahead of it, which keep both fixes, leave the cursor, and that can + differ from where it started. An entry it places at a page bottom then shows the lines its new + start allows, so a document can show fewer lines than before. It happens to a list that holds + an entry no page holds, which reports 208, and to a list the continuation limit sends back, + which reports 207. A document that holds a renderer of yours lays every list out as it was + (below), so no list ahead of one keeps the fixes. + - **Deliberate output change, a `ListRenderer` that serves a second document draws the placement + the first gave an entry.** A renderer reused for a second document keeps the entries it built + for the first (#476 above), and a paragraph draws the lines of its last layout when its layout + in the second document places nothing. 2.3.3 draws the first document's lines at that stale + position too, for an entry that fitted in the first document and does not in the second + (#691, which this change does not close). The first document now moves an entry that did not + fit what was left of a page, so the second draws the lines that placement gave it, where + 2.3.3 drew only the part that fitted. A renderer you add to the document and a renderer + of yours also holds draws the first placement's lines at the second the same way, as 2.3.3 + does. + - **A document that holds an entry in a font it cannot draw lays every list out as it was before + the clamp and the moving of entries.** A handle that another document returned, or a + `Standard14` value the enumeration does not name, makes the save throw where an entry's text or + marker is drawn, and 2.3.3 saved when that text fell where it did not fit and was dropped. + Clamping or moving an entry changes where everything after it falls, so a document could flip + from saving to throwing, or the reverse, without any list touching the entry. The rule is + therefore per document: when any list the document holds has such an entry, at any depth, no + list of the document is clamped or moved. Without `StrictDiagnostics` the save gives what it + gave before this change: the same bytes, or the same exception and message. With it, a 207 + refuses the save. `ListIndentClampSkipped` (207) reports a list the document placed this way + and draws from its first entry, with the number of entries the clamp would have narrowed as + `Count`, or 1; its XML doc says which lists report nothing. `ListEntryPartDropped` (208) + reports an entry left with a part missing. + - **A document that holds a renderer of yours lays every list out as it was before the clamp + and the moving of entries.** That is any renderer that is not one of the library's own, added + with `Document.Add(IRenderer)` or `DocumentRenderer.Add(IRenderer)`, wherever it sits and + whether or not it holds a list. A `ListRenderer`, `ParagraphRenderer`, `TableRenderer` or + another renderer the library ships is its own, and so is the barcode renderer. The library + cannot read where such a renderer starts or what it lays out, and a list that moved ahead of it + can change whether the document saves, so the document decides once, from the elements added + to it and before it lays anything out. Every pass of one save, a header or footer's + page-counting pass included, therefore lays each list out the same way. Without + `StrictDiagnostics` these documents save as they did before this change: the same bytes, or + the same exception and message; with it, a 207 refuses the save. A renderer reused from a + first document that moved an entry still draws that placement (#691). + `ListIndentClampSkipped` (207) is reported as for the font (above), and names the renderer. + `ListRenderer.Layout` says so, with a "Do not rely on" sentence: 3.0 lays a list out one way. + - **A document with an element after a list that can need about as many page continuations as + the limit allows lays every list out as it was before the clamp and the moving of entries.** + An element that needs that many saves or is refused according to where it starts, and a moved + entry changes where, so a paragraph after such a list could be refused where 2.3.3 saved it, + or saved where 2.3.3 refused it. The document reads the element's size, and not its layout: a + paragraph, heading, table or list counts when its characters, with one for each table row and + each list item that holds none, come to 49,999 or more, and so does preformatted text, with + each tab counted as its `TabWidth` because a tab can become that many columns and lines. A + page break, an image, a separator and a chart never count. The same report applies as for the + font (above). A renderer of yours is not read for its size; it + makes the document lay every list out as it was (above). + - A list that a renderer of yours holds reports nothing: neither 207 nor 208, because the + document did not place it, and nor do its pieces, including a piece the document calls itself + when your renderer returns the list's own result. A list the document places over entries a + renderer of yours built first is held the same way, unless the document lays every list out as + it was (above), which reports it as any list the document places. The bytes are those of the + list laid out as it was. + - Moving entries adds pages, so the continuation bound now covers every list, not only a list + with a clamped entry, and a list that would pass the limit because of moved entries is placed + as it was before, with `ListIndentClampSkipped` (207). + - **An element exactly as tall as the content area is placed at the top of a page (#549).** At the top of a page the document offered the height from the cursor to the bottom of the content area, `(Y + H) - Y`, while the retry after a `Nothing` offered the content area's own height `H`. The diff --git a/src/VellumPdf.Barcodes/BarcodeRenderer.cs b/src/VellumPdf.Barcodes/BarcodeRenderer.cs index 4c1c08147..6bec22a22 100644 --- a/src/VellumPdf.Barcodes/BarcodeRenderer.cs +++ b/src/VellumPdf.Barcodes/BarcodeRenderer.cs @@ -4,6 +4,7 @@ using VellumPdf.Barcodes.Internal; using VellumPdf.Document; using VellumPdf.Layout.Core; +using VellumPdf.Layout.Rendering; namespace VellumPdf.Barcodes; @@ -12,7 +13,7 @@ namespace VellumPdf.Barcodes; /// , or directly through the generic /// Document.Add(IRenderer) overload. /// -public sealed class BarcodeRenderer : IRenderer +public sealed class BarcodeRenderer : IRenderer, IListFreeRenderer { private readonly Barcode _barcode; private LayoutBox _occupied; diff --git a/src/VellumPdf.Kernel/Document/PdfDocument.cs b/src/VellumPdf.Kernel/Document/PdfDocument.cs index 3512ed257..59561a35a 100644 --- a/src/VellumPdf.Kernel/Document/PdfDocument.cs +++ b/src/VellumPdf.Kernel/Document/PdfDocument.cs @@ -407,6 +407,18 @@ private void RefuseUndefinedForeignFonts() } } + /// + /// Whether a page that draws passes the check + /// makes at save: the handle is this document's own, + /// or this document defines a font under its resource name. It reads the same two tests, so a + /// caller that must know before it draws, without registering the usage, gets the save's + /// answer. Removed in 3.0 (#688) with the list's own check of what it can draw. + /// + internal bool CanDrawFont(EmbeddedFontHandle handle) => + ReferenceEquals(handle.Owner, this) + || OwnEmbeddingOf(handle) is not null + || _embeddedFonts.Exists(f => f.ResourceName == handle.ResourceName); + // The same font program embedded here under the same resource name: the content stream names the // foreign handle's resource, and this document's own embedding defines that name, so the glyphs // the foreign embedder registered are added to this subset. Where the name is defined here for a diff --git a/src/VellumPdf.Layout/AssemblyInfo.cs b/src/VellumPdf.Layout/AssemblyInfo.cs index 8a2db3484..0f47b1074 100644 --- a/src/VellumPdf.Layout/AssemblyInfo.cs +++ b/src/VellumPdf.Layout/AssemblyInfo.cs @@ -4,5 +4,7 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("VellumPdf.Signing, PublicKey=0024000004800000140200000602000000240000525341310010000001000100f988869ac2abeba2cc200b481376afef9811d5801ae590a6ed2b1425350a618f076225d9d027f377bdc3301a7733718e10da17f7012963d4dc086672b8d61092faa1cf687546387e3a3681977cb1319a13d376558c02a4cb85cac9210d64fb245fdf35e394b938c92e0c48713835cba7a11e8e739fc965b78f9de64c321264149801a08b8bfe1c188c00f6192ed6a5502c99a094ad499b125dd3f1415935246f3a6c721c2eda2354e23ff44c071e3df14dcae09b2c02476a7a0ef9d6fb829b26c993e4d370515cf00bfabd00136a661cb0a49deb8284f352cb1c1dc23738b240c8787aff4adb681245ab790723685ba4c996cb69c89ed05f639ac6707fef5a142aac80934caaca46f5d533b9223c044c98b277d6afbcc3c7c8ceadeb524293fa269a3b050fbf2a0438de5c34ddbce231dc29e0e1326b13fd9e6ca11bd3a78915998eb52d809e728f9bf4c996c376a309a7576ad4e8fc7d28d1ec43465ca1171c3c60dac216a78d471bc73c6aeff0809eaa56a1613211149c37e88da1bdb467f7166506689b8de2c690b805c962538e03355190407252a394acecbf8e92135aed64dc7d8dff11faa5bee325a95da18ec5dca6f602c58e1b53ba3880facabac52facf96bc4af10d69871a05a34f49c08c8002f416f82ef33366850170c081066f1e7cb65e3479b971fa691a77f773d8adfaf9366a4783d83f9a511e6bd3db6f9be")] +// The barcode renderer marks itself as one of the library's own (IListFreeRenderer). +[assembly: InternalsVisibleTo("VellumPdf.Barcodes, PublicKey=0024000004800000140200000602000000240000525341310010000001000100f988869ac2abeba2cc200b481376afef9811d5801ae590a6ed2b1425350a618f076225d9d027f377bdc3301a7733718e10da17f7012963d4dc086672b8d61092faa1cf687546387e3a3681977cb1319a13d376558c02a4cb85cac9210d64fb245fdf35e394b938c92e0c48713835cba7a11e8e739fc965b78f9de64c321264149801a08b8bfe1c188c00f6192ed6a5502c99a094ad499b125dd3f1415935246f3a6c721c2eda2354e23ff44c071e3df14dcae09b2c02476a7a0ef9d6fb829b26c993e4d370515cf00bfabd00136a661cb0a49deb8284f352cb1c1dc23738b240c8787aff4adb681245ab790723685ba4c996cb69c89ed05f639ac6707fef5a142aac80934caaca46f5d533b9223c044c98b277d6afbcc3c7c8ceadeb524293fa269a3b050fbf2a0438de5c34ddbce231dc29e0e1326b13fd9e6ca11bd3a78915998eb52d809e728f9bf4c996c376a309a7576ad4e8fc7d28d1ec43465ca1171c3c60dac216a78d471bc73c6aeff0809eaa56a1613211149c37e88da1bdb467f7166506689b8de2c690b805c962538e03355190407252a394acecbf8e92135aed64dc7d8dff11faa5bee325a95da18ec5dca6f602c58e1b53ba3880facabac52facf96bc4af10d69871a05a34f49c08c8002f416f82ef33366850170c081066f1e7cb65e3479b971fa691a77f773d8adfaf9366a4783d83f9a511e6bd3db6f9be")] // Layout.Tests reaches the buffer a save to a path builds the PDF in, so it can copy it in small chunks. [assembly: InternalsVisibleTo("VellumPdf.Layout.Tests, PublicKey=0024000004800000140200000602000000240000525341310010000001000100f988869ac2abeba2cc200b481376afef9811d5801ae590a6ed2b1425350a618f076225d9d027f377bdc3301a7733718e10da17f7012963d4dc086672b8d61092faa1cf687546387e3a3681977cb1319a13d376558c02a4cb85cac9210d64fb245fdf35e394b938c92e0c48713835cba7a11e8e739fc965b78f9de64c321264149801a08b8bfe1c188c00f6192ed6a5502c99a094ad499b125dd3f1415935246f3a6c721c2eda2354e23ff44c071e3df14dcae09b2c02476a7a0ef9d6fb829b26c993e4d370515cf00bfabd00136a661cb0a49deb8284f352cb1c1dc23738b240c8787aff4adb681245ab790723685ba4c996cb69c89ed05f639ac6707fef5a142aac80934caaca46f5d533b9223c044c98b277d6afbcc3c7c8ceadeb524293fa269a3b050fbf2a0438de5c34ddbce231dc29e0e1326b13fd9e6ca11bd3a78915998eb52d809e728f9bf4c996c376a309a7576ad4e8fc7d28d1ec43465ca1171c3c60dac216a78d471bc73c6aeff0809eaa56a1613211149c37e88da1bdb467f7166506689b8de2c690b805c962538e03355190407252a394acecbf8e92135aed64dc7d8dff11faa5bee325a95da18ec5dca6f602c58e1b53ba3880facabac52facf96bc4af10d69871a05a34f49c08c8002f416f82ef33366850170c081066f1e7cb65e3479b971fa691a77f773d8adfaf9366a4783d83f9a511e6bd3db6f9be")] diff --git a/src/VellumPdf.Layout/Core/IRenderer.cs b/src/VellumPdf.Layout/Core/IRenderer.cs index 7c043083e..8972b8a08 100644 --- a/src/VellumPdf.Layout/Core/IRenderer.cs +++ b/src/VellumPdf.Layout/Core/IRenderer.cs @@ -57,6 +57,21 @@ public interface IRenderer /// reads every cell unbroken (#679); see /// . Your must /// forward to the same renderer. + /// A that your renderer lays out + /// is laid out as it was before the fixes of #476 and #685. Through the context you were + /// given, through or through the public + /// constructor, it narrows no entry's gutter and moves no entry to + /// the next page, so the list saves, or is refused for the continuation limit, as it did. The + /// document applies those fixes only to a list it lays out itself, where it can see the limit. + /// Do not rely on where such a list lands: 3.0 lays a list out one way, whatever called + /// it. + /// A document that holds a renderer of yours lays every list out as it was before the + /// fixes above, whether the list sits before it or after it. The document decides this + /// once, before it lays anything out, so a header or footer's page-counting pass and the pass + /// that draws agree, and those fixes do not change where your renderer starts. See + /// for which renderers count and + /// what is reported. Do not write a renderer whose result depends on anything but the + /// area it is offered. /// /// /// Raised from and the other diff --git a/src/VellumPdf.Layout/Core/LayoutContext.cs b/src/VellumPdf.Layout/Core/LayoutContext.cs index 09e2513ec..4f3364c72 100644 --- a/src/VellumPdf.Layout/Core/LayoutContext.cs +++ b/src/VellumPdf.Layout/Core/LayoutContext.cs @@ -108,6 +108,15 @@ internal ContinuationMode ModeFor(IRenderer renderer) => internal bool IsPlacedAsTwin(IRenderer renderer) => Session is { Probing: false, TwinChosen: true } session && ReferenceEquals(session.Called, renderer); + // Removed in 3.0 (#688). + /// + /// Whether the document called itself, outside a probe. False for a + /// renderer a caller's renderer holds, and for one a probe lays out, because neither was placed + /// by the document: the document is not the one that reads where such a renderer falls. + /// + internal bool IsAddressedByDocument(IRenderer renderer) => + Session is { Probing: false } session && ReferenceEquals(session.Called, renderer); + // Removed in 3.0 (#688). /// /// A context for a built-in renderer that , itself called under this @@ -150,7 +159,12 @@ internal static LayoutContext Addressed(LayoutBox area, IRenderer child, Continu public double ContentTop { get; } /// Creates a context for the given available area and optional content top. - /// Nothing is refused. Both arguments are stored as passed. + /// + /// Nothing is refused. Both arguments are stored as passed. + /// A context you build is not one the document built for the renderer you lay out with + /// it, so a then lays out as it did + /// before the fixes of #476 and #685; see . + /// public LayoutContext(LayoutBox area, double contentTop = 0) { Area = area; @@ -164,9 +178,11 @@ 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. 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 . + /// lines as fit. A built-in renderer that lays out differently when the document lays it out + /// lays out as it did before that change under the copy: a + /// reads every cell unbroken + /// (#679), and a narrows no entry's + /// gutter and moves no entry to the next page (#476, #685); see . /// public LayoutContext WithArea(LayoutBox area) => new(area, ContentTop) { FreshPageArea = FreshPageArea }; } diff --git a/src/VellumPdf.Layout/Core/LayoutValidation.cs b/src/VellumPdf.Layout/Core/LayoutValidation.cs index f04bc07ba..1f5c39487 100644 --- a/src/VellumPdf.Layout/Core/LayoutValidation.cs +++ b/src/VellumPdf.Layout/Core/LayoutValidation.cs @@ -152,6 +152,36 @@ internal static void ValidateStyle(TextStyle style, string owner) ValidateColor(style.Color, owner, "text colour"); } + /// + /// True when would accept every run of that + /// holds text, answered without throwing. A run with a null style that holds text counts as + /// refused, because the wrap refuses it. + /// + /// + /// For a caller that must know, before it lets text be laid out, whether the layout would raise + /// a refusal it has not raised so far. It reads the same two tests as + /// (a finite font size, a finite colour channel) on the runs that + /// hold text. It is stricter than the walk: a run of only white space holds text and is read + /// here, although the wrap yields no fragment for it and the walk never reads its style. A + /// caller that tests with it keeps the layout it had for such a run, which is the safe side. A + /// run with no text at all is not read. + /// + internal static bool AreRunStylesAccepted(IReadOnlyList runs) + { + foreach (var run in runs) + { + if (run.Text.Length == 0) continue; + if (run.Style is not { } style) return false; + if (!double.IsFinite(style.FontSize) + || !double.IsFinite(style.Color.R) + || !double.IsFinite(style.Color.G) + || !double.IsFinite(style.Color.B)) + return false; + } + + return true; + } + /// /// The font-size half of , for the callers that check a colour only /// where it is written: a running band and a table cell. diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index 868bf8f01..077d40d8c 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -113,6 +113,15 @@ public Document() { } /// it lies beyond the width a custom renderer laid the paragraph out at), /// and /// (a null below the second level of a list), + /// (an indent that left list text no + /// width), + /// (a list laid out without that + /// clamp, and without moving entries to the next page, because that would have taken it past + /// the continuation limit, because the document holds a renderer of yours, an entry in a font + /// it cannot draw, or an element after a list that can need about as many continuations as the + /// limit allows), + /// (a list entry placed with its marker + /// or its text not drawn), /// (a character an embedded font has no glyph /// for, written as glyph 0), (an element that /// selects a Standard 14 font under a conformance claim), @@ -1164,6 +1173,10 @@ public Document Add(string text, TextStyle? style = null) /// never gets smaller reaches that limit; has the rule. The save /// then throws naming the limit. Split a long element /// yourself. + /// A that a renderer of yours lays out is laid out as it was + /// before the fixes of #476 and #685, whatever context your renderer passes it, and so is every + /// list of a document that holds a renderer of yours; see + /// . /// A renderer you wrote yourself cannot ask for a page break. The library's own /// , , and /// honour their element's BreakBefore when added here. diff --git a/src/VellumPdf.Layout/Elements/ListElement.cs b/src/VellumPdf.Layout/Elements/ListElement.cs index 40aa8f883..860122cd4 100644 --- a/src/VellumPdf.Layout/Elements/ListElement.cs +++ b/src/VellumPdf.Layout/Elements/ListElement.cs @@ -47,10 +47,45 @@ public enum ListStyle /// negative indices is on . /// The last item a list draws on a page keeps all of its lines: the draw pass offers each /// item the height the layout pass did. +/// An item is placed when its marker and its text are both placed. When only one of them +/// fits what is left of a page, or a marker that wraps gets only some of its lines, the item moves +/// whole to the next page, as it does when neither fits. Text that has no width is not a line that +/// did not fit: it is discarded, as describes, and is not reported. +/// A list is laid out as it was before the clamp of (#476) and this +/// moving of items (#685) in six cases, and then none of its items is clamped or moved. Each +/// item stays where it falls, with the part that fits drawn and the other part not. +/// reports each such item the document +/// placed, and reports the list in the +/// last four cases. A list a renderer of yours holds reports neither, nor do its pieces. First, a +/// renderer of yours lays the list out, whatever context it passes on, or its entries were built +/// first by something other than the document's own call (you laid it out before the save, +/// another document did, or a renderer of yours that holds the list laid it out first); +/// see . Second, no page holds one of its items, +/// because a line of its marker, or of its text at the width the clamp would give it, is taller +/// than a page. Third, laying it out the new way would take it past the continuation limit, as +/// describes. Fourth, any list of the document holds an item whose marker or +/// text is in a font the document cannot draw, which is a handle another document returned or a +/// value the enumeration does not name. The save throws +/// where such text is drawn and saves where it is dropped at the bottom of a page, so widening or +/// moving anything ahead of the item can turn one outcome into the other. Fifth, the document +/// holds, after one of its lists, an element that can need about as many page continuations as +/// the limit allows. That element is refused or saved according to where it starts, so moving an +/// item ahead of it can turn one outcome into the other. The document reads the element's size, +/// not its layout: it counts the characters of a paragraph, heading, list item or table cell, and +/// of preformatted text with each tab counted as its , because +/// a tab can become that many columns and so that many lines. It adds one for an item that holds +/// no characters and one more for each table row, and the element counts when two more than that +/// is over the limit. A page break, an image, a separator and a +/// chart never count, and neither does an element a renderer of yours holds. Sixth, the document +/// holds a renderer that is not one of this library's own, wherever it sits; see +/// . In the last three cases every list of the document +/// is laid out that way, so without the document keeps +/// the outcome it had while nothing ahead of the font, the element or the renderer moves; with +/// it, a report refuses the save. /// Attention: an item whose text holds only white space is laid out at the leading of /// , as on , while its marker is laid out in -/// the item's own style. When the marker's line does not fit where the item lands, the item is -/// placed without its marker, and nothing reports it. +/// the item's own style, so the marker's line can be the one that does not fit where the item +/// lands. The rules above then apply to it. /// public sealed class ListElement { @@ -76,21 +111,49 @@ public sealed class ListElement /// own left edge. At the top level that gutter is the larger of this value and that item's own /// marker width. One level in, the marker itself starts at this value, so what has to be /// cleared is a position rather than a width, and the gutter is the larger of twice this value - /// and this value plus the child's marker width. One case overrides both: where the widened + /// and this value plus the child's marker width. Two cases override both. Where the widened /// gutter would leave less room than the item's longest word, the gutter reverts to the - /// unwidened figure. That is this value at the top level and twice it when nested. The - /// override rewrites a gutter and never a marker's own inset, so no marker moves with it. + /// unwidened figure, which is this value at the top level and twice it when nested. Where that + /// gutter leaves the text no width at all, the clamp described below replaces it. Neither + /// rewrites a marker's own inset, so no marker moves with them. /// Every boundary below is measured against the list's own area width, which is the /// page's content width narrowed by the left and right edges of . The top /// and bottom edges do not enter into it. A left or right inset narrows that area, so every /// boundary below moves in with it, each in proportion to where it sits. - /// An indent reaching that area width is not refused on a flat list. The marker is - /// drawn, the item text is discarded, and nothing reports the loss, so the list renders as a - /// column of markers with no content. A nested list throws at the area width, as the exception - /// records, but from half that width its child text is already being discarded the same - /// silent way, because the nested gutter reaches the area width at half the indent a top-level - /// gutter needs. The child marker, inset by this value alone, is not refused and is still - /// drawn. Keep this value well below half the area width (#476). + /// An indent reaching that area width is not refused on a flat list. An entry + /// whose gutter would leave its text no width at all, which is a gutter at or beyond the area + /// width, gets one instead: the width of its widest word, or all the room right of its + /// marker's inset when the word is wider, where the word is broken. The content then starts at + /// the area's right edge less that width, and never left of the marker's inset. A marker is + /// never moved, so the text can overprint it. The entry is then placed as at any indent: when + /// its marker or its text does not fit what is left of a page it moves to the next page. A + /// clamped line taller than a page leaves the whole list unclamped; see + /// . A list the document + /// draws from its first entry reports its clamped entries as one + /// item. + /// These keep their earlier output, and are not reported by + /// : a gutter that leaves the text a width, + /// however narrow; an entry with no word that measures wider than zero, such as one holding + /// only white space, set at font size 0 or set in Symbol or ZapfDingbats, whose text is + /// discarded; and an entry with a run that holds text and has a non-finite font size or a + /// non-finite colour channel, whose text is discarded and which does not make the save throw, + /// because a width would have let the layout read that style and refuse it. So does every + /// entry of a list that is laid out as it was before the clamp, which + /// lists in six cases. An entry whose marker has no room at the top + /// of a page is refused as before. A nested list throws at the area width, as the exception + /// records. Below that, from half the area width, a child's text is clamped in the same way, + /// because the nested gutter reaches the area width at half the indent a top-level gutter + /// needs. + /// One element may take at most 50,000 page continuations; see + /// . Drawing the text of a clamped entry adds lines, + /// and moving an entry adds pages, so a list the document lays out, and whose layout could + /// pass that limit, is laid out twice without drawing first: as it was before the clamp and the + /// moving of entries, and as it is now. It is placed the new way only when neither reaches the + /// limit. Otherwise it is placed as it was before both: no gutter is narrowed, an entry the + /// clamp would have changed keeps its marker and loses its text, no entry moves, and + /// reports it. That list then saves, + /// or throws the limit's , as a list with no clamp does. + /// /// Do not pass a negative value. It can carry content left of the margin and off /// the page, and a finite negative value is not reported. 3.0 will reject it. /// A non-finite indent is not checked before the layout; see . A @@ -101,8 +164,14 @@ public sealed class ListElement /// negative-infinity indent, because the gutter widens to the marker's own width, and a list with /// no items saves with any. Do not pass a non-finite indent: 3.0 refuses it. /// Positive infinity is not refused here, because it writes no invalid token. A nested list - /// throws at the area width as described above, and a flat list discards the item text. A - /// finite negative value is not refused either. + /// throws at the area width as described above, and a flat list clamps each entry whose text + /// has no width, as for any indent at or beyond that width. A finite negative value is not + /// refused either. + /// Do not pass an indent that leaves an entry's text no width beside its gutter: + /// the text is given a width and reported as + /// , or left out and reported as + /// when that would take the list past + /// the continuation limit, as above. 3.0 will refuse the input. /// A finite negative value can put linked item text, or a linked nested marker, at a /// non-finite position when the gutter taken from it, added to the list's left edge, overflows, /// as a nested list with an indent of -1e308 and a left margin of -1e308 does. The save then @@ -120,9 +189,12 @@ public sealed class ListElement /// /// Raised from a save rather than from this property, when a list with nested children has an /// indent that reaches the list's own area width, which is the page's content width narrowed by - /// the left and right edges of , positive infinity included; a flat list at - /// any such indent is not refused. The message reports an element too tall to fit and names - /// neither this property nor the list. + /// the left and right edges of , positive infinity included. A flat list + /// at such an indent is not refused for the indent. It is refused for two other reasons, as at + /// any indent. An entry's marker has no room at the top of a page: the message begins "An + /// element is too tall to fit on a single page". Or the list would pass the page-continuation + /// limit: the message begins "A single element needed more than 50000 page continuations". + /// Neither message names this property or the list. /// public double Indent { get; init; } = 20; diff --git a/src/VellumPdf.Layout/Elements/ListItem.cs b/src/VellumPdf.Layout/Elements/ListItem.cs index d323fa35e..3e4824e05 100644 --- a/src/VellumPdf.Layout/Elements/ListItem.cs +++ b/src/VellumPdf.Layout/Elements/ListItem.cs @@ -287,6 +287,13 @@ public ListItem(IEnumerable runs) internal IReadOnlyList ContentRuns(TextStyle inherited) => _runs ?? [new TextRun(Text, inherited)]; + /// + /// The runs the item was built from, or null for an item built from a string. It is the list + /// itself, not a copy, so a caller must not change it; it exists so that a walk over every + /// run allocates nothing. Removed in 3.0 (#688), with the check of what a list can draw. + /// + internal IReadOnlyList? OwnRuns => _runs; + /// True when the constructor was given a null text. internal bool HasNullText { get; } diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index 9fb5ed24c..4b70c2140 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -22,10 +22,10 @@ namespace VellumPdf.Layout; 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), 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. + // 105 SymbolFontMeasuredAsZero (Error), 204 ListDepthCapped, 205 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 @@ -170,6 +170,82 @@ public enum LayoutDiagnosticCode /// NullGrandchild = 202, + /// + /// A list's left the text of one or more entries no + /// width beside its gutter, so the save gave that text a width: the width of its widest word, + /// or all the room right of its marker's inset when the word is wider. + /// is the number of entries whose gutter was narrowed. + /// + /// + /// The text is drawn, and it may overprint its marker, so strict mode refuses it. It is + /// reported once for a list the document draws from its first entry; a + /// you build to start at a later entry clamps its entries + /// and reports nothing. An indent that leaves the text a width, however narrow, is not clamped + /// and not reported. Neither is an entry with no word that measures wider than zero, or one + /// with a run whose font size or colour channel is not finite, whose text is still discarded. + /// No entry of a list that is laid out as it was before the clamp is clamped; + /// lists the six cases, and + /// and report them. + /// Do not pass an indent that leaves an entry's text no width: 3.0 will refuse it. See + /// . + /// + ListIndentClamped = 203, + + /// + /// A list was laid out as it was before the clamp described at + /// and before entries that do not fit what is left of a page were moved to the next one: no + /// gutter narrowed and no entry moved. Either it would have needed more page continuations + /// than one element may take with them, or the document holds a renderer of yours, a list entry + /// in a font it cannot draw, or an element after a list that can need about as many + /// continuations as the limit allows, which turns every list of the document back. + /// is the number of entries the clamp would have narrowed, + /// and 1 when it would have narrowed none. + /// + /// + /// The text of the entries the clamp would have narrowed is discarded, and only their + /// markers are drawn. An entry that does not fit what is left of a page is placed there + /// with the part that fits, as it was, and reports it. The + /// list then saves, or throws for the continuation + /// limit, as a list with every gutter left as and the + /// marker widths give it would and every entry kept where it falls. The three document-wide + /// causes exist because a font the document cannot draw makes the save throw where its text is + /// drawn, an element near the limit is refused or saved according to where it starts, and a + /// renderer of yours reads where it starts, and the clamp or a moved entry ahead of any of them + /// can change where that is; the document then saves or throws as it did. It decides this once, + /// before it lays anything out, from the elements added to it. The message names every cause + /// it read there: the continuation limit for the list, or any of the font, the element near + /// the limit and the renderer of yours. Strict mode refuses this code. It is reported once for + /// each list the document placed this way and draws from its first entry; a list that a + /// renderer of yours holds is laid out as before and reports nothing. A list the document + /// places itself over entries a renderer of yours built first is reported when the document + /// lays every list out as it was. Do not pass an + /// indent that leaves an entry's text no width, or a font the document cannot draw: 3.0 will + /// refuse both. See . + /// + ListIndentClampSkipped = 207, + + /// + /// A list entry was placed with its marker or its text not drawn, because it does not fit where + /// it falls and the list did not move it to the next page. + /// is the number of such entries in the pieces the + /// document drew. + /// + /// + /// A part of the entry is missing from the page. A line that does not fit is not drawn, + /// while a marker or a text that wraps keeps the lines that fit. An entry is left where it + /// falls, and reported, when its list is laid out as it was before the clamp and the moving of + /// entries and the document placed the list; lists the + /// six cases. In one of them no page holds the entry, because a line of its marker, or a line + /// of its text at the width the clamp would give it, is taller than a page. A list that a + /// renderer of yours lays out is laid out that way too, and reports nothing: the document did + /// not place it. An entry whose text has no width is not reported, and neither is one that + /// moves to the next page whole. It is reported from the piece of the list that holds the + /// entry, once per list however many entries it counts. Strict mode refuses this code. + /// Do not give an entry a marker or a line of text taller than a page: the part that + /// does not fit is not drawn. + /// + ListEntryPartDropped = 208, + /// /// A running band's resolved text was cut to fit the content box. It mirrors /// , and there is one item per band. diff --git a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt index 62dce73c4..d2975f5fb 100644 --- a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt +++ b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt @@ -16,6 +16,9 @@ VellumPdf.Layout.LayoutDiagnosticCode VellumPdf.Layout.LayoutDiagnosticCode.BandTruncated = 401 -> VellumPdf.Layout.LayoutDiagnosticCode VellumPdf.Layout.LayoutDiagnosticCode.DiagnosticsDropped = 901 -> VellumPdf.Layout.LayoutDiagnosticCode VellumPdf.Layout.LayoutDiagnosticCode.NullGrandchild = 202 -> VellumPdf.Layout.LayoutDiagnosticCode +VellumPdf.Layout.LayoutDiagnosticCode.ListIndentClamped = 203 -> VellumPdf.Layout.LayoutDiagnosticCode +VellumPdf.Layout.LayoutDiagnosticCode.ListIndentClampSkipped = 207 -> VellumPdf.Layout.LayoutDiagnosticCode +VellumPdf.Layout.LayoutDiagnosticCode.ListEntryPartDropped = 208 -> VellumPdf.Layout.LayoutDiagnosticCode VellumPdf.Layout.LayoutDiagnosticCode.NullGrandchildText = 201 -> VellumPdf.Layout.LayoutDiagnosticCode VellumPdf.Layout.LayoutDiagnosticCode.NullTextRunStyle = 101 -> VellumPdf.Layout.LayoutDiagnosticCode VellumPdf.Layout.LayoutDiagnosticCode.UnencodableCharacter = 103 -> VellumPdf.Layout.LayoutDiagnosticCode diff --git a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs index 98f8f58b4..28ef71925 100644 --- a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs @@ -432,6 +432,22 @@ public void Render(Stream destination) /// on the underlying document. /// internal void RunLayout() + { + // Every list this layout lays out reads the run, whatever context it is handed, and a + // layout that a renderer of a caller's starts from inside this one gets a run of its own. + // Removed in 3.0 (#688). + var run = ListLayoutRun.Begin(_pdf, out var outerRun); + try + { + RunLayoutWith(run); + } + finally + { + ListLayoutRun.End(outerRun); + } + } + + private void RunLayoutWith(ListLayoutRun listRun) { // A refusal belongs to the layout that raised it; a renderer reused for another layout starts clean. _deferredCanvasRefusal = null; @@ -495,6 +511,8 @@ internal void RunLayout() // and the guard compares the drawing pass with them. Tests set RecordPlacements. _collect = dependents is not null || RecordPlacements || _navigation.HasAnchors || _navigation.HasBreakLabels; + ScanLists(listRun); + int totalPages; if (dependents is not null) { @@ -777,6 +795,136 @@ private LayoutBox AreaOnPage(LayoutBox area, int pageIndex) => ? new LayoutBox(_margins.Right, area.Y, area.Width, area.Height) : area; + // Decides, before anything is laid out, whether every list of the document is its twin + // (ListLayoutRun), and records which of the three document-wide rules said so. Every element + // the document holds itself is read here, and every list sits at the top level: no built-in + // renderer builds one. The decision is taken once, from what was added, so the measuring pass + // that counts pages and the pass that draws lay every list out the same way. + // + // The first rule is the renderer: a renderer the library does not ship reads where it starts + // and lays out whatever it holds, a list among it, through a context of its own making, and + // nothing here can read what it will do. Where the lists before it put it can decide whether + // the document saves, and a document whose passes disagreed about where a list fell would + // count pages the saved file does not have. A renderer of this library that is not in this + // assembly and holds no list does not count (IListFreeRenderer). + // + // The second rule is the font: a list that holds an entry the document cannot draw turns every + // list into its twin. + // + // The third rule is the limit: a built-in element after a list whose continuations can come + // near the limit starts where the lists before it put it, and the limit's verdict for it + // depends on where that is. 2.3.3 saved or refused it according to where the twin lists put + // it, so the lists are the twins. The bound is ContinuationBoundOf's, which holds for either + // placement, and an element whose bound is within the limit cannot reach it from any start. + // Each rule is tested whatever the others have found, so the causes the scan records do not + // depend on the order of the elements, and the 207 of a list names every cause the scan found. + // Removed in 3.0 (#688). + private void ScanLists(ListLayoutRun listRun) + { + var listBefore = false; + foreach (var renderer in _renderers) + { + if (renderer is ListRenderer list) + { + if (listBefore && ContinuationBoundOf(renderer) > ContinuationLimit) + listRun.NoteNearTheLimit(); + listBefore = true; + if (ListRenderer.HoldsUndrawableEntry(list.Element, listRun)) listRun.NoteUndrawable(); + } + else if (renderer.GetType().Assembly != typeof(ListRenderer).Assembly) + { + if (renderer is not IListFreeRenderer) listRun.NoteCallerRenderer(); + } + else if (listBefore && ContinuationBoundOf(renderer) > ContinuationLimit) + { + listRun.NoteNearTheLimit(); + } + } + } + + // An upper bound on the page continuations a built-in renderer's placement can take from any + // start, so that a bound within the limit says the element cannot reach it however far a list + // before it moved its start. Every Partial a renderer returns consumes at least one line, entry + // or row, a Nothing the loop retries can only come first, and the piece that ends adds one, so + // the continuations are at most 2 plus the lines, entries and rows. The count is capped as it + // is summed: a bound past the limit is all the caller asks. Elements that never return a + // Partial take at most a retry and a piece. A renderer built with a negative start, which the + // constructors ask callers not to pass, is the exception. A built-in renderer this does not + // name is taken to be near the limit. + // + // What a line holds, for each kind that wraps text, read from the renderer: + // - A paragraph, and a heading, which wraps through one: no step rewrites the text. A hard + // break ends a line and is a character, and a word wider than the line is cut at one scalar + // at least per line, so the lines are at most the characters plus one. A tab stop only + // places text; a line is committed only before a word or a break, which are characters. + // - A list: each entry is its text's lines in a paragraph of that kind, and a marker that + // wraps moves the entry whole, so an entry adds at most max(1, its characters). + // - A table: a cell reads its line ends (#679) and wraps each line at spaces, cutting a word + // at one scalar at least per line. A line end is a character and ends one line, so the + // cell holds at most one line more than its characters. Any other control white-space + // character reads as one space, and a cell read unbroken, as the table's twin reads every + // cell, holds at most max(1, its characters) lines. A row is cut only where every cell + // holds a line on a fresh page, so each piece after the first takes at least one line from + // every cell that has lines left, and a cut row ends in at most one call more than its + // characters. The first piece can leave the cell with the most lines untouched, when the + // room left holds the shorter lines of the others. That happens in a call that also + // finishes the row before it, which then needs no call of its own, or in the table's first + // call, which the 2 covers. A row counts one more than the characters of its cells. + // - Preformatted text rewrites the text before it wraps: PreformattedText.Expand replaces + // each tab by 1 to TabWidth spaces, and that is the only rewrite. A line end is a + // character and ends one line, and the wrap cuts an expanded line after at least one + // cluster, which is at least one character. So the lines are at most 1 plus the + // characters with a tab counted as TabWidth, which is what the count below is. + // Removed in 3.0 (#688). + internal long ContinuationBoundOf(IRenderer renderer) + { + var cap = (long)ContinuationLimit + 1; + long total = 2; + switch (renderer) + { + case ParagraphRenderer paragraph: + var runs = paragraph.Paragraph.Runs; + for (var i = 0; i < runs.Count && total <= cap; i++) total += runs[i].Text.Length; + return total; + + case HeadingRenderer heading: + return total + heading.Element.Text.Length; + + case PreformattedRenderer preformatted: + var pre = preformatted.Element; + return total + pre.Text.Length + (long)pre.Text.AsSpan().Count('\t') * (pre.TabWidth - 1); + + case ListRenderer list: + var items = list.Element.Items; + for (var i = 0; i < items.Count && total <= cap; i++) + { + total += Math.Max(1, items[i].Text.Length); + if (items[i].Children is not { } children) continue; + for (var c = 0; c < children.Count && total <= cap; c++) + total += Math.Max(1, children[c].Text.Length); + } + + return total; + + case TableRenderer table: + var rows = table.Element.Rows; + for (var r = 0; r < rows.Count && total <= cap; r++) + { + total++; + var cells = rows[r].Cells; + for (var c = 0; c < cells.Count && total <= cap; c++) total += cells[c].Content?.Length ?? 0; + } + + return total; + + case LayoutImageRenderer or LineSeparatorRenderer or PieChartRenderer or PageBreakRenderer: + return total; + + default: + return long.MaxValue; + } + } + // Only the renderers added to this document are searched, not ones a renderer holds inside // itself. private List? FindPlanDependents() diff --git a/src/VellumPdf.Layout/Rendering/IListFreeRenderer.cs b/src/VellumPdf.Layout/Rendering/IListFreeRenderer.cs new file mode 100644 index 000000000..b9fcb787a --- /dev/null +++ b/src/VellumPdf.Layout/Rendering/IListFreeRenderer.cs @@ -0,0 +1,17 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +namespace VellumPdf.Layout.Rendering; + +/// +/// Marks a renderer of this library that lives outside this assembly and never lays a list out, +/// so that a document that holds it is not treated as one that holds a renderer of a caller's. +/// +/// +/// Internal, so that only the library's own packages can set it: a renderer of a caller's cannot +/// claim to be the library's own. A 2.x compatibility device, removed in 3.0 (#688), with the rule +/// it is an exception to (). +/// +internal interface IListFreeRenderer +{ +} diff --git a/src/VellumPdf.Layout/Rendering/ListLayoutRun.cs b/src/VellumPdf.Layout/Rendering/ListLayoutRun.cs new file mode 100644 index 000000000..20083ec62 --- /dev/null +++ b/src/VellumPdf.Layout/Rendering/ListLayoutRun.cs @@ -0,0 +1,184 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; + +namespace VellumPdf.Layout.Rendering; + +/// +/// What every list of one document layout shares: the document, and whether the document keeps +/// every list as its twin. +/// +/// +/// A 2.x compatibility device, removed in 3.0 (#688), which refuses such a font where the style is +/// built and lays a list out one way. +/// Clamping or moving an entry changes where everything after it falls, and three things on +/// 2.3.3 depend on where that is. A list entry whose font the document cannot draw saved when its +/// text fell where it does not fit and was dropped there, and threw when the text was drawn. An +/// element that needs about as many continuations as the limit allows (#459) saved or threw +/// according to where it started. A renderer of a caller's reads where it starts, and nothing the +/// library can read says how. One document could flip from one outcome to the other without any +/// list having touched the element itself. The document keeps its 2.3.3 outcome only if no list +/// moves anything, so a document that holds any of the three lays every list out as its twin. +/// reads what the document holds before it lays anything out, so +/// the decision is the same in every pass. +/// The run is the one place a list reads that decision, and the document it lays out for: +/// is the run of the layout in progress, whatever context the list was +/// handed and whatever thread it is laid out on. It flows with the execution context, so a +/// renderer that lays its list out on a task or a thread pool thread is seen. Work queued with the +/// context suppressed (ThreadPool.UnsafeQueueUserWorkItem, +/// ExecutionContext.SuppressFlow) is not. +/// +internal sealed class ListLayoutRun +{ + // Not ThreadStatic: a renderer of a caller's that lays its list out through Task.Run, Parallel + // or a new thread would otherwise lay it out under no run, and the document would not learn + // what that list holds. A layout started inside another one restores the outer run in End. + private static readonly AsyncLocal s_current = new(); + + // The embedded fonts the document was found able to draw. A list asks about the same few fonts + // for every run of every entry, so a font is asked about once, however the runs alternate. Only + // a yes is kept: a font cannot be taken away from a document, and a renderer of a caller's may + // embed one while the layout runs, so a no is asked again. Read from every thread a renderer + // lays its list out on. + private System.Collections.Concurrent.ConcurrentDictionary? _drawable; + + // The Standard 14 value whose answer was asked for last, which costs one comparison. The value + // and its answer are packed in one long, written and read whole, because the run is read from + // every thread a renderer lays its list out on and three separate fields can pair one value + // with another's answer. Bit 0 says an answer is held, bit 1 is the answer, the rest the + // value. Zero is no answer yet. + private long _lastStandard; + + // Read from every thread a renderer lays its list out on, and only ever set to true. The + // causes are kept apart because the report of a list names the ones that applied. + private volatile bool _allAsTwin; + private volatile bool _undrawable; + private volatile bool _nearTheLimit; + private volatile bool _callerRenderer; + + private ListLayoutRun(PdfDocument pdf) => Pdf = pdf; + + /// The run of the layout in progress, or null outside one. + internal static ListLayoutRun? Current => s_current.Value; + + /// The document the layout is for. + internal PdfDocument Pdf { get; } + + /// + /// True once the document was found to hold a renderer that is not one of the library's own, + /// a list entry it cannot draw, or an element after a list that can need about as many + /// continuations as the limit allows. It never goes back: every list of the document is then + /// laid out as its twin. + /// + internal bool AllAsTwin => _allAsTwin; + + /// Whether the scan found a list with an entry the document cannot draw. + internal bool FoundUndrawable => _undrawable; + + /// + /// Whether an element after a list was found that can need about as many continuations as the + /// limit allows. + /// + internal bool FoundNearTheLimit => _nearTheLimit; + + /// + /// Whether the document holds a renderer that is not one of the library's own. + /// + internal bool FoundCallerRenderer => _callerRenderer; + + /// + /// Starts the run of a layout. is what restores, + /// so a layout started inside another one, from a renderer of a caller's, leaves the outer run + /// as it was. + /// + internal static ListLayoutRun Begin(PdfDocument pdf, out ListLayoutRun? previous) + { + previous = s_current.Value; + var run = new ListLayoutRun(pdf); + s_current.Value = run; + return run; + } + + internal static void End(ListLayoutRun? previous) => s_current.Value = previous; + + /// + /// Records that a list the document holds holds an entry the document cannot draw. + /// + internal void NoteUndrawable() + { + _undrawable = true; + _allAsTwin = true; + } + + /// + /// Records that an element after a list can need about as many continuations as the limit + /// allows, so where it starts decides whether the document saves. + /// + internal void NoteNearTheLimit() + { + _nearTheLimit = true; + _allAsTwin = true; + } + + /// + /// Records that the document holds a renderer that is not one of the library's own, wherever + /// it sits among the elements, so where the lists before it put it is read by code the library + /// cannot see. + /// + internal void NoteCallerRenderer() + { + _callerRenderer = true; + _allAsTwin = true; + } + + /// + /// Whether text in can be drawn in the document, which is the question + /// before text that was discarded is drawn (#476) or an entry that was dropped is moved and + /// drawn (#685). The text is drawn through TextEmitter.SelectFont, and two things there refuse + /// a style that layout accepted. An embedded handle is registered for the page, and the save + /// refuses one the document defines no font for (PdfDocument.RefuseUndefinedForeignFonts). A + /// Standard 14 value the enumeration does not name makes the save throw + /// IndexOutOfRangeException when the font dictionary reads its name + /// (PdfFontResource.BaseFontName). A non-finite size or colour is the other refusal the draw + /// adds, and the clamp checks it separately. + /// + /// + /// A layout that has no run cannot say whether a handle is defined in the document, so an + /// embedded font is then not drawable. + /// + internal static bool CanDraw(ListLayoutRun? run, TextStyle style) + { + var font = style.FontRef; + if (font.IsEmbedded) return run is not null && run.CanDrawEmbedded(font.Embedded); + return run is null ? Enum.IsDefined(font.Standard14) : run.IsStandardDefined(font.Standard14); + } + + // How many times the document was asked whether an embedded font can be drawn, for a test to + // pin that a font it answered yes for is not asked about again. + private int _documentQuestions; + + internal int DocumentQuestions => Volatile.Read(ref _documentQuestions); + + private bool CanDrawEmbedded(EmbeddedFontHandle handle) + { + if (_drawable is { } known && known.ContainsKey(handle)) return true; + Interlocked.Increment(ref _documentQuestions); + if (!Pdf.CanDrawFont(handle)) return false; + + var created = _drawable ?? Interlocked.CompareExchange(ref _drawable, new(), null) ?? _drawable; + created[handle] = true; + return true; + } + + private bool IsStandardDefined(Standard14 font) + { + var last = Volatile.Read(ref _lastStandard); + if (last != 0 && (last >> 2) == (long)font) return (last & 2) != 0; + var defined = Enum.IsDefined(font); + Volatile.Write(ref _lastStandard, ((long)font << 2) | (defined ? 2L : 0L) | 1L); + return defined; + } +} diff --git a/src/VellumPdf.Layout/Rendering/ListRenderer.cs b/src/VellumPdf.Layout/Rendering/ListRenderer.cs index 09589968f..603c020ce 100644 --- a/src/VellumPdf.Layout/Rendering/ListRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/ListRenderer.cs @@ -1,6 +1,7 @@ // 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; @@ -16,12 +17,48 @@ namespace VellumPdf.Layout.Rendering; /// /// Grandchildren are ignored; see . /// -public sealed class ListRenderer : IRenderer, IPageBreakSource, IKeepSource, IPlacementSource +public sealed class ListRenderer : IRenderer, IPageBreakSource, IKeepSource, IPlacementSource, IContinuationTwin { private readonly ListElement _list; - // Flattened (marker, content-renderer) pairs, built once during first Layout. - private List<(ParagraphRenderer Marker, ParagraphRenderer Content, ListItem Item)>? _items; + // A list is placed two ways. The new layout gives an entry's text a width where the indent left + // it none (#476) and moves an entry that does not fit what is left of a page whole to the next + // one (#685). The twin is the layout it had before both: no gutter narrowed, no entry moved. + // The document uses the new layout only for a call it addresses to this instance, once it has + // decided the continuation limit (#686). Under any other context, for a list that holds an + // entry no page holds, for a list a caller laid out before the save, and for every list of a + // document that holds an entry whose font it cannot draw or an element after a list near the + // limit (ListLayoutRun), the list lays out as its twin. The twin, the delegation below and + // everything that exists for them are 2.x compatibility devices, removed in 3.0 (#688), which + // lays a list out one way. + /// + /// The list laid out as it was before the clamp and the moving of entries: no gutter is + /// narrowed, so an entry whose text has no width keeps its marker and loses its text, and no + /// entry is moved. The same object on every call. + /// + internal ListRenderer Unclamped() + { + _twin ??= new ListRenderer(_list, _startItem, _partialContentOverrideAtStart) { _unclamped = true }; + + // The entries that fit no page are known once this list has built its items, which the + // twin is asked for only after. The entries the clamp would have narrowed the twin counts + // itself, from the same gutters. + _twin._unplaceable = _unplaceable; + return _twin; + } + + IRenderer IContinuationTwin.Twin() => Unclamped(); + + // One entry of the flattened list: the marker and the text paragraph of an item or a child. + // Clamped is set when BuildItems narrowed the gutter, and UnclampedGutter is the gutter the + // entry has without the clamp. A twin that keeps the entries an earlier layout built rebuilds + // the text of an entry the clamp narrowed from the paragraph and that gutter, and not from the + // list, which may have changed since. + private readonly record struct Entry( + ParagraphRenderer Marker, ParagraphRenderer Content, ListItem Item, bool Clamped, + double UnclampedGutter); + + private List? _items; // Pagination window private readonly int _startItem; @@ -33,6 +70,108 @@ public sealed class ListRenderer : IRenderer, IPageBreakSource, IKeepSource, IPl private LayoutBox _occupied; + // The number of entries whose gutter BuildItems clamped, which Draw reports when it draws the + // list from its first entry. The pieces a split returns carry it, because the piece that + // starts the list is the one that is drawn. + private int _indentClamped; + + // True on the twin Unclamped returns, and on every piece a split of it hands on: BuildItems + // then leaves every gutter as it was before the clamp existed and Layout moves no entry, so the + // twin lays the list out as it was laid out without either. + private bool _unclamped; + + // On the twin, the number of entries the clamp would have narrowed, counted from the same + // gutters, which Draw reports as ListIndentClampSkipped when the document chose the twin for + // that reason. Carried by splits like _indentClamped. + private int _clampSkipped; + + // Why a list is the twin, as far as the document is concerned. A twin that a caller's renderer + // holds, one that the caller laid out before the save, and one a continuation probe lays out + // were not placed by the document and report nothing. AllLists is the document-wide rule of + // ListLayoutRun with the causes that applied added as bits: the document held an entry it + // cannot draw, an element after a list near the limit, or a renderer of the caller's. + private enum TwinPlacement : byte + { + Held = 0, + Document, + Limit, + AllLists = 8, + } + + private const byte AllListsFont = 1; + private const byte AllListsNearLimit = 2; + private const byte AllListsRenderer = 4; + + // How the document placed this twin, read from the context of the last Layout and carried by + // the pieces a split hands on. Document is a list the document placed as its twin without + // deciding it: a list that holds an entry no page holds, which reports its dropped entries. + // Limit is the continuation limit's decision, and the three AllLists values the document-wide + // rules of ListLayoutRun, named for the rule that applied (an entry in a font the document + // cannot draw, an element after a list near the limit, or both); all of them also report + // ListIndentClampSkipped. + private TwinPlacement _placement; + + // What the list that built this twin tells it before each call: how that list was called. Set + // by LayOutAsTwin, and read by the twin's own Layout. + private TwinPlacement _handoff; + + // The twin Unclamped hands out, built once so the measuring and the drawing pass place the same + // object. + private ListRenderer? _twin; + + // Set when the last Layout call was answered by a twin: because the context was not one the + // document addressed to this list, because an entry of the list fits no page, because the + // document keeps every list as its twin, or because the entries were built before the save. The + // document draws and asks for placements on the instance it called, so Draw and + // ReportPlacements hand the call on to it. It is the twin Unclamped returns. + private ListRenderer? _delegate; + + // Which layout built the entries. 2.3.3 builds a list's entries at its first layout, at that + // layout's width, and keeps them for every later one, whatever document or call that is: a + // caller who laid the list out before the save, another document, or a save before this one. + // This list builds its own entries new and its twin builds the ones 2.3.3 builds, so a layout + // that finds entries built by another layout than the document's own call in this run lays the + // list out as its twin, which holds or builds the entries 2.3.3 keeps. Those are entries built + // under another run than the one in progress (or none), and entries the twin built under a + // call the document did not address to this list (_builtForCaller). Every call the document + // makes within one run counts as one layout: the measuring and the drawing pass, the + // continuation probes, the pieces of a split, a second placement of the same renderer. + // _builtUnder is carried by splits, which share the items. Removed in 3.0 (#688). + private ListLayoutRun? _builtUnder; + + // On a twin, whether it built its entries under a context that did not name the twin: a + // renderer of the caller's holds the list and laid it out, or the document called the list and + // the twin built them for it. Within one run only the first kind can make a later call the + // document does address count as laying out entries an earlier layout built, because the + // document's calls on an empty list go to the twin from then on (AllAsTwin, ModeFor). Entries + // built under another run count whatever this holds (_builtUnder). + private bool _builtForCaller; + + // On a piece a split hands on, set when the piece takes the placement of the call that made it + // (_placement) and does not read it again from the context. A piece the document calls itself + // is addressed to the document whether or not the list it came from was, so reading the + // context turns a piece of a held list into a placed one. Held then stays what the call that + // made the piece said, and is not confused with a twin nobody handed a placement. + private bool _placementInherited; + + // On a twin, the entries the list it answers for built before the twin's first layout, + // whichever run that was: another document's, or this one's, when a list added to the document + // is also held by a renderer of the caller's. The twin has built none of its own then, and + // does not build any: it takes those entries whole, whatever the list holds now, as 2.3.3 + // keeps them, with the wrap each paragraph cached. For an entry the clamp narrowed it keeps the + // marker, which the clamp does not change, and rebuilds the text as 2.3.3 built it, without + // the clamp, because on 2.3.3 that text had no width and was never wrapped. Let go once the + // twin holds the entries. + private List? _earlier; + + // Whether the entries have been tried on an empty page, and what that found. When any entry + // fits no page the list lays out as its twin (_wholeAsMain). _unplaceable marks the entries + // that fit none, by index, and the twin reports them from Draw. Carried by splits, which share + // the items. + private bool _placeabilityKnown; + private bool _wholeAsMain; + private bool[]? _unplaceable; + // The height Layout offered each item it visited, indexed by the item's offset from the start // item. Draw offers the same height: it lays the item out a second time, a paragraph's line // count is a floor of the height it is given, and Bottom - y can come out one rounding step @@ -53,7 +192,9 @@ public sealed class ListRenderer : IRenderer, IPageBreakSource, IKeepSource, IPl /// occupying no height. A negative start on an empty list also /// returns occupying no height, and then /// throws . - /// A null is refused here. + /// A null is refused here. A renderer that starts after the first + /// entry still clamps an entry's gutter, and does not report that; see + /// . /// Do not pass a start outside the list's entries, which count each child after its /// parent. 3.0 will throw from this constructor. /// @@ -87,6 +228,14 @@ public ListRenderer(ListElement list, int startItem = 0) // follow report from the item they start at. void IPlacementSource.ReportPlacements(PlacementSink sink) { + // The document asks the instance it called, and a list the twin laid out is that twin's. + // Removed in 3.0 (#688). + if (_delegate is { } delegated) + { + ((IPlacementSource)delegated).ReportPlacements(sink); + return; + } + if (_items is null) return; if (_startItem == 0 && _partialContentOverrideAtStart is null && _list.Anchor is { } listAnchor) @@ -115,10 +264,55 @@ private ListRenderer(ListElement list, int startItem, ParagraphRenderer? partial /// Paginates the list item-by-item, splitting at item boundaries on overflow; handles mid-item splits by chaining content overflow renderers. /// /// See the constructor for a negative or past-end start. Overflow splits at an item, or - /// mid-item when a paragraph does. When the document calls this method, the exceptions it lists - /// reach you from the save. A list added with never - /// starts at a negative item, so reaches the save - /// only from a renderer you construct with a negative start and add yourself. + /// mid-item when a paragraph does. An item whose marker or text does not fit what is left of a + /// page moves whole to the next page; see . + /// The two fixes of #476 and #685, the clamp of an entry's text width and the moving + /// of entries, apply only to a list the document lays out itself. A list laid out through a + /// context the document did not build for this instance is laid out as it was before them, with + /// no gutter narrowed and no entry moved. That is a context from the public + /// constructor, one from , and + /// the one a renderer of yours passes on or makes when it lays a out + /// from its own . It keeps the verdict of the page-continuation + /// limit on such a list: 2.3.3 saved it or refused it, and it does so again. A list that holds + /// an entry no page holds is laid out that way too, so is a list the document would otherwise + /// take past that limit, and so is every list of a document that holds a renderer of yours, a + /// font it cannot draw, or an element after a list that can need about as many continuations + /// as the limit allows; see , + /// and + /// . A list that your renderer holds + /// reports neither: the document did not place it. That holds for the pieces of the list too, + /// when your renderer returns the list's own result and the document calls a piece + /// itself. + /// A list builds its entries at its first layout and keeps them, whole and at the + /// width that layout used, as it did. The calls the document makes in one save do not + /// count as an earlier layout of each other. When the first layout was another one, which is a + /// layout of yours before the save, another document's, or a renderer of yours that holds the + /// list, the document lays the list out as it was before the fixes, with those entries. That + /// holds for a list changed since: an item or a child added after that layout is not laid out + /// or drawn, and an entry the clamp narrowed is laid out without the clamp, from the text it + /// had then. Such a list reports nothing, unless the document lays every list out as it was + /// before the fixes (a renderer of yours, a font it cannot draw, an element near the limit): it + /// then reports + /// , and + /// for an entry placed with a part not + /// drawn, as any list does. + /// A document that holds a renderer of yours lays every list out as it was before the + /// fixes. That is any renderer that is not one of this library's own, added with + /// , wherever it sits and whether or not it holds a list. + /// A , a or another renderer this + /// library ships is the library's own, and so is the barcode renderer. The document decides + /// this once, from what was added, before it lays anything out, so the pass that counts pages + /// for a header or footer and the pass that draws lay each list out the same way. The library + /// cannot read where your renderer starts or what it lays out, and a list that moved ahead of + /// it can change whether the document saves. A list the document places this way reports + /// as that code describes, naming + /// this cause. Do + /// not rely on where a list lands in such a document: 3.0 lays a list out one way, whatever + /// called it (#688). + /// When the document calls this method, the exceptions it lists reach you from the + /// save. A list added with never starts at a negative + /// item, so reaches the save only from a renderer + /// you construct with a negative start and add yourself. /// /// /// The start item is negative, the list has items, and the area is not empty. The parameter @@ -138,11 +332,121 @@ private ListRenderer(ListElement list, int startItem, ParagraphRenderer? partial /// An item has a null child or a null text where it is drawn; see . /// public LayoutResult Layout(LayoutContext context) + { + // Removed in 3.0 (#688), which lays a list out one way under every context. A context the + // document did not address to this instance gets the twin, which is what the list was + // before the fixes, and so does every list once the document's scan found a cause + // (ListLayoutRun). The pieces a split of the twin returns are twins, so the rest of the + // placement is as well. + if (!_unclamped) + { + var run = ListLayoutRun.Current; + if (run is { AllAsTwin: true }) return LayOutAsTwin(context, AllListsFor(run)); + if (context.ModeFor(this) == ContinuationMode.Twin) + return LayOutAsTwin(context, TwinPlacement.Document); + + // 2.3.3 keeps the entries an earlier layout built, at the width it used. This list's + // own are built new, so for an earlier layout the twin holds the ones to keep. + if (BuiltByAnEarlierLayout(run)) return LayOutAsTwin(context, TwinPlacement.Held); + } + + _delegate = null; + return LayOut(context); + } + + private static TwinPlacement AllListsFor(ListLayoutRun run) => + (TwinPlacement)((byte)TwinPlacement.AllLists + | (run.FoundUndrawable ? AllListsFont : 0) + | (run.FoundNearTheLimit ? AllListsNearLimit : 0) + | (run.FoundCallerRenderer ? AllListsRenderer : 0)); + + // The 207 of a list the document-wide rule turned into its twin names every cause that applied. + private static string AllListsMessage(TwinPlacement placement) + { + var causes = new List(3); + var bits = (byte)placement & ~(byte)TwinPlacement.AllLists; + if ((bits & AllListsFont) != 0) causes.Add("a list entry in a font it cannot draw"); + if ((bits & AllListsNearLimit) != 0) + causes.Add( + "an element after a list that can need about as many page continuations as one element may use"); + if ((bits & AllListsRenderer) != 0) causes.Add("a renderer of yours"); + var named = causes.Count == 1 + ? causes[0] + : string.Join(", ", causes.GetRange(0, causes.Count - 1)) + " and " + causes[^1]; + return "The document holds " + named + ", so this list was laid out as it was before the text of its " + + "entries was given a width and the entries that do not fit were moved to the next page."; + } + + // The twin lays the list out and this instance answers for it afterwards: the document draws + // and asks for placements on the instance it called, and a Full result names no renderer. The + // twin reports only for a list the document placed, so a list a caller's renderer holds, which + // this instance is told apart from by the context, is handed over as held. + // Removed in 3.0 (#688). + private LayoutResult LayOutAsTwin(LayoutContext context, TwinPlacement placement) + { + var twin = Unclamped(); + _delegate = twin; + if (_items is not null && twin._items is null) twin._earlier = _items; + + twin._handoff = context.IsAddressedByDocument(this) ? placement : TwinPlacement.Held; + return twin.Layout(context); + } + + // True when this list or its twin holds entries that a layout built other than the document's + // own calls in this run: under another run than this one, which is another document or no + // document at all, or by the twin under a call the document did not address to the list, which + // is a renderer of the caller's. A call of the document's own is one the document addressed to + // this list or to its twin, in any pass or probe, and the list's own entries are built only + // by such a call. + private bool BuiltByAnEarlierLayout(ListLayoutRun? run) => + (_items is not null && !ReferenceEquals(_builtUnder, run)) + || (_twin is { _items: not null } twin && (!ReferenceEquals(twin._builtUnder, run) || twin._builtForCaller)); + + // Whether the document called this instance with the context. The session names the instance + // the document called, in probes as well. + private bool IsCalledByDocument(LayoutContext context) => + context.Session is { } session && ReferenceEquals(session.Called, this); + + // The context of a child that this list lays out in its own mode: the new layout hands a child + // a context addressed to it, and the twin hands it the one a narrowed area gives, which is what + // the twin did before the document addressed anything. + private LayoutContext ChildContext(LayoutContext context, ParagraphRenderer child, LayoutBox area) => + _unclamped ? context.WithArea(area) : context.Address(this, child, area); + + private LayoutResult LayOut(LayoutContext context) { var area = context.Area.Deflate(_list.Margins); if (area.IsEmpty) return LayoutResult.Nothing(); - _items ??= BuildItems(area.Width); + // How the document placed this instance is read on every call, for the pieces the call + // returns. A twin the document called itself was chosen by its limit decision; one a list + // handed the call to carries what that list was told. + if (_unclamped) + { + _placement = context.IsPlacedAsTwin(this) ? TwinPlacement.Limit + : _handoff != TwinPlacement.Held ? _handoff + : _placementInherited ? _placement + : context.IsAddressedByDocument(this) ? TwinPlacement.Document + : TwinPlacement.Held; + } + + if (_items is null) + { + var run = ListLayoutRun.Current; + _builtUnder = run; + if (_earlier is { } earlier) + { + // 2.3.3 never reads the list again once it has built its entries, so a list that + // was changed since has none of its new items here, whatever it holds now. + _items = AdoptEarlier(earlier); + _earlier = null; + } + else + { + _builtForCaller = _unclamped && !IsCalledByDocument(context); + _items = BuildItems(area.Width); + } + } if (_items.Count == 0) { @@ -156,6 +460,20 @@ public LayoutResult Layout(LayoutContext context) // as the cause (#556). ArgumentOutOfRangeException.ThrowIfNegative(_startItem, "startItem"); + if (!_unclamped) + { + // An entry no page holds is placed where it falls, as it always was, and moving the + // entries around it would change what is drawn of it. So the whole list keeps that + // layout, and the twin reports the entry. + if (!_placeabilityKnown) TryEntriesOnAnEmptyPage(context, area); + if (_wholeAsMain) return LayOutAsTwin(context, TwinPlacement.Document); + + // The list lays out its new way, which can differ from its twin's, so the document + // decides before it uses this result (#686). The bound covers both layouts. + if (context.Session is { Mode: ContinuationMode.Undecided, Probing: false } session) + session.Report(this, UnitBound(area.Width)); + } + // Walk items and accumulate height, handling overflow. var y = area.Y; var remaining = area.Height; @@ -169,20 +487,40 @@ public LayoutResult Layout(LayoutContext context) offered.Add(remaining); tops.Add(y); var itemArea = new LayoutBox(area.X, y, area.Width, remaining); - var itemCtx = context.WithArea(itemArea); + var entry = _items[i]; // For the first item, use the partial content override if present. var contentRenderer = (i == _startItem && _partialContentOverrideAtStart is not null) ? _partialContentOverrideAtStart - : _items[i].Content; - var markerRenderer = _items[i].Marker; + : entry.Content; + var markerRenderer = entry.Marker; // Layout both marker and content at the same Y (side-by-side). - var markerResult = markerRenderer.Layout(itemCtx); - var contentResult = contentRenderer.Layout(itemCtx); - - if (markerResult.Status == LayoutResult.Outcome.Nothing - && contentResult.Status == LayoutResult.Outcome.Nothing) + var markerResult = markerRenderer.Layout(ChildContext(context, markerRenderer, itemArea)); + + // The text of a clamped entry was discarded before the clamp, so an entry whose marker + // has no room was placed by that outcome: both Nothing, which splits the list before + // the entry or, at a page top, refuses it. Giving the text a width must not turn that + // refusal into a save that draws the text and drops the marker. + var contentResult = entry.Clamped && markerResult.Status == LayoutResult.Outcome.Nothing + ? LayoutResult.Nothing() + : contentRenderer.Layout(ChildContext(context, contentRenderer, itemArea)); + + // An entry is placed when its marker and its content are both placed. When one of them + // is not, because the marker returned Nothing or only some of its lines, or the content + // returned Nothing, the entry moves whole to the next page, as an entry does when + // neither fits. Every entry fits a page of its own here, because a list that holds one + // that does not was handed to the twin above. At the top of a page nothing is gained by + // moving it, and an entry that cannot be drawn keeps the part that fits, as it always + // has; Draw reports the part that does not. Text that has no width is not a part that + // did not fit: it is discarded, as it always was, and the clamp reports the entries it + // can give a width. The twin moves no entry. + var moves = !_unclamped + && PartUnplaced(markerResult, contentResult, contentRenderer, area.Width) + && !(i == _startItem && context.AtPageTop); + + if ((markerResult.Status == LayoutResult.Outcome.Nothing + && contentResult.Status == LayoutResult.Outcome.Nothing) || moves) { // Nothing fits if (i == _startItem) @@ -196,10 +534,24 @@ public LayoutResult Layout(LayoutContext context) var overflow = new ListRenderer(_list, i) { _items = _items, + _builtUnder = _builtUnder, + _unclamped = _unclamped, + _placement = _placement, + _placementInherited = _unclamped, + _placeabilityKnown = _placeabilityKnown, + _unplaceable = _unplaceable, }; var split = new ListRenderer(_list, _startItem, _partialContentOverrideAtStart) { _items = _items, + _builtUnder = _builtUnder, + _unclamped = _unclamped, + _placement = _placement, + _placementInherited = _unclamped, + _placeabilityKnown = _placeabilityKnown, + _unplaceable = _unplaceable, + _indentClamped = _indentClamped, + _clampSkipped = _clampSkipped, _endItem = i, _occupied = _occupied, _offered = offered, @@ -228,11 +580,25 @@ public LayoutResult Layout(LayoutContext context) var overflowList = new ListRenderer(_list, i, contentOverflow) { _items = _items, + _builtUnder = _builtUnder, + _unclamped = _unclamped, + _placement = _placement, + _placementInherited = _unclamped, + _placeabilityKnown = _placeabilityKnown, + _unplaceable = _unplaceable, }; var split = new ListRenderer(_list, _startItem, _partialContentOverrideAtStart) { _items = _items, + _builtUnder = _builtUnder, + _unclamped = _unclamped, + _placement = _placement, + _placementInherited = _unclamped, + _placeabilityKnown = _placeabilityKnown, + _unplaceable = _unplaceable, + _indentClamped = _indentClamped, + _clampSkipped = _clampSkipped, _endItem = i + 1, _occupied = _occupied, _offered = offered, @@ -252,6 +618,99 @@ public LayoutResult Layout(LayoutContext context) return LayoutResult.Full(_occupied); } + // An upper bound on the page continuations a placement of this list can take, in either + // layout, from its start item: the number of units it holds, an entry or one wrapped line of + // its text, whichever is more for that entry. + // + // Every Partial the list returns consumes at least one unit. A split before an entry has + // placed at least one whole entry, and a split inside an entry has placed at least one of its + // lines, because ParagraphRenderer only splits when maxLines is positive. An entry that moves + // to the next page leaves the entries before it as the piece that ends. The piece that ends + // the list consumes at least one more. A Nothing the document retries on the next page can + // only come first: the document offers a page top the area the retry was offered and the list + // answers the same height the same way, so the call after a Nothing or a Partial, which is at a + // page top, is neither. So continuations are at most one Nothing plus the Partial count, and + // the Partial count is at most the units less one. The twin's entries hold no more units than + // these: an entry whose text the clamp widened has a line or more here and none there, and an + // entry the clamp left alone is the same in both. + private long UnitBound(double areaWidth) + { + // Wrapping an entry here is what its layout does first, at the width it would use, and the + // wrap refuses nothing that BuildItems has not already refused, so it cannot raise a + // refusal the layout would not. + long units = 0; + for (var i = _startItem; i < _items!.Count; i++) + units += Math.Max(1, _items[i].Content.LineCountAt(areaWidth)); + return units; + } + + // Lays each entry's marker and text out on a page of its own and records whether both place. + // An entry that fits no page, because a line of its marker or of its text is taller than a + // page, makes the whole list lay out as its twin: where such an entry falls is where it was + // always placed, and moving the entries around it would show fewer of its lines than before. + // A context the document built names the page a Nothing is retried on, which is that page. + // Removed in 3.0 (#688), with the twin that keeps such a list as it was. + // + // This reads every entry before the first is placed, and the layout reads them one at a time, + // as the twin does. A refusal the layout raises for an entry it reaches late, and not for one + // before it (a style, a surrogate), would then come first here and replace the refusal the + // twin raises where it raised it. So a refusal in this walk makes the list lay out as the + // twin, whose own walk raises it where it always did. + private void TryEntriesOnAnEmptyPage(LayoutContext context, LayoutBox area) + { + _placeabilityKnown = true; + if (context.FreshPageArea is not { } fresh) return; + + var page = fresh.Deflate(_list.Margins); + var freshArea = new LayoutBox(area.X, page.Y, area.Width, page.Height); + try + { + for (var i = _startItem; i < _items!.Count; i++) + { + var entry = _items[i]; + + // A paragraph keeps where its last layout put it, and Draw reads that when the + // layout it makes for itself answers Nothing. An entry that is not placed where + // the list lays it out must be drawn as it was, so the page of its own that is + // tried here leaves no trace. + var markerWas = entry.Marker.Placement; + var contentWas = entry.Content.Placement; + var markerFits = entry.Marker.Layout(ChildContext(context, entry.Marker, freshArea)).Status + == LayoutResult.Outcome.Full; + + // Text with no width is discarded, not unplaced, as PartUnplaced reads it. + var contentFits = entry.Content.Layout(ChildContext(context, entry.Content, freshArea)).Status + != LayoutResult.Outcome.Nothing + || entry.Content.LineCountAt(area.Width) == 0; + entry.Marker.RestorePlacement(markerWas); + entry.Content.RestorePlacement(contentWas); + if (markerFits && contentFits) continue; + + (_unplaceable ??= new bool[_items.Count])[i] = true; + _wholeAsMain = true; + } + } + catch (Exception ex) when (ex is not OutOfMemoryException and not OperationCanceledException) + { + _unplaceable = null; + _wholeAsMain = true; + } + } + + // True when exactly one side of an entry is not placed: the marker did not get all its lines, + // or the text got none although it has a width. Both Nothing is the case that splits the list + // before the entry, and text with no width is discarded, not unplaced. + private static bool PartUnplaced( + LayoutResult marker, LayoutResult content, ParagraphRenderer contentRenderer, double areaWidth) + { + var markerNothing = marker.Status == LayoutResult.Outcome.Nothing; + var contentNothing = content.Status == LayoutResult.Outcome.Nothing; + if (markerNothing && contentNothing) return false; + + return marker.Status != LayoutResult.Outcome.Full + || (contentNothing && contentRenderer.LineCountAt(areaWidth) != 0); + } + // ── Phase 2: Draw ───────────────────────────────────────────────────────── /// Draws each item's marker and content, building the tagged L → LI → Lbl/LBody hierarchy when tagging is enabled. @@ -266,13 +725,39 @@ public LayoutResult Layout(LayoutContext context) /// public void Draw(DrawContext ctx) { + // The document draws the instance it called. When the twin laid the list out, this + // instance answers with the twin's drawing. Removed in 3.0 (#688). + if (_delegate is { } delegated) + { + delegated.Draw(ctx); + return; + } + if (_items is null) return; // Only the piece that starts the list, drawn through the document's context, takes part in // the walk, so a list that is measured and never drawn, or that starts at a later item, // leaves the items it did not report for the list that does. if (_startItem == 0 && _partialContentOverrideAtStart is null && ctx.Diagnostics is { } sink) + { ReportBelowSecondLevel(sink); + if (_indentClamped > 0) + sink.Report( + LayoutDiagnosticCode.ListIndentClamped, + 0, + "A list indent left an entry's text no width beside its gutter, so the text was given a width, that of its widest word or the room right of its marker, and may overprint the marker.", + _indentClamped, + perElement: true); + if (_placement is not (TwinPlacement.Held or TwinPlacement.Document) && _items.Count > 0) + sink.Report( + LayoutDiagnosticCode.ListIndentClampSkipped, + 0, + _placement == TwinPlacement.Limit + ? "Laying the list out with the text of its entries given a width, or with the entries that do not fit moved to the next page, would have taken more page continuations than one element may use, so the list was laid out as it was before both." + : AllListsMessage(_placement), + Math.Max(1, _clampSkipped), + perElement: true); + } // _occupied is already the margin-deflated area from Layout; do not deflate again. var area = _occupied; @@ -285,9 +770,15 @@ public void Draw(DrawContext ctx) if (ctx.Tagged) listElem = new PdfStructElem("L"); + var partDropped = 0; + + // The children are laid out again here in the mode this list was laid out in. The twin was + // laid out as the twin, and a list the document addressed was laid out the new way. + var childMode = _unclamped ? ContinuationMode.Twin : ContinuationMode.New; for (var i = _startItem; i < _endItem; i++) { - var (marker, baseContent, _) = _items[i]; + var marker = _items[i].Marker; + var baseContent = _items[i].Content; // On a continuation page the start item resumes mid-content; its marker // was already drawn on the page where the item began, so suppress it here @@ -300,13 +791,21 @@ public void Draw(DrawContext ctx) // enough to drop a line (#556); the fallback is for a renderer Layout never ran on. var offeredHeight = _offered is { } o ? o[i - _startItem] : area.Bottom - y; var itemArea = new LayoutBox(area.X, y, area.Width, offeredHeight); - var itemCtx = new LayoutContext(itemArea); - - var markerH = isContinuation ? 0 : marker.Layout(itemCtx).OccupiedArea?.Height ?? 0; - var contentResult = content.Layout(itemCtx); + var markerResult = isContinuation ? null : marker.Layout(LayoutContext.Addressed(itemArea, marker, childMode)); + var markerH = markerResult?.OccupiedArea?.Height ?? 0; + var contentResult = content.Layout(LayoutContext.Addressed(itemArea, content, childMode)); + if (markerResult is not null + && (PartUnplaced(markerResult, contentResult, content, area.Width) + || (_unplaceable is { } unplaceable && unplaceable[i]))) + partDropped++; var itemH = Math.Max(markerH, contentResult.OccupiedArea?.Height ?? 0); + // A clamped entry whose line does not fit where it is placed has its text dropped, as + // it was when the text had no width. Its paragraph has been wrapped, so drawing it + // would write an empty text object where that left none (#685). + var placedWithoutText = _items[i].Clamped && contentResult.Status == LayoutResult.Outcome.Nothing; + if (ctx.Tagged && listElem is not null) { // LI groups the label and body for one list item. @@ -330,7 +829,7 @@ public void Draw(DrawContext ctx) if (!isContinuation) DrawMarker(marker, ctx); - content.Draw(ctx); + if (!placedWithoutText) content.Draw(ctx); // Reset for safety (layout/draw may be called multiple times in pagination) if (!isContinuation) @@ -345,7 +844,7 @@ public void Draw(DrawContext ctx) { if (!isContinuation) DrawMarker(marker, ctx); - content.Draw(ctx); + if (!placedWithoutText) content.Draw(ctx); } y += itemH; @@ -353,6 +852,18 @@ public void Draw(DrawContext ctx) if (listElem is not null) ctx.RegisterStructElemTree(listElem); + + // An entry reaches this count only at the top of a page that cannot hold both its marker + // and its text, or in the list laid out as it was before entries moved. A twin that a + // caller's renderer holds reports nothing: the document did not place that list. + if (partDropped > 0 && ctx.Diagnostics is { } dropSink + && (!_unclamped || _placement != TwinPlacement.Held)) + dropSink.Report( + LayoutDiagnosticCode.ListEntryPartDropped, + 0, + "A list entry was placed with its marker or its text not drawn, because it does not fit where it falls and was not moved to the next page.", + partDropped, + perElement: true); } // A marker is text the library wrote, not the caller's: a '?' it substitutes, such as the @@ -470,9 +981,142 @@ void EndWord() return widest; } - private List<(ParagraphRenderer Marker, ParagraphRenderer Content, ListItem Item)> BuildItems(double areaWidth) + /// + /// Narrows a gutter that would leave an entry's text no width to the one that gives the text + /// exactly the width of its widest word. + /// + /// + /// The gutter is changed only when minus it is zero or negative + /// (the text would be discarded), the entry's own marker starts inside the area, and the text + /// has a word to measure. In every other case it is returned as given, which is what keeps a + /// width that is positive but short of the widest word, a NaN gutter and an entry with + /// no measurable word on their earlier output. The new gutter is never left of + /// , so the content does not start left of its own marker. + /// + internal static bool TryClampGutter( + double areaWidth, double gutter, double markerInset, double widestWord, out double clamped) + { + clamped = gutter; + + // Written so that a NaN in any operand makes a test false and leaves the gutter alone. + if (!(areaWidth - gutter <= 0)) return false; + var room = areaWidth - markerInset; + if (!(room > 0) || !(widestWord > 0)) return false; + + // The paragraph deflates the area by the gutter, so it sees areaWidth - g, which is not + // always the widest word again once g = areaWidth - widest has been rounded: one step short + // makes WordWrap read the word as wider than the line and hard-break it. + if (widestWord >= room) + { + clamped = markerInset; + return true; + } + + // The result is never left of markerInset, so no clamp is needed after the loop. The word + // is narrower than room = fl(areaWidth - markerInset), so fl(areaWidth - word) is at least + // fl(areaWidth - BitDecrement(room)), which is at least markerInset: the exact difference + // sits one spacing of room above it, and rounding moves it by at most half that. The loop + // steps only while g is above markerInset, and a double above one steps down to it at + // worst. + var g = areaWidth - widestWord; + while (g > markerInset && areaWidth - g < widestWord) g = Math.BitDecrement(g); + clamped = g; + return true; + } + + // Whether everything an entry would draw can be drawn in the document: its marker, which is + // set in the style the entry inherits, and each run that holds text (ListLayoutRun.CanDraw + // says what that asks of a style). A run with no text draws nothing, so its style is not read. + // A white-space-only run is read although it may yield no fragment, so this is stricter than + // the draw, in the safe direction. An item built from a string has one run, in the style it + // inherits, so that style is the only one to read. + // Removed in 3.0 (#688), which refuses such a font where the style is built. + private static bool CanDrawEntry(ListLayoutRun? run, TextStyle markerStyle, ListItem item) + { + if (!ListLayoutRun.CanDraw(run, markerStyle)) return false; + if (item.OwnRuns is not { } runs) return true; + + for (var i = 0; i < runs.Count; i++) + { + if (runs[i].Text.Length == 0) continue; + if (runs[i].Style is not { } style || !ListLayoutRun.CanDraw(run, style)) return false; + } + + return true; + } + + /// + /// Whether any entry of holds something the document cannot draw. It + /// reads the entries BuildItems builds, in the styles it builds them in, and allocates nothing. + /// + /// + /// A null text stops nothing here: the layout refuses it where it reaches it, and a list that + /// is refused is refused whatever this says. Removed in 3.0 (#688). + /// + internal static bool HoldsUndrawableEntry(ListElement list, ListLayoutRun run) { - var result = new List<(ParagraphRenderer, ParagraphRenderer, ListItem)>(); + var defaultStyle = list.DefaultStyle ?? TextStyle.Default; + var items = list.Items; + for (var i = 0; i < items.Count; i++) + { + var item = items[i]; + var itemStyle = item.Style ?? defaultStyle; + if (!CanDrawEntry(run, itemStyle, item)) return true; + if (item.Children is not { } children) continue; + for (var c = 0; c < children.Count; c++) + { + if (!CanDrawEntry(run, children[c].Style ?? itemStyle, children[c])) return true; + } + } + + return false; + } + + // The entries an earlier layout of the list built, as 2.3.3 keeps them: the whole list as that + // layout saw it, whatever the list holds now. An entry the clamp narrowed is not one 2.3.3 + // built. It built that entry's text with the gutter the entry has without the clamp, at the + // width the earlier layout used, and so does this, from the text and the gutter the entry + // recorded. The marker is the same either way. Removed in 3.0 (#688), with the twin. + private List AdoptEarlier(List earlier) + { + var items = new List(earlier.Count); + for (var i = 0; i < earlier.Count; i++) + { + var entry = earlier[i]; + // The entries here are the list's own, so Clamped says the clamp would narrow the + // entry, which is what the twin counts. + if (entry.Clamped) _clampSkipped++; + items.Add(entry.Clamped ? entry with { Content = WithoutClamp(entry), Clamped = false } : entry); + } + + return items; + } + + private static ParagraphRenderer WithoutClamp(Entry entry) + { + var narrowed = entry.Content.Paragraph; + var paragraph = new Paragraph(narrowed.Runs) + { + Margins = narrowed.Margins with { Left = entry.UnclampedGutter }, + }; + return new ParagraphRenderer(paragraph) + { + ElementLanguage = entry.Content.ElementLanguage, + RunOwner = entry.Content.RunOwner, + }; + } + + /// + /// The times this thread built the entries of a list, which a test reads to see that a piece of + /// a list does not build them again. Removed in 3.0 (#688), with the twin. + /// + [ThreadStatic] + internal static int BuildCalls; + + private List BuildItems(double areaWidth) + { + BuildCalls++; + var result = new List(); var indent = _list.Indent; var defaultStyle = _list.DefaultStyle ?? TextStyle.Default; @@ -506,11 +1150,39 @@ void EndWord() // widest word still fits keeps the fix from introducing a hard break that today's // indent does not have, and where it cannot, today's indent and the overprint it // carries are the lesser harm. - if (areaWidth - gutter < WidestWord(contentRuns)) + var widest = WidestWord(contentRuns); + if (areaWidth - gutter < widest) { gutter = indent; } + // An indent that leaves the content no width at all discards the text and keeps the + // marker, because ParagraphRenderer.Layout returns Nothing for a non-positive width. + // Only that case is changed; a width that is positive but short of the widest word + // keeps the hard-breaking it has always had. That Nothing is also why no run's style + // was read: the wrap and the line-height walk come after it. Giving the text a width + // starts them, so an entry is clamped only when every run that holds text passes the + // walk's checks (a finite font size, a finite colour). The content paragraph has no tab + // stops, so the leader and stop checks cannot fire, and a null style is refused by + // ListItem; a surrogate the wrap refuses in an embedded font is one WidestWord has + // already measured. + // The twin asks the same question and only counts the answer, which is what it reports + // when the document chose it. The gutter test comes first because it is the one that + // fails for almost every entry. + var unclampedGutter = gutter; + var wouldClamp = TryClampGutter(areaWidth, gutter, 0, widest, out var clampedGutter) + && LayoutValidation.AreRunStylesAccepted(contentRuns); + var clamped = !_unclamped && wouldClamp; + if (clamped) + { + gutter = clampedGutter; + _indentClamped++; + } + else if (wouldClamp) + { + _clampSkipped++; + } + // Marker paragraph: sits in the gutter (left portion of the line). var markerPara = new Paragraph(markerText, itemStyle) { @@ -527,7 +1199,7 @@ void EndWord() }; var contentRenderer = new ParagraphRenderer(contentPara) { ElementLanguage = item.Language, RunOwner = "A list item" }; - result.Add((markerRenderer, contentRenderer, item)); + result.Add(new Entry(markerRenderer, contentRenderer, item, clamped, unclampedGutter)); // A null child of a top-level item is refused here, where the position is known. The // same null on a grandchild is counted when the list is drawn instead, because @@ -564,9 +1236,27 @@ void EndWord() // parent rather than continuing the top-level sequence. var childMarkerWidth = childStyle.MeasureString(childMarker); var childGutter = Math.Max(indent * 2, indent + childMarkerWidth); - if (areaWidth - childGutter < WidestWord(childRuns)) + var childWidest = WidestWord(childRuns); + if (areaWidth - childGutter < childWidest) childGutter = indent * 2; + // The child's marker starts at `indent`, so that is the leftmost the clamped + // content may start. + var unclampedChildGutter = childGutter; + var childWouldClamp = TryClampGutter( + areaWidth, childGutter, indent, childWidest, out var clampedChildGutter) + && LayoutValidation.AreRunStylesAccepted(childRuns); + var childClamped = !_unclamped && childWouldClamp; + if (childClamped) + { + childGutter = clampedChildGutter; + _indentClamped++; + } + else if (childWouldClamp) + { + _clampSkipped++; + } + var childMarkerPara = new Paragraph(childMarker, childStyle) { Margins = new EdgeInsets(0, 0, 0, indent), @@ -576,10 +1266,12 @@ void EndWord() Margins = new EdgeInsets(0, 0, 0, childGutter), }; - result.Add(( + result.Add(new Entry( new ParagraphRenderer(childMarkerPara) { RunOwner = "A list item" }, new ParagraphRenderer(childContentPara) { ElementLanguage = child.Language, RunOwner = "A list item" }, - child)); + child, + childClamped, + unclampedChildGutter)); } } } diff --git a/src/VellumPdf.Layout/Rendering/ParagraphRenderer.cs b/src/VellumPdf.Layout/Rendering/ParagraphRenderer.cs index b0d8be9ea..86ff6b381 100644 --- a/src/VellumPdf.Layout/Rendering/ParagraphRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/ParagraphRenderer.cs @@ -143,16 +143,7 @@ public LayoutResult Layout(LayoutContext context) if (area.Width <= 0) return LayoutResult.Nothing(); - if (_lines is null) - { - // The document checks this before any layout for its own paragraphs; a renderer of - // yours that lays one out meets it here. - LayoutValidation.ValidateLeaderSizes(_para); - var stops = StopsWithin(_para, area.Width, out _tabStopsBeyond); - (_lines, _lineEnds) = WordWrap(_para.Runs, area.Width, out var nullStyleRuns, stops); - _nullStyleRuns = nullStyleRuns; - WrapCalls++; - } + EnsureWrapped(area.Width); // The line height is a property of the wrap, so it is taken once per wrap: every later // Layout on this renderer, and every piece a split hands on, reads the same _lines. @@ -233,6 +224,45 @@ public LayoutResult Layout(LayoutContext context) return LayoutResult.Partial(_occupied, split, overflow); } + // Where the last successful Layout left this renderer, which Draw reads when the Layout it + // makes for itself answers Nothing. A caller that lays the paragraph out only to measure it, + // and must not change what a later Draw does, reads this first and puts it back (ListRenderer, + // for the page of its own it lays each entry out on). Removed in 3.0 (#688) with that analysis. + internal (int EndLine, LayoutBox Occupied) Placement => (_endLine, _occupied); + + internal void RestorePlacement((int EndLine, LayoutBox Occupied) placement) => + (_endLine, _occupied) = placement; + + // Wraps once, at the width of the first Layout call, and keeps the lines for every later call + // and for the pieces a split returns. + [System.Diagnostics.CodeAnalysis.MemberNotNull(nameof(_lines), nameof(_lineEnds))] + private void EnsureWrapped(double width) + { + if (_lines is not null && _lineEnds is not null) return; + + // The document checks this before any layout for its own paragraphs; a renderer of + // yours that lays one out meets it here. + LayoutValidation.ValidateLeaderSizes(_para); + var stops = StopsWithin(_para, width, out _tabStopsBeyond); + (_lines, _lineEnds) = WordWrap(_para.Runs, width, out var nullStyleRuns, stops); + _nullStyleRuns = nullStyleRuns; + WrapCalls++; + } + + /// + /// The number of lines would wrap this paragraph into when it is offered a + /// box wide, wrapping it now when it has not been wrapped. Zero + /// where returns Nothing for lack of width. + /// + internal int LineCountAt(double boxWidth) + { + // The subtraction Deflate makes, so the width is the one Layout would wrap at. + var width = boxWidth - _para.Margins.Left - _para.Margins.Right; + if (width <= 0) return 0; + EnsureWrapped(width); + return _lines.Count; + } + // Line height = max EffectiveLeading across every fragment in every line. _lineHeight is // written as the walk goes, so a walk that throws leaves what it had reached. private void TakeLineHeight() diff --git a/tests/VellumPdf.Barcodes.Tests/BarcodeRendererTests.cs b/tests/VellumPdf.Barcodes.Tests/BarcodeRendererTests.cs index e38090860..684675819 100644 --- a/tests/VellumPdf.Barcodes.Tests/BarcodeRendererTests.cs +++ b/tests/VellumPdf.Barcodes.Tests/BarcodeRendererTests.cs @@ -15,6 +15,24 @@ public sealed class BarcodeRendererTests public void Constructor_nullBarcode_throws() => Assert.Throws(() => new BarcodeRenderer(null!)); + /// + /// The layout library treats a renderer from outside it as a caller's, and lays every list + /// out as it did before the list fixes, unless that renderer is marked as one of the + /// library's own. The mark is an internal interface, which only this package can implement + /// through the layout library's friend assembly; the document reads it, and nothing in the + /// public surface shows it. + /// + [Fact] + public void TheRenderer_carriesTheMarkThatItIsOneOfTheLibrarysOwn() + { + var marks = typeof(BarcodeRenderer).GetInterfaces() + .Where(i => i.FullName == "VellumPdf.Layout.Rendering.IListFreeRenderer").ToArray(); + + var mark = Assert.Single(marks); + Assert.False(mark.IsPublic); + Assert.Empty(mark.GetMembers()); + } + [Fact] public void TooTallForRemainingSpace_overflowsToPage2() { diff --git a/tests/VellumPdf.Layout.Tests/BoundaryContractTests.cs b/tests/VellumPdf.Layout.Tests/BoundaryContractTests.cs index 2ca63cb25..c79c4c6dd 100644 --- a/tests/VellumPdf.Layout.Tests/BoundaryContractTests.cs +++ b/tests/VellumPdf.Layout.Tests/BoundaryContractTests.cs @@ -400,16 +400,15 @@ public void FlatListIndent_atNaN_isRefusedByTheCanvas_where2_3_3WroteAnInvalidTo } /// - /// At positive infinity a flat list draws its marker and discards the item text (a behaviour - /// #476 intends to change): one show - /// operator in the content stream, and the item's own text nowhere in it. A default indent - /// draws both, which is what makes the first assertion discriminating rather than a count of - /// whatever happened to be emitted. + /// At positive infinity a flat list draws its marker and its item text: two show operators and + /// the item's own text in the content stream, the same as at a default indent. The text was + /// discarded before #476, which left one show operator, so the second assertion discriminates + /// the clamp from a document that merely saved. /// [Theory] - [InlineData(double.PositiveInfinity, 1, false)] + [InlineData(double.PositiveInfinity, 2, true)] [InlineData(20, 2, true)] - public void FlatListIndent_atPositiveInfinity_drawsTheMarkerAndDropsTheText( + public void FlatListIndent_atPositiveInfinity_drawsTheMarkerAndTheText( double indent, int showOperators, bool keepsText) { using var doc = new LayoutDocument(); diff --git a/tests/VellumPdf.Layout.Tests/LayoutDiagnosticsTests.cs b/tests/VellumPdf.Layout.Tests/LayoutDiagnosticsTests.cs index 1b09ca05b..6592b64c9 100644 --- a/tests/VellumPdf.Layout.Tests/LayoutDiagnosticsTests.cs +++ b/tests/VellumPdf.Layout.Tests/LayoutDiagnosticsTests.cs @@ -1081,7 +1081,7 @@ public void AListMeasuredAndNeverDrawn_leavesItsNullsForTheListThatIsDrawn() var ex = Assert.Throws(() => doc.Save(new MemoryStream())); Assert.StartsWith("StrictDiagnostics refused the save: NullGrandchildText in List 1", ex.Message, StringComparison.Ordinal); - var item = Assert.Single(doc.Diagnostics); + var item = Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.NullGrandchildText); Assert.Equal(1, item.Count); Assert.Equal(1, item.ElementIndex); } diff --git a/tests/VellumPdf.Layout.Tests/ListCallerRendererRuleTests.cs b/tests/VellumPdf.Layout.Tests/ListCallerRendererRuleTests.cs new file mode 100644 index 000000000..7c7703254 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/ListCallerRendererRuleTests.cs @@ -0,0 +1,309 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Security.Cryptography; +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; + +namespace VellumPdf.Layout.Tests; + +/// +/// A document that holds a renderer that is not one of the library's own lays every list out as it +/// was before the fixes of #476 and #685, decided once from the elements added to it, wherever the +/// renderer sits and however it lays its own list out. The reference for each row is the same +/// document built over , the list as it was. +/// +public sealed class ListCallerRendererRuleTests +{ + private static readonly DateTimeOffset Stamp = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + + private static TextStyle H(double size) => new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = size }; + + private static byte[] Save(Document doc) + { + doc.Timestamp = Stamp; + doc.DocumentId = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray(); + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + private static string Sha(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes))[..16]; + + private static string[] Shows(byte[] bytes) => + Regex.Matches(PdfTestUtil.DecompressAllFlatStreams(bytes), @"\(((?:\\.|[^\\)])*)\)\s*Tj") + .Select(m => m.Groups[1].Value).ToArray(); + + // An indent no page width leaves any text, so the new layout clamps the entry. + private static ListElement Clamp() => + new ListElement(ListStyle.OrderedDecimal) { Indent = 300 }.Add(new ListItem("clamped text", H(10))); + + // Many entries of many words: one word to a line when clamped, only the markers as it was. + private static ListElement Tall(int items) + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 300 }; + for (var i = 0; i < items; i++) + list.Add(new ListItem(string.Join(' ', Enumerable.Repeat("word", 12)), H(10))); + return list; + } + + private static ListElement Undrawable() => + new ListElement(ListStyle.Unordered) { Indent = 1000 } + .Add(new ListItem([new TextRun("bad", new TextStyle { FontRef = new FontReference((Standard14)99), FontSize = 10 })]) + { Style = H(10) }); + + private static TableElement Table() + { + var table = new TableElement(); + table.AddRow().AddCell("x"); + return table; + } + + private static Preformatted NearTheLimit() => new(new string('\t', 1_700), H(1)) { TabWidth = 32 }; + + // A renderer of the caller's that takes one point and draws nothing. + private sealed class Opaque : IRenderer + { + public LayoutResult Layout(LayoutContext context) => + LayoutResult.Full(new LayoutBox(context.Area.X, context.Area.Y, 1, 1)); + + public void Draw(DrawContext ctx) + { + } + } + + // A renderer of the caller's that lays a list out only from its Draw, at the area Layout kept. + private sealed class LaysOutFromDraw(IRenderer inner) : IRenderer + { + private LayoutBox _box; + + public LayoutResult Layout(LayoutContext context) + { + _box = context.Area.WithHeight(Math.Min(20, context.Area.Height)); + return LayoutResult.Full(_box); + } + + public void Draw(DrawContext ctx) + { + inner.Layout(new LayoutContext(_box)); + inner.Draw(ctx); + } + } + + private static Document Page(bool footer) + { + var doc = new Document { PageSize = new PdfRectangle(0, 0, 300, 300), Margins = new EdgeInsets(10, 10, 30, 10) }; + if (footer) doc.SetFooter("pg{page}of{pages}"); + return doc; + } + + private static string[] Skipped(Document doc) => + doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped) + .Select(d => d.Message).ToArray(); + + private const string RendererCause = "a renderer of yours"; + + /// + /// The renderer before the lists, between them, after them, or the only other element: each is + /// the same document as the one built over the twins, and the lists the document places say + /// why. The control without the renderer is clamped, so the rows compare two layouts that + /// differ. + /// + [Theory] + [InlineData("before", false)] + [InlineData("between", false)] + [InlineData("after", false)] + [InlineData("before", true)] + [InlineData("after", true)] + public void ARendererOfTheCallers_anywhere_laysEveryListOutAsItWas(string where, bool footer) + { + Document Build(bool twin, bool withCaller) + { + var doc = Page(footer); + if (withCaller && where == "before") doc.Add(new Opaque()); + doc.Add(twin ? new ListRenderer(Tall(12)).Unclamped() : new ListRenderer(Tall(12))); + if (withCaller && where == "between") doc.Add(new Opaque()); + doc.Add(twin ? new ListRenderer(Clamp()).Unclamped() : new ListRenderer(Clamp())); + if (withCaller && where == "after") doc.Add(new Opaque()); + return doc; + } + + var reference = Save(Build(twin: true, withCaller: true)); + var doc = Build(twin: false, withCaller: true); + var bytes = Save(doc); + + Assert.Equal(Sha(reference), Sha(bytes)); + Assert.NotEqual(Sha(reference), Sha(Save(Build(twin: false, withCaller: false)))); + Assert.All(Skipped(doc), m => Assert.Contains(RendererCause, m, StringComparison.Ordinal)); + Assert.Equal(2, Skipped(doc).Length); + Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListIndentClamped); + } + + /// + /// The two public doors a renderer enters a document by, + /// and , are both read. + /// + [Fact] + public void TheDocumentRendererDoor_isReadAsWellAsTheDocumentOne() + { + var pdf = new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 300, 300), new EdgeInsets(10)); + renderer.Add(new ListRenderer(Clamp())); + renderer.Add(new Opaque()); + using var ms = new MemoryStream(); + + renderer.Render(ms); + + var one = Assert.Single(renderer.Diagnostics); + Assert.Equal(LayoutDiagnosticCode.ListIndentClampSkipped, one.Code); + Assert.Contains(RendererCause, one.Message, StringComparison.Ordinal); + } + + /// + /// A renderer this library ships, added through Add(IRenderer), is the library's own: + /// the lists are laid out the new way and nothing is reported as skipped. + /// + [Theory] + [InlineData("paragraph")] + [InlineData("list")] + [InlineData("table")] + public void ARendererTheLibraryShips_isNotARendererOfTheCallers(string kind) + { + var doc = Page(footer: false); + doc.Add(new ListRenderer(Clamp())); + doc.Add(kind switch + { + "paragraph" => new ParagraphRenderer(new Paragraph("text", H(10))), + "list" => new ListRenderer(Clamp()), + _ => (IRenderer)new TableRenderer(Table()), + }); + + Save(doc); + + Assert.Empty(Skipped(doc)); + Assert.Contains(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListIndentClamped); + } + + /// + /// A footer counts pages in a pass of its own, and the pass that draws must agree with it. The + /// renderer lays its list out only from its Draw, so only the drawing pass reaches that + /// list: the total in the footer is the number of pages in the file whatever the list holds. + /// + [Theory] + [InlineData(3)] + [InlineData(10)] + [InlineData(30)] + public void AFooterTotal_isThePageCountOfTheFile_inADocumentThatHoldsARenderer(int items) + { + Document Build(bool twin) + { + var doc = Page(footer: true); + doc.Add(twin ? new ListRenderer(Clamp()).Unclamped() : new ListRenderer(Clamp())); + doc.Add(new LaysOutFromDraw(new ListRenderer(Undrawable()))); + doc.Add(twin ? new ListRenderer(Tall(items)).Unclamped() : new ListRenderer(Tall(items))); + return doc; + } + + var bytes = Save(Build(twin: false)); + + var pages = PlacementLoopSupport.PageCount(bytes); + var footers = Shows(bytes).Where(s => s.StartsWith("pg", StringComparison.Ordinal)).ToArray(); + Assert.Equal(pages, footers.Length); + Assert.All(footers, f => Assert.EndsWith("of" + pages, f, StringComparison.Ordinal)); + Assert.Equal(Sha(Save(Build(twin: true))), Sha(bytes)); + } + + /// + /// The 207 of a list the rule turned into its twin names every cause the document read, and + /// only those: the renderer, alone or with the font, the element near the limit, or both. The + /// rows without a renderer of the caller's expect its cause to be absent. + /// + [Theory] + [InlineData("font", false, true, false)] + [InlineData("near", false, false, true)] + [InlineData("font, near", false, true, true)] + [InlineData("renderer", true, false, false)] + [InlineData("renderer, font", true, true, false)] + [InlineData("renderer, near", true, false, true)] + [InlineData("near, renderer, font", true, true, true)] + public void TheFallbackOfARenderer_namesEveryCauseTheDocumentRead( + string order, bool namesRenderer, bool namesFont, bool namesNear) + { + var doc = Page(footer: false); + doc.Add(new ListRenderer(Clamp())); + foreach (var cause in order.Split(", ")) + { + if (cause == "renderer") doc.Add(new Opaque()); + else if (cause == "font") doc.Add(Undrawable()); + else doc.Add(NearTheLimit()); + } + + doc.Add(new ListRenderer(Clamp())); + Save(doc); + + var first = Skipped(doc)[0]; + Assert.Equal(namesRenderer, first.Contains(RendererCause, StringComparison.Ordinal)); + Assert.Equal(namesFont, first.Contains("font it cannot draw", StringComparison.Ordinal)); + Assert.Equal(namesNear, first.Contains("element after a list", StringComparison.Ordinal)); + } + + /// + /// The causes named are the ones the scan of the elements read, so a font in a list that a + /// renderer of the caller's lays out is not named by the lists placed after it and not by the + /// ones before it: every list of the document says the same. + /// + [Fact] + public void AFontInAListARendererLaysOut_isNotNamedByAnyList() + { + var doc = Page(footer: false); + doc.Add(new ListRenderer(Clamp())); + doc.Add(new LaysOutFromDraw(new ListRenderer(Undrawable()))); + doc.Add(new ListRenderer(Clamp())); + Save(doc); + + var messages = Skipped(doc); + Assert.Equal(2, messages.Length); + Assert.Equal(messages[0], messages[1]); + Assert.Contains(RendererCause, messages[0], StringComparison.Ordinal); + Assert.DoesNotContain("font it cannot draw", messages[0], StringComparison.Ordinal); + } + + [Fact] + public void TheMessageOfAllThreeCauses_readsAsOneSentence() + { + var doc = Page(footer: false); + doc.Add(new ListRenderer(Clamp())); + doc.Add(Undrawable()); + doc.Add(NearTheLimit()); + doc.Add(new Opaque()); + Save(doc); + + Assert.StartsWith( + "The document holds a list entry in a font it cannot draw, an element after a list " + + "that can need about as many page continuations as one element may use and a renderer of " + + "yours, so this list was laid out as it was before", + Skipped(doc)[0], + StringComparison.Ordinal); + } + + /// + /// A document with no list has nothing to report, whatever renderer it holds. + /// + [Fact] + public void ADocumentWithoutAList_reportsNothingForARenderer() + { + var doc = Page(footer: false); + doc.Add(new Paragraph("text", H(10))); + doc.Add(new Opaque()); + + Save(doc); + + Assert.Empty(doc.Diagnostics); + } +} diff --git a/tests/VellumPdf.Layout.Tests/ListDocumentFontRuleTests.cs b/tests/VellumPdf.Layout.Tests/ListDocumentFontRuleTests.cs new file mode 100644 index 000000000..a76a7ba88 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/ListDocumentFontRuleTests.cs @@ -0,0 +1,1156 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Security.Cryptography; +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Rendering; + +namespace VellumPdf.Layout.Tests; + +/// +/// A document that holds an entry in a font it cannot draw (a handle another document returned, a +/// value the enumeration does not name) saves where that entry's text +/// falls where it does not fit and is dropped, and throws where the text is drawn. Clamping or +/// moving an entry ahead of it changes which, so every list of such a document is laid out as its +/// twin. The rows compare each document with the same document whose lists are replaced by their +/// twins, which is how the lists were laid out before the clamp and the moving of entries (#476, +/// #685). +/// +public sealed class ListDocumentFontRuleTests +{ + private static TextStyle H(double size) => new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = size }; + + private static readonly DateTimeOffset Stamp = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + + // How a list is placed. A visible list is one the document holds itself; the others are lists + // that a renderer of the caller's lays out, through the context, through WithArea and through + // the public constructor. + private const int Visible = -1; + + private static EmbeddedFontHandle ForeignHandle() => new Document().UseTrueTypeFont(FontReportSupport.DejaVuBytes); + + // A handle whose resource name is TT2, which a document that embedded one font does not define. + private static EmbeddedFontHandle SecondForeignHandle() + { + var other = new Document(); + other.UseTrueTypeFont(FontReportSupport.LiberationMonoBytes); + return other.UseTrueTypeFont(FontReportSupport.DejaVuBytes); + } + + // "ok" is a font the document draws, for the controls. + private static TextStyle Bad(string kind, double size) => new() + { + FontRef = kind switch + { + "foreign" => ForeignHandle(), + "ok" => new FontReference(Standard14.Helvetica), + _ => new FontReference((Standard14)99), + }, + FontSize = size, + }; + + private static Document Page(double width, double height, int leadLines, bool header) + { + var doc = new Document { PageSize = new PdfRectangle(0, 0, width, height), Margins = new EdgeInsets(10) }; + if (header) doc.Header = new RunningBand("H {page}/{pages}", H(8)); + for (var i = 0; i < leadLines; i++) doc.Add(new Paragraph("lead" + i, H(10)) { Margins = EdgeInsets.Zero }); + return doc; + } + + private static void Place(Document doc, ListElement list, int how, bool twin) + { + var renderer = new ListRenderer(list); + if (how == Visible) + { + if (twin) doc.Add(renderer.Unclamped()); + else doc.Add(list); + } + else + { + doc.Add(new Holder(twin ? renderer.Unclamped() : renderer, how)); + } + } + + // What a save gives, as one string: the SHA of the file, or the exception's type and message. + private static string Outcome(Document doc) + { + doc.Timestamp = Stamp; + doc.DocumentId = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray(); + try + { + using var ms = new MemoryStream(); + doc.Save(ms); + return "OK " + Convert.ToHexString(SHA256.HashData(ms.ToArray()))[..16]; + } + catch (Exception ex) + { + return "EX " + ex.GetType().Name + " " + ex.Message; + } + } + + private static string[] Shows(Document doc) + { + doc.Timestamp = Stamp; + doc.DocumentId = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray(); + using var ms = new MemoryStream(); + doc.Save(ms); + return Regex.Matches(PdfTestUtil.DecompressAllFlatStreams(ms.ToArray()), @"\(((?:\\.|[^\\)])*)\)\s*Tj") + .Select(m => m.Groups[1].Value).ToArray(); + } + + private static LayoutDiagnosticCode[] Codes(Document doc) => doc.Diagnostics.Select(d => d.Code).ToArray(); + + // ── The scenarios ──────────────────────────────────────────────────────── + + // An entry that moves whole to the next page, then one whose text fits where it falls on the + // first page and does not on the second, or the reverse. Page 200x100, margins 10. + private static Document ShiftedByAMove(string kind, int how, bool header, bool twin, bool badFirst) + { + var doc = Page(200, 100, 4, header); + var a = new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem("a", H(10))) + .Add(new ListItem([new TextRun("mover", H(20))]) { Style = H(10) }); + var b = new ListElement(ListStyle.Unordered) + .Add(new ListItem([new TextRun("bad", Bad(kind, 10))]) { Style = H(6) }); + if (badFirst) + { + Place(doc, b, how, twin); + Place(doc, a, Visible, twin); + } + else + { + Place(doc, a, Visible, twin); + Place(doc, b, how, twin); + } + + return doc; + } + + // A clamped nested child grows, pushing the entry after it down. Indent 100 on a 180 pt area. + private static Document ShiftedByAClamp(string kind, int how, bool header, bool twin, double child) + { + var doc = Page(200, 100, 0, header); + var parent = new ListItem("p", H(10)); + parent.AddChild(new ListItem([new TextRun("kid", H(child))]) { Style = H(10) }); + var a = new ListElement(ListStyle.OrderedDecimal) { Indent = 100 }.Add(parent); + var b = new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("bad", Bad(kind, 30))]) { Style = H(10) }); + Place(doc, a, Visible, twin); + Place(doc, b, how, twin); + return doc; + } + + // The list that holds the font comes first and drops its text at the bottom of page 1, so it + // saves. The list after it starts page 2 with an entry that moves where it is laid out the new + // way, so only a document that lays it out as its twin is the document 2.3.3 saved. + // The font sits in the text of the entry, in its marker, or in the text of a nested child. + private static Document BadListFirst(string kind, int how, bool header, bool twin, string where = "text") + { + var doc = Page(200, 100, where == "child" ? 5 : header ? 5 : 6, header); + var b = new ListElement(ListStyle.Unordered); + switch (where) + { + case "text": + b.Add(new ListItem([new TextRun("bad", Bad(kind, 10))]) { Style = H(5) }); + break; + case "marker": + // The marker is too tall for the room left and is dropped; the text fits. + b.Add(new ListItem([new TextRun("t", H(5))]) { Style = Bad(kind, 30) }); + break; + default: + var parent = new ListItem([new TextRun("p", H(10))]) { Style = H(10) }; + parent.AddChild(new ListItem([new TextRun("bad", Bad(kind, 10))]) { Style = H(5) }); + b.Add(parent); + break; + } + + var a = new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem("a", H(10))) + .Add(new ListItem([new TextRun("mover", H(header ? 50 : 60))]) { Style = H(10) }); + Place(doc, b, how, twin); + Place(doc, a, Visible, twin); + return doc; + } + + // The entry that holds the font follows the entry that moves in the same list. + private static Document SameListAfterAMove(string kind, bool header, bool twin) + { + var doc = Page(200, 100, 5, header); + var list = new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("dropped", H(20))]) { Style = H(10) }) + .Add(new ListItem([new TextRun("bad", Bad(kind, 10))]) { Style = H(6) }); + Place(doc, list, Visible, twin); + return doc; + } + + // ── The rule ───────────────────────────────────────────────────────────── + + /// + /// An entry that follows a moved entry in its own list, which the first version of the check + /// left on the new layout: main dropped its text at the page bottom and saved. + /// + [Theory] + [InlineData("undefined", false)] + [InlineData("undefined", true)] + [InlineData("foreign", false)] + [InlineData("foreign", true)] + public void AnUndrawableEntryAfterAMovedEntryInItsOwnList_keepsTheOutcomeItHad(string kind, bool header) + { + var twin = Outcome(SameListAfterAMove(kind, header, twin: true)); + var doc = SameListAfterAMove(kind, header, twin: false); + + Assert.Equal(twin, Outcome(doc)); + if (!header) + { + Assert.StartsWith("OK ", twin); + Assert.Equal(["lead0", "lead1", "lead2", "lead3", "lead4", "1.", "2."], Shows(SameListAfterAMove(kind, header, twin: false))); + } + } + + /// + /// The entry sits in another list, which the first list's moved entry shifts. The other list is + /// laid out as its twin would be, so nothing of it changes by itself. + /// + [Theory] + [InlineData("undefined", Visible, false)] + [InlineData("undefined", Visible, true)] + [InlineData("undefined", 0, false)] + [InlineData("undefined", 0, true)] + [InlineData("undefined", 1, false)] + [InlineData("undefined", 2, false)] + [InlineData("undefined", 2, true)] + [InlineData("undefined", 3, false)] + [InlineData("foreign", 3, false)] + [InlineData("foreign", Visible, false)] + [InlineData("foreign", 0, false)] + [InlineData("foreign", 0, true)] + [InlineData("foreign", 1, false)] + [InlineData("foreign", 2, false)] + [InlineData("undefined", 4, false)] + [InlineData("undefined", 4, true)] + [InlineData("undefined", 5, false)] + [InlineData("foreign", 4, false)] + [InlineData("foreign", 5, true)] + public void AnUndrawableListAfterAMovingList_keepsTheOutcomeItHad(string kind, int how, bool header) + { + var twin = Outcome(ShiftedByAMove(kind, how, header, twin: true, badFirst: false)); + + Assert.Equal(twin, Outcome(ShiftedByAMove(kind, how, header, twin: false, badFirst: false))); + } + + [Theory] + [InlineData("undefined", 0, false)] + [InlineData("undefined", 2, false)] + [InlineData("foreign", 1, false)] + [InlineData("foreign", 1, true)] + public void AnUndrawableListBeforeAMovingList_keepsTheOutcomeItHad(string kind, int how, bool header) + { + var twin = Outcome(ShiftedByAMove(kind, how, header, twin: true, badFirst: true)); + + Assert.Equal(twin, Outcome(ShiftedByAMove(kind, how, header, twin: false, badFirst: true))); + } + + /// The font is in the marker's style, or in a nested child. + [Theory] + [InlineData("marker", "undefined", Visible)] + [InlineData("marker", "foreign", 0)] + [InlineData("marker", "undefined", 3)] + [InlineData("child", "undefined", Visible)] + [InlineData("child", "foreign", 1)] + [InlineData("child", "undefined", 2)] + public void AnUndrawableMarkerOrChild_turnsTheListsAfterItIntoTheirTwins(string where, string kind, int how) + { + var twin = Outcome(BadListFirst(kind, how, header: false, twin: true, where)); + + Assert.StartsWith("OK ", twin); + Assert.Equal(twin, Outcome(BadListFirst(kind, how, header: false, twin: false, where))); + AssertControl(how, header: false, twin: false, ok => BadListFirst("ok", how, false, ok, where)); + } + + // The control, with a font the document draws. A list the document holds itself is laid out the + // new way and so is not its twin; a document that holds a renderer of the caller's lays every + // list out as its twin whatever the font, which is the rule these rows depend on. + private static void AssertControl(int how, bool header, bool twin, Func build) + { + var control = Outcome(build(false)); + if (how == Visible) Assert.NotEqual(Outcome(build(true)), control); + else Assert.Equal(Outcome(build(true)), control); + } + + /// + /// A document that holds a renderer of the caller's lays the list after it out as its twin, + /// whether or not the font in the held list can be drawn. Here the first list saves, with its + /// text dropped, so only the lists after it tell the two layouts apart. + /// + [Theory] + [InlineData("undefined", 0, false)] + [InlineData("undefined", 1, false)] + [InlineData("undefined", 2, true)] + [InlineData("undefined", 3, false)] + [InlineData("foreign", 0, false)] + [InlineData("foreign", 2, false)] + [InlineData("foreign", 3, false)] + [InlineData("foreign", 1, true)] + [InlineData("undefined", 4, false)] + [InlineData("foreign", 5, false)] + public void ARendererOfTheCallers_turnsTheListsAfterAHeldListIntoTheirTwins(string kind, int how, bool header) + { + var twin = Outcome(BadListFirst(kind, how, header, twin: true)); + + Assert.StartsWith("OK ", twin); + Assert.Equal(twin, Outcome(BadListFirst(kind, how, header, twin: false))); + AssertControl(how, header, twin: false, ok => BadListFirst("ok", how, header, ok)); + } + + /// + /// A clamp ahead of the entry pushes it down past the room its text needs. Main drew the text + /// and threw, and the document still throws. + /// + [Theory] + [InlineData("undefined", Visible, 50.0, false)] + [InlineData("undefined", Visible, 60.0, true)] + [InlineData("undefined", 0, 50.0, false)] + [InlineData("undefined", 1, 60.0, false)] + [InlineData("undefined", 2, 50.0, true)] + [InlineData("foreign", Visible, 50.0, false)] + [InlineData("foreign", 0, 60.0, false)] + [InlineData("foreign", 2, 50.0, false)] + public void AnUndrawableEntryAfterAClampedChild_keepsTheOutcomeItHad(string kind, int how, double child, bool header) + { + var twin = Outcome(ShiftedByAClamp(kind, how, header, twin: true, child)); + + Assert.StartsWith("EX ", twin); + Assert.Equal(twin, Outcome(ShiftedByAClamp(kind, how, header, twin: false, child))); + + // The clamp is what makes the entry's text not fit: with a font the document draws, the + // document saves, and not as the twin does. + Assert.StartsWith("OK ", Outcome(ShiftedByAClamp("ok", how, header, twin: false, child))); + } + + /// + /// The fixture holds the change: with a font the document draws and no renderer of the + /// caller's, the same documents are not their twins, so the rows above compare two layouts that + /// differ where the font allows it. With a renderer of the caller's holding the second list, + /// they are their twins, which is the rule that renderer brings. + /// + [Theory] + [InlineData(Visible, false)] + [InlineData(0, false)] + [InlineData(1, false)] + [InlineData(2, false)] + [InlineData(3, false)] + public void AControlWithAFontTheDocumentDraws_isItsTwinOnlyWhenARendererOfTheCallersIsHeld(int how, bool header) + { + AssertControl(how, header, twin: false, twin => ShiftedByAMove("ok", how, header, twin, badFirst: false)); + } + + [Fact] + public void AControlWithAFontTheDocumentDraws_isClampedAndMovedAfterAMovedEntry() + { + var doc = SameListAfterAMove("ok", header: false, twin: false); + + Assert.Equal(["lead0", "lead1", "lead2", "lead3", "lead4", "1.", "dropped", "2.", "bad"], Shows(doc)); + Assert.Empty(doc.Diagnostics); + } + + // ── What is reported ───────────────────────────────────────────────────── + + /// + /// Every list the document placed reports the fallback once, whether or not it holds the entry, + /// and a list a renderer of the caller's holds reports nothing, 208 included. + /// + [Fact] + public void EveryListTheDocumentPlaces_reportsTheFallbackOnce_andAHeldListReportsNothing() + { + var doc = ShiftedByAMove("undefined", 0, header: false, twin: false, badFirst: false); + + Outcome(doc); + + // The list the document holds reports 207 and the part of its entry that is dropped. + Assert.Equal( + [LayoutDiagnosticCode.ListIndentClampSkipped, LayoutDiagnosticCode.ListEntryPartDropped], + Codes(doc)); + Assert.All(doc.Diagnostics, d => Assert.Equal(LayoutElementKind.List, d.ElementKind)); + } + + [Fact] + public void BothVisibleLists_reportTheFallback() + { + var doc = ShiftedByAMove("foreign", Visible, header: false, twin: false, badFirst: false); + + Outcome(doc); + + Assert.Equal(2, doc.Diagnostics.Count(d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped)); + } + + /// + /// The count is the entries the clamp would have narrowed, from the same gutters the clamp + /// reads, and 1 when it would have narrowed none. + /// + [Fact] + public void TheFallbackCount_isTheEntriesTheClampWouldHaveNarrowed() + { + var doc = Page(200, 400, 0, header: false); + var clamped = new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 } + .Add(new ListItem("one", H(10))) + .Add(new ListItem("two", H(10))) + .Add(new ListItem([new TextRun("bad", Bad("undefined", 10))]) { Style = H(10) }); + doc.Add(clamped); + // Indent 100 leaves a child's gutter, 200, no room on the 180 pt area, and its parent some. + var parent = new ListItem("p", H(10)); + parent.AddChild(new ListItem("c1", H(10))); + parent.AddChild(new ListItem("c2", H(10))); + doc.Add(new ListElement(ListStyle.Unordered) { Indent = 100 }.Add(parent)); + var untouched = new ListElement(ListStyle.Unordered).Add(new ListItem("x", H(10))); + doc.Add(untouched); + + Outcome(doc); + + var skipped = doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped).ToArray(); + Assert.Equal(3, skipped.Length); + Assert.Equal(2, skipped[0].Count); + Assert.Equal(2, skipped[1].Count); + Assert.Equal(1, skipped[2].Count); + } + + /// A list with no items has nothing to report. + [Fact] + public void AnEmptyList_reportsNothingInADocumentThatHoldsTheFont() + { + var doc = Page(200, 100, 0, header: false); + doc.Add(new ListElement(ListStyle.Unordered)); + doc.Add(new ListElement(ListStyle.Unordered) { Indent = 1000 } + .Add(new ListItem([new TextRun("bad", Bad("undefined", 10))]))); + + Outcome(doc); + + Assert.Single(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped); + } + + /// + /// A twin used only because a caller's renderer holds the list reports nothing. A part of its + /// entry is dropped at the page bottom, as it was, and no diagnostic says so. + /// + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + public void AListACallersRendererHolds_reportsNoPartDropped(int how) + { + var doc = Page(200, 100, 5, header: false); + var list = new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("dropped", H(20))]) { Style = H(10) }); + doc.Add(new Holder(new ListRenderer(list), how)); + + var outcome = Outcome(doc); + + Assert.StartsWith("OK ", outcome); + Assert.Empty(doc.Diagnostics); + } + + /// The same list, added to the document itself, is reported as before. + [Fact] + public void AListTheDocumentPlacesAsItsTwin_stillReportsThePartDropped() + { + var doc = Page(200, 100, 5, header: false); + doc.Add(new ListRenderer(new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("dropped", H(20))]) { Style = H(10) })).Unclamped()); + + Outcome(doc); + + Assert.Equal([LayoutDiagnosticCode.ListEntryPartDropped], Codes(doc)); + } + + // ── The passes ────────────────────────────────────────────────────────────────────── + + private static (DocumentRenderer Renderer, byte[] Bytes) Render( + Action add, bool header = false, PdfDocument? pdf = null) + { + pdf ??= new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, 100), new EdgeInsets(10)); + if (header) renderer.Header = new RunningBand("H {page}/{pages}", H(8)); + add(renderer); + using var ms = new MemoryStream(); + renderer.Render(ms); + return (renderer, ms.ToArray()); + } + + // The indent leaves the text no width where it is asked for, so a font the document cannot + // draw is held and its text is never drawn, which is what lets the document save. + private static ListElement OneEntry(string text, TextStyle style, double indent = 20) => + new ListElement(ListStyle.Unordered) { Indent = indent } + .Add(new ListItem([new TextRun(text, style)]) { Style = H(10) }); + + /// + /// A list ahead of a renderer of the caller's is laid out once, in the pass that draws, as the + /// renderer is: the document decides before any pass whether the lists are their twins, so no + /// pass lays out to find out. It still reports that it measured nothing, as one with no header + /// or dependent does. + /// + [Fact] + public void AListAheadOfACallersRenderer_isLaidOutOncePerPass() + { + var (renderer, _) = Render(r => + { + r.Add(new ListRenderer(OneEntry("a", H(10)))); + r.Add(new Holder(new ListRenderer(OneEntry("b", H(10))), 0)); + }); + + Assert.Equal(0, renderer.MeasureRuns); + Assert.Null(renderer.MeasurePlan); + Assert.Equal(2, renderer.LayoutCalls); + } + + [Fact] + public void ADocumentWithOnlyBuiltInRenderers_isLaidOutOncePerPass() + { + var (renderer, _) = Render(r => + { + r.Add(new ListRenderer(OneEntry("a", H(10)))); + r.Add(new ParagraphRenderer(new Paragraph("x", H(10)))); + }); + + Assert.Equal(2, renderer.LayoutCalls); + } + + [Fact] + public void ACallersRendererAheadOfTheLists_isLaidOutOncePerPass() + { + var (renderer, _) = Render(r => + { + r.Add(new Holder(new ListRenderer(OneEntry("b", H(10))), 0)); + r.Add(new ListRenderer(OneEntry("a", H(10)))); + }); + + Assert.Equal(2, renderer.LayoutCalls); + } + + /// + /// A document that holds a renderer of the caller's lays its lists out as their twins from the + /// first pass. A list laid out the new way measures text that 2.3.3 never measured, here the + /// space between two words that the clamp gives a width, which adds a glyph to the subset of an + /// embedded font, so the saved file would differ from the one 2.3.3 wrote. The document + /// compared here holds the renderer, so it is that file. + /// + [Fact] + public void ADocumentThatHoldsACallersRenderer_addsNoGlyphToAFontSubset() + { + Document Build(bool twin) + { + var doc = Page(200, 400, 0, header: false); + var own = doc.UseTrueTypeFont(FontReportSupport.DejaVuBytes); + var ahead = new ListElement(ListStyle.Unordered) { Indent = 1000 } + .Add(new ListItem([new TextRun("ab cd", new TextStyle { FontRef = own, FontSize = 10 })]) { Style = H(10) }); + Place(doc, ahead, Visible, twin); + Place(doc, OneEntry("b", Bad("undefined", 10), 1000), 0, twin); + return doc; + } + + Assert.Equal(Outcome(Build(twin: true)), Outcome(Build(twin: false))); + } + + /// + /// A list builds its entries once for each layout, however many pages it spans: the pieces of + /// a list that starts over carry the generation, and do not build the entries again for each + /// page. Two builds are two lists in the one layout that draws. + /// + [Fact] + public void AListThatSpansManyPages_buildsItsEntriesOncePerLayout() + { + var many = new ListElement(ListStyle.OrderedDecimal); + for (var i = 0; i < 200; i++) many.Add(new ListItem("w", H(10))); + var doc = Page(200, 40, 0, header: false); + doc.Add(many); + doc.Add(new Holder(new ListRenderer(OneEntry("b", H(10))), 0)); + ListRenderer.BuildCalls = 0; + + Assert.StartsWith("OK ", Outcome(doc)); + + Assert.Equal(2, ListRenderer.BuildCalls); + } + + /// + /// A header's page-counting pass is the one the document reports, whether or not a list holds + /// the font. + /// + [Theory] + [InlineData(false, 1)] + [InlineData(true, 1)] + public void AHeaderMeasure_runsOnceWhetherOrNotAListHoldsTheFont(bool bad, int measureRuns) + { + var (renderer, _) = Render( + r => + { + r.Add(new ListRenderer(OneEntry("a", H(10)))); + r.Add(new Holder(new ListRenderer(OneEntry("b", bad ? Bad("undefined", 10) : H(10), 1000)), 0)); + }, + header: true); + + Assert.Equal(measureRuns, renderer.MeasureRuns); + } + + /// + /// A list ahead of a held list leaves nothing behind. A paragraph keeps where its last layout + /// placed it, and a list's Draw reads that when its own layout answers Nothing, so a held list + /// whose entry text was placed on a page where it fits, and the drawing layout drops, would + /// show the text. The reference has five paragraphs as tall as the entries of the list ahead + /// of it; what the held list shows is the same. + /// + [Theory] + [InlineData(0)] + [InlineData(2)] + public void AListAheadOfAHeldList_doesNotChangeWhatTheHeldListShows(int how) + { + Document Build(bool listAhead) + { + var doc = new Document { PageSize = new PdfRectangle(0, 0, 100, 150), Margins = EdgeInsets.Zero }; + if (listAhead) + { + var ahead = new ListElement(ListStyle.Unordered); + for (var i = 0; i < 5; i++) ahead.Add(new ListItem("a", H(10))); + doc.Add(ahead); + } + else + { + for (var i = 0; i < 5; i++) doc.Add(new Paragraph("a", H(10)) { Margins = EdgeInsets.Zero }); + } + + var held = new ListElement(ListStyle.OrderedDecimal); + for (var i = 0; i < 3; i++) + { + held.Add(new ListItem([new TextRun("wd wd wd wd wd wd", H(14))]) { Style = H(20) }); + } + + doc.Add(new Holder(new ListRenderer(held), how)); + return doc; + } + + var withList = Shows(Build(listAhead: true)); + var reference = Shows(Build(listAhead: false)); + + // Each entry of the list ahead shows its marker and text; each paragraph shows its text. + Assert.Equal(reference.Skip(5).ToArray(), withList.Skip(10).ToArray()); + Assert.Contains("1.", withList.Skip(10)); + } + + /// + /// A document whose text depends on the plan measures until it settles, in two passes here, + /// whether or not a list holds the font. + /// + [Theory] + [InlineData(false, 2)] + [InlineData(true, 2)] + public void ADependentThatSettles_isMeasuredTwice_whetherOrNotAListHoldsTheFont(bool bad, int measureRuns) + { + var (renderer, _) = Render(r => + { + r.Add(new ListRenderer(OneEntry("a", H(10)))); + r.Add(new Holder(new ListRenderer(OneEntry("b", bad ? Bad("undefined", 10) : H(10), 1000)), 0)); + r.Add(new Settled()); + }); + + Assert.Equal(measureRuns, renderer.MeasureRuns); + } + + /// + /// The run belongs to the layout in progress. A layout started from inside a renderer of the + /// caller's has a run of its own, and the outer one is as it was afterwards. + /// + [Fact] + public void ALayoutInsideALayout_leavesTheOuterRunAsItWas() + { + Assert.Null(ListLayoutRun.Current); + var inner = new Document(); + inner.Add(OneEntry("bad", Bad("undefined", 10))); + var seen = new Capture(); + inner.Add(seen); + var probe = new RunProbe(inner); + var (renderer, _) = Render(r => + { + r.Add(new ListRenderer(OneEntry("a", H(10)))); + r.Add(probe); + }); + + Assert.NotNull(probe.Outer); + Assert.Same(probe.Outer, probe.AfterInner); + Assert.NotNull(seen.Run); + Assert.NotSame(probe.Outer, seen.Run); + Assert.False(probe.Outer.FoundUndrawable); + Assert.True(seen.Run.FoundUndrawable); + Assert.Null(ListLayoutRun.Current); + Assert.Equal(0, renderer.MeasureRuns); + } + + [Fact] + public void TheRun_isGoneAfterALayoutThatThrows() + { + var pdf = new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, 100), new EdgeInsets(10)); + renderer.Add(new Throws()); + + using var ms = new MemoryStream(); + Assert.Throws(() => renderer.Render(ms)); + + Assert.Null(ListLayoutRun.Current); + } + + /// + /// The run flows with the execution context: a list laid out through a task or on a thread + /// started from the layout sees it. The rows with modes 4 and 5 above compare the outcomes. + /// This one reads the run where those lists are laid out. + /// + [Fact] + public void TheRun_isSeenOnAPoolThreadAndOnANewThread() + { + var seenOnPool = new Capture(); + var seenOnThread = new Capture(); + var (renderer, _) = Render(r => + { + r.Add(new ListRenderer(OneEntry("a", H(10)))); + r.Add(new Holder(seenOnPool, 4)); + r.Add(new Holder(seenOnThread, 5)); + }); + + Assert.NotNull(seenOnPool.Run); + Assert.NotNull(seenOnThread.Run); + Assert.Same(seenOnPool.Run, seenOnThread.Run); + Assert.Equal(0, renderer.MeasureRuns); + Assert.Null(ListLayoutRun.Current); + } + + /// + /// Work queued with the execution context suppressed does not see the run, so a list laid out + /// there reads none. The document's decision does not depend on it: it is taken from the + /// elements added, before anything is laid out. + /// + [Fact] + public void WorkQueuedWithoutTheExecutionContext_doesNotSeeTheRun() + { + var seen = new Capture(); + var queued = new QueuedWithoutContext(seen); + + Render(r => + { + r.Add(new ListRenderer(OneEntry("a", H(10)))); + r.Add(queued); + }); + + Assert.True(queued.Ran); + Assert.Null(seen.Run); + } + + /// + /// Saves that run side by side, each on its own thread, keep the run of their own layout: + /// every outcome is the one the same document gives alone, and no run is left behind. + /// + [Fact] + public void SavesThatRunInParallel_eachKeepTheirOwnRun() + { + Document Build(int i) => ShiftedByAMove(i % 2 == 0 ? "undefined" : "ok", Visible, header: i % 3 == 0, twin: false, badFirst: false); + var expected = Enumerable.Range(0, 12).Select(i => Outcome(Build(i))).ToArray(); + Assert.Contains(expected, o => o.StartsWith("EX ", StringComparison.Ordinal) || o.StartsWith("OK ", StringComparison.Ordinal)); + + var actual = new string[expected.Length * 8]; + Parallel.For(0, actual.Length, new ParallelOptions { MaxDegreeOfParallelism = 4 }, + k => actual[k] = Outcome(Build(k % expected.Length))); + + for (var k = 0; k < actual.Length; k++) Assert.Equal(expected[k % expected.Length], actual[k]); + Assert.Null(ListLayoutRun.Current); + } + + /// + /// The run is set in the task SaveAsync starts, and none is left on the caller. + /// + [Fact] + public async Task SaveAsync_givesTheOutcomeSaveGives() + { + var expected = Outcome(ShiftedByAMove("undefined", 4, header: false, twin: false, badFirst: false)); + var doc = ShiftedByAMove("undefined", 4, header: false, twin: false, badFirst: false); + doc.Timestamp = Stamp; + doc.DocumentId = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray(); + using var ms = new MemoryStream(); + + await doc.SaveAsync(ms, TestContext.Current.CancellationToken); + + Assert.Equal(expected, "OK " + Convert.ToHexString(SHA256.HashData(ms.ToArray()))[..16]); + Assert.Null(ListLayoutRun.Current); + } + + // ── What the document is asked about ───────────────────────────────────── + + private static bool Holds(ListElement list, PdfDocument? pdf = null) + { + var run = ListLayoutRun.Begin(pdf ?? new PdfDocument(), out var previous); + try + { + return ListRenderer.HoldsUndrawableEntry(list, run); + } + finally + { + ListLayoutRun.End(previous); + } + } + + [Fact] + public void ARunInTheMarkersStyle_isRead() + { + var list = new ListElement(ListStyle.Unordered) + .Add(new ListItem([new TextRun("ok", H(10))]) { Style = Bad("undefined", 10) }); + + Assert.True(Holds(list)); + } + + [Fact] + public void ACharacterlessRun_isNotRead() + { + var list = new ListElement(ListStyle.Unordered) + .Add(new ListItem([new TextRun("", Bad("undefined", 10)), new TextRun("ok", H(10))]) { Style = H(10) }); + + Assert.False(Holds(list)); + } + + [Fact] + public void AnItemBuiltFromAString_isReadInTheStyleItInherits() + { + var inherits = new ListElement(ListStyle.Unordered) { DefaultStyle = Bad("undefined", 10) } + .Add(new ListItem("text")); + var own = new ListElement(ListStyle.Unordered) { DefaultStyle = Bad("undefined", 10) } + .Add(new ListItem("text", H(10))); + + Assert.True(Holds(inherits)); + Assert.False(Holds(own)); + } + + [Fact] + public void AChildsRuns_areRead_andAChildInheritsItsParentsStyle() + { + var run = new ListItem("p", H(10)); + run.AddChild(new ListItem([new TextRun("c", Bad("undefined", 10))])); + var inherited = new ListItem("p", Bad("undefined", 10)); + inherited.AddChild(new ListItem("c")); + var fine = new ListItem("p", H(10)); + fine.AddChild(new ListItem("c")); + + Assert.True(Holds(new ListElement(ListStyle.Unordered).Add(run))); + Assert.True(Holds(new ListElement(ListStyle.Unordered).Add(inherited))); + Assert.False(Holds(new ListElement(ListStyle.Unordered).Add(fine))); + } + + [Fact] + public void AHandleTheDocumentDefines_isDrawable_andOneItDoesNot_isNot() + { + var pdf = new PdfDocument(); + var own = pdf.UseTrueTypeFont(FontReportSupport.DejaVuBytes); + + Assert.False(Holds(OneEntry("x", new TextStyle { FontRef = own, FontSize = 10 }), pdf)); + Assert.True(Holds(OneEntry("x", new TextStyle { FontRef = ForeignHandle() }), new PdfDocument())); + } + + /// + /// With no document to ask, an embedded font cannot be said to be defined, and a Standard 14 + /// value is read from the enumeration. + /// + [Fact] + public void WithNoRun_anEmbeddedFontIsNotDrawable_andAStandard14ValueIsRead() + { + Assert.False(ListLayoutRun.CanDraw(null, new TextStyle { FontRef = ForeignHandle() })); + Assert.False(ListLayoutRun.CanDraw(null, new TextStyle { FontRef = (Standard14)99 })); + Assert.True(ListLayoutRun.CanDraw(null, H(10))); + } + + /// + /// A font is asked about once however many runs use it, and asking about the next font gives + /// that font's own answer, so the memo never answers for the wrong one. + /// + [Fact] + public void TheMemoOfTheLastFont_neverAnswersForAnother() + { + var pdf = new PdfDocument(); + var own = pdf.UseTrueTypeFont(FontReportSupport.LiberationMonoBytes); + var foreign = SecondForeignHandle(); + var run = ListLayoutRun.Begin(pdf, out var previous); + try + { + var styles = new[] + { + new TextStyle { FontRef = own }, + new TextStyle { FontRef = own }, + new TextStyle { FontRef = foreign }, + new TextStyle { FontRef = foreign }, + new TextStyle { FontRef = own }, + H(10), + new TextStyle { FontRef = (Standard14)99 }, + new TextStyle { FontRef = (Standard14)99 }, + H(10), + }; + + Assert.Equal( + [true, true, false, false, true, true, false, false, true], + styles.Select(s => ListLayoutRun.CanDraw(run, s)).ToArray()); + } + finally + { + ListLayoutRun.End(previous); + } + } + + /// + /// Threads that ask about two Standard 14 values at once each get their own value's answer. The + /// memo holds one value and its answer as a unit, so no thread reads one value with the + /// other's answer. A race needs the threads to interleave a write, so the loop cannot force + /// it; it fails on a memo that pairs a value with another's answer only when that happens. + /// + [Fact] + public void TheMemoOfTheLastStandard14Value_answersEachThreadForItsOwnValue() + { + var run = ListLayoutRun.Begin(new PdfDocument(), out var previous); + try + { + var defined = H(10); + var undefined = new TextStyle { FontRef = (Standard14)99 }; + var wrong = 0; + + Parallel.For(0, 4, new ParallelOptions { MaxDegreeOfParallelism = 4 }, worker => + { + for (var i = 0; i < 200_000; i++) + { + var useDefined = ((i + worker) & 1) == 0; + if (ListLayoutRun.CanDraw(run, useDefined ? defined : undefined) != useDefined) + Interlocked.Increment(ref wrong); + } + }); + + Assert.Equal(0, wrong); + } + finally + { + ListLayoutRun.End(previous); + } + } + + /// + /// A document that holds an entry it cannot draw lays every list out as its twin, and a + /// caller's renderer after the list adds nothing to that. The two layouts are one for each + /// renderer. + /// + [Fact] + public void AnUndrawableEntryAheadOfACallersRenderer_isLaidOutOncePerPass() + { + var (renderer, _) = Render(r => + { + r.Add(new ListRenderer(OneEntry("a", Bad("undefined", 10), indent: 1000))); + r.Add(new Holder(new ListRenderer(OneEntry("b", H(10))), 0)); + }); + + Assert.Equal(2, renderer.LayoutCalls); + } + + /// + /// Runs that alternate between two embedded fonts ask the document once for each font, not once + /// for each change of font, and a font the document cannot draw is asked about again. + /// + [Fact] + public void RunsThatAlternateTwoFonts_askTheDocumentOncePerFont() + { + var pdf = new PdfDocument(); + var mono = pdf.UseTrueTypeFont(FontReportSupport.LiberationMonoBytes); + var sans = pdf.UseTrueTypeFont(FontReportSupport.DejaVuBytes); + var run = ListLayoutRun.Begin(pdf, out var previous); + try + { + for (var i = 0; i < 50; i++) + { + Assert.True(ListLayoutRun.CanDraw(run, new TextStyle { FontRef = mono })); + Assert.True(ListLayoutRun.CanDraw(run, new TextStyle { FontRef = sans })); + } + + Assert.Equal(2, run.DocumentQuestions); + + // A font the document cannot draw is asked about each time: a renderer of a caller's + // may embed it while the layout runs, which turns the answer. + var empty = ListLayoutRun.Begin(new PdfDocument(), out var outer); + try + { + var foreign = new TextStyle { FontRef = ForeignHandle() }; + Assert.False(ListLayoutRun.CanDraw(empty, foreign)); + Assert.False(ListLayoutRun.CanDraw(empty, foreign)); + Assert.Equal(2, empty.DocumentQuestions); + } + finally + { + ListLayoutRun.End(outer); + } + } + finally + { + ListLayoutRun.End(previous); + } + } + + // ── Helpers ────────────────────────────────────────────────────────────── + + /// + /// A renderer of a caller's that lays a list out through the context it was given, through + /// or through the public constructor. + /// + private sealed class Holder(IRenderer inner, int how) : IRenderer + { + public LayoutResult Layout(LayoutContext context) + { + // Modes 4 and 5 lay the list out on a pool thread and on a thread of its own, through + // the context, while this thread waits. + if (how == 4) return Task.Run(() => inner.Layout(context)).GetAwaiter().GetResult(); + if (how == 5) return OnNewThread(() => inner.Layout(context)); + + // Mode 3 measures the list at a narrower width first and lays it out through the + // context afterwards, so the list sees two calls in a row at two widths. + if (how == 3) + { + var area = context.Area; + inner.Layout(context.WithArea(new LayoutBox(area.X, area.Y, area.Width * 0.75, area.Height))); + return inner.Layout(context); + } + + return inner.Layout(how switch + { + 0 => context, + 1 => context.WithArea(context.Area), + _ => new LayoutContext(context.Area, context.ContentTop), + }); + } + + public void Draw(DrawContext ctx) => inner.Draw(ctx); + + private static LayoutResult OnNewThread(Func layout) + { + LayoutResult result = default!; + Exception? error = null; + var thread = new Thread(() => + { + try + { + result = layout(); + } + catch (Exception ex) + { + error = ex; + } + }); + thread.Start(); + thread.Join(); + if (error is not null) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(error).Throw(); + return result; + } + } + + /// A renderer whose text depends on the plan and never changes. + private sealed class Settled : IRenderer, IPlanDependent + { + public string TargetName => "settled"; + + public string ResolvedText => "x"; + + public bool Resolve(PaginationPlan plan) => false; + + public LayoutResult Layout(LayoutContext context) => + LayoutResult.Full(new LayoutBox(context.Area.X, context.Area.Y, 10, 10)); + + public void Draw(DrawContext ctx) + { + } + } + + private sealed class Throws : IRenderer + { + private int _calls; + + public LayoutResult Layout(LayoutContext context) => + throw new InvalidOperationException("layout " + ++_calls); + + public void Draw(DrawContext ctx) + { + } + } + + /// Runs its work on a pool thread the execution context does not flow to. + private sealed class QueuedWithoutContext(Capture inner) : IRenderer + { + public bool Ran { get; private set; } + + public LayoutResult Layout(LayoutContext context) + { + using var done = new ManualResetEventSlim(); + LayoutResult result = default!; + ThreadPool.UnsafeQueueUserWorkItem( + _ => + { + result = inner.Layout(context); + Ran = true; + done.Set(); + }, + null); + done.Wait(); + return result; + } + + public void Draw(DrawContext ctx) + { + } + } + + /// Notes the run it is laid out under. + private sealed class Capture : IRenderer + { + public ListLayoutRun? Run { get; private set; } + + public LayoutResult Layout(LayoutContext context) + { + Run = ListLayoutRun.Current; + return LayoutResult.Full(new LayoutBox(context.Area.X, context.Area.Y, 1, 1)); + } + + public void Draw(DrawContext ctx) + { + } + } + + /// Saves another document from inside its layout and notes the run. + private sealed class RunProbe(Document inner) : IRenderer + { + private bool _done; + + public ListLayoutRun? Outer { get; private set; } + + public ListLayoutRun? AfterInner { get; private set; } + + public LayoutResult Layout(LayoutContext context) + { + if (!_done) + { + _done = true; + Outer = ListLayoutRun.Current; + using var ms = new MemoryStream(); + try + { + inner.Save(ms); + } + catch (IndexOutOfRangeException) + { + // The font is the point of the document, not a failure of the test. + } + + AfterInner = ListLayoutRun.Current; + } + + return LayoutResult.Full(new LayoutBox(context.Area.X, context.Area.Y, 10, 10)); + } + + public void Draw(DrawContext ctx) + { + } + } +} diff --git a/tests/VellumPdf.Layout.Tests/ListDocumentLimitPreformattedTests.cs b/tests/VellumPdf.Layout.Tests/ListDocumentLimitPreformattedTests.cs new file mode 100644 index 000000000..5c1f593c9 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/ListDocumentLimitPreformattedTests.cs @@ -0,0 +1,175 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Security.Cryptography; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Rendering; + +namespace VellumPdf.Layout.Tests; + +/// +/// Preformatted text rewrites its text before it wraps: a tab becomes up to TabWidth +/// spaces, and the wrap then cuts an expanded line after at least one cluster. So a line of such +/// text does not hold a character of the original, and the count of an element near the limit +/// (ListDocumentLimitRuleTests) must read a tab as the columns it can become. The limit is small +/// here so a document reaches it in a blink. +/// +public sealed class ListDocumentLimitPreformattedTests +{ + private const int Limit = 60; + + private static readonly DateTimeOffset Stamp = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + + private static TextStyle H(double size) => new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = size }; + + private static TextStyle Courier(double size) => new() { FontRef = new FontReference(Standard14.Courier), FontSize = size }; + + // What a save gives, as one string: the SHA of the file, or the exception's type and message. + private static string Save(Action add, double pageHeight = 80) + { + var pdf = new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, pageHeight), new EdgeInsets(10)) + { + ContinuationLimit = Limit, + }; + add(renderer); + try + { + using var ms = new MemoryStream(); + renderer.Render(ms); + return "OK " + Convert.ToHexString(SHA256.HashData(ms.ToArray()))[..16]; + } + catch (Exception ex) + { + return "EX " + ex.GetType().Name + " " + ex.Message; + } + } + + private static ListElement Mover(double size) => new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem("a", H(10))) + .Add(new ListItem([new TextRun("mover", H(size))]) { Style = H(10) }); + + private static Paragraph Lead() => new("lead", H(10)) { Margins = EdgeInsets.Zero }; + + // Tabs alone: a tab at a stop moves a full TabWidth, so each one becomes 32 columns, which a + // Courier line 180 points wide wraps into two or three lines of its own. + private static Preformatted Tabs(int count) => + new(new string('\t', count) + "\n\n", Courier(20)) { TabWidth = 32, Margins = EdgeInsets.Zero }; + + private static string Shifted(int tabs, int leads, double mover, bool twin) => Save(r => + { + for (var i = 0; i < leads; i++) r.Add(new ParagraphRenderer(Lead())); + var list = new ListRenderer(Mover(mover)); + r.Add(twin ? list.Unclamped() : list); + r.Add(new PreformattedRenderer(Tabs(tabs))); + }); + + /// + /// Preformatted text of tabs reaches the limit with far fewer characters than the limit, and + /// starts lower when a list before it moves an entry, so the limit's verdict on it flips: one + /// lead line and a moved entry, or two lead lines and a taller one. The document is the twin's + /// whichever way it would flip. The element's characters, counted one each, are within the + /// limit where it is refused. + /// + [Theory] + [InlineData(1, 40.0)] + [InlineData(2, 30.0)] + public void PreformattedTabsNearTheLimit_getTheVerdictTheyHadWhenAListMovesAnEntry(int leads, double mover) + { + // The first count of tabs the twin refuses, which is where the limit falls. + var edge = 1; + while (edge < Limit && Shifted(edge, leads, mover, twin: true).StartsWith("OK", StringComparison.Ordinal)) edge++; + + // Two plus the characters is the count that stopped holding the lists back: the tabs and + // the two line ends. + Assert.InRange(edge + 4, 1, Limit); + + for (var tabs = edge - 12; tabs <= edge + 12; tabs++) + Assert.Equal(Shifted(tabs, leads, mover, twin: true), Shifted(tabs, leads, mover, twin: false)); + } + + /// + /// The fixture's list does move an entry: with preformatted text too short to come near the + /// limit, the document is not the twin's. + /// + [Theory] + [InlineData(1, 40.0)] + [InlineData(2, 30.0)] + public void AControlWithAShortPreformattedText_isLaidOutNewAndMovesTheEntry(int leads, double mover) + { + var twin = Shifted(1, leads, mover, twin: true); + + Assert.StartsWith("OK ", twin); + Assert.NotEqual(twin, Shifted(1, leads, mover, twin: false)); + } + + /// + /// The bound counts a tab as its width and every other character as one, with line ends and + /// the two for the retry and the piece that ends. + /// + [Theory] + [InlineData(1, 2 + 8 + 3 * 0)] + [InlineData(8, 2 + 8 + 3 * 7)] + [InlineData(32, 2 + 8 + 3 * 31)] + public void TheBoundOfPreformattedText_countsATabAsItsWidth(int tabWidth, long expected) + { + var renderer = new PreformattedRenderer(new Preformatted("a\tb\t\tc\r\n", Courier(10)) { TabWidth = tabWidth }); + var document = new DocumentRenderer(new PdfDocument(), new PdfRectangle(0, 0, 200, 80), new EdgeInsets(10)); + + Assert.Equal(expected, document.ContinuationBoundOf(renderer)); + } + + /// + /// For random preformatted text at narrow widths, with tabs, line ends of the three kinds, + /// combining marks and wide letters, a document whose limit is the bound is never refused for + /// the limit: the bound is never below the continuations taken. + /// + [Fact] + public void TheBoundOfPreformattedText_isNeverBelowTheContinuationsTaken() + { + string[] pieces = ["\t", "\t", "\t", "a", "b", "W", " ", "\n", "\r", "\r\n", "́", "é", "中"]; + var rng = new Random(20260901); + var taken = 0; + for (var seed = 0; seed < 400; seed++) + { + var text = string.Concat(Enumerable.Range(0, rng.Next(0, 60)).Select(_ => pieces[rng.Next(pieces.Length)])); + var element = new Preformatted(text, Courier(8 + rng.Next(13))) + { + TabWidth = 1 + rng.Next(32), + Margins = EdgeInsets.Zero, + }; + var width = 30 + rng.Next(90); + var height = 30 + rng.Next(70); + + var probe = new DocumentRenderer(new PdfDocument(), new PdfRectangle(0, 0, width, height), new EdgeInsets(10)); + var bound = probe.ContinuationBoundOf(new PreformattedRenderer(element)); + + var pdf = new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var document = new DocumentRenderer(pdf, new PdfRectangle(0, 0, width, height), new EdgeInsets(10)) + { + ContinuationLimit = (int)bound, + }; + document.Add(new PreformattedRenderer(element)); + try + { + using var ms = new MemoryStream(); + document.Render(ms); + taken += pdf.Pages.Count; + } + catch (InvalidOperationException ex) when (ex.Message.Contains("page continuations", StringComparison.Ordinal)) + { + Assert.Fail($"seed {seed}: limit {bound} reached by {text.Length} characters, tab width {element.TabWidth}, page {width}x{height}"); + } + catch (InvalidOperationException) + { + // Too small a page for one line: a refusal that is not the limit. + } + } + + // The sample reaches many pages, so the property is not met by documents of one page. + Assert.True(taken > 400, $"only {taken} pages across the sample"); + } +} diff --git a/tests/VellumPdf.Layout.Tests/ListDocumentLimitRuleTests.cs b/tests/VellumPdf.Layout.Tests/ListDocumentLimitRuleTests.cs new file mode 100644 index 000000000..0dc9b6ac6 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/ListDocumentLimitRuleTests.cs @@ -0,0 +1,301 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Security.Cryptography; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Elements.Table; +using VellumPdf.Layout.Rendering; +using VellumPdf.Layout.Rendering.Table; + +namespace VellumPdf.Layout.Tests; + +/// +/// A moved entry (#685) changes where the element after its list starts, and an element that needs +/// about as many continuations as the limit allows saves or is refused according to where it +/// starts. A document with such an element after a list keeps every list as its twin, which is how +/// the lists were laid out before the clamp and the moving of entries, so the element starts where +/// it started then. The limit is small here so a document reaches it in a blink. +/// +public sealed class ListDocumentLimitRuleTests +{ + private const int Limit = 60; + + private static readonly DateTimeOffset Stamp = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + + private static TextStyle H(double size) => new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = size }; + + // What a save gives, as one string: the SHA of the file, or the exception's type and message. + private static string Save(Action add, double pageHeight = 80, int limit = Limit) + { + var pdf = new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, pageHeight), new EdgeInsets(10)) + { + ContinuationLimit = limit, + }; + add(renderer); + try + { + using var ms = new MemoryStream(); + renderer.Render(ms); + return "OK " + Convert.ToHexString(SHA256.HashData(ms.ToArray()))[..16]; + } + catch (Exception ex) + { + return "EX " + ex.GetType().Name + " " + ex.Message; + } + } + + private static IRenderer ListOf(ListElement list, bool twin) => + twin ? new ListRenderer(list).Unclamped() : new ListRenderer(list); + + // An entry of 40 points does not fit the 20 points left under the first entry on a page of 60 + // after the lead, so the entry moves whole to the next page, which the twin does not do. + private static ListElement Mover(double size) => new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem("a", H(10))) + .Add(new ListItem([new TextRun("mover", H(size))]) { Style = H(10) }); + + private static Paragraph Lead() => new("lead", H(10)) { Margins = EdgeInsets.Zero }; + + // One word to a line at 20 points, so n words are n lines. + private static Paragraph Words(int n) => + new(string.Join(" ", Enumerable.Repeat("WWWWW", n)), H(20)) { Margins = EdgeInsets.Zero }; + + private static string Shifted(int words, int leads, double mover, bool twin) => Save(r => + { + for (var i = 0; i < leads; i++) r.Add(new ParagraphRenderer(Lead())); + r.Add(ListOf(Mover(mover), twin)); + r.Add(new ParagraphRenderer(Words(words))); + }); + + /// + /// A paragraph that needs about as many continuations as the limit allows starts lower when a + /// list before it moves an entry, and the limit's verdict on it flips: one lead line and the + /// moved entry saves where the twin is refused, and two lead lines and a taller entry is + /// refused where the twin saves. The document is the twin's whichever way it would flip. + /// + [Theory] + [InlineData(1, 40.0)] + [InlineData(2, 30.0)] + public void ALaterElementNearTheLimit_getsTheVerdictItHadWhenAListMovesAnEntry(int leads, double mover) + { + // The first length the twin refuses, which is where the limit falls for the paragraph. + var edge = 1; + while (edge < 40 * Limit && Shifted(edge, leads, mover, twin: true).StartsWith("OK", StringComparison.Ordinal)) edge++; + Assert.InRange(edge, Limit / 2, 39 * Limit); + + for (var words = edge - 12; words <= edge + 12; words++) + Assert.Equal(Shifted(words, leads, mover, twin: true), Shifted(words, leads, mover, twin: false)); + } + + /// + /// The fixture's list does move an entry: with a paragraph too short to come near the limit, + /// the document is not the twin's. + /// + [Theory] + [InlineData(1, 40.0)] + [InlineData(2, 30.0)] + public void AControlWithAShortParagraph_isLaidOutNewAndMovesTheEntry(int leads, double mover) + { + var twin = Shifted(2, leads, mover, twin: true); + + Assert.StartsWith("OK ", twin); + Assert.NotEqual(twin, Shifted(2, leads, mover, twin: false)); + } + + // ── Which elements count, and where the line is ───────────────────────── + + // An element after the moving list whose bound is the count the caller names plus two. The + // table is one row of one cell. + private static IRenderer After(string kind, int characters) + { + var text = string.Join(" ", Enumerable.Repeat("ab", characters / 3 + 1))[..characters]; + switch (kind) + { + case "paragraph": + return new ParagraphRenderer(new Paragraph(text, H(10)) { Margins = EdgeInsets.Zero }); + case "heading": + return new HeadingRenderer(new Heading(text, H(10))); + case "preformatted": + return new PreformattedRenderer(new Preformatted(text, H(10))); + case "table": + var table = new TableElement(); + table.AddRow().AddCell(new Cell(text) { Style = H(10) }); + return new TableRenderer(table); + case "listchild": + var parent = new ListItem("p", H(10)); + parent.AddChild(new ListItem(text, H(10))); + return new ListRenderer(new ListElement(ListStyle.Unordered).Add(parent)); + case "tablerows": + // One row for each character asked for, each holding an empty cell. + var rows = new TableElement().SetColumnWidths(100); + for (var i = 0; i < characters; i++) rows.AddRow().AddCell(new Cell("")); + return new TableRenderer(rows); + case "listempty": + // One entry for each character asked for, each holding no text. + var empty = new ListElement(ListStyle.Unordered); + for (var i = 0; i < characters; i++) empty.Add(new ListItem("", H(10))); + return new ListRenderer(empty); + default: + var list = new ListElement(ListStyle.Unordered); + list.Add(new ListItem(text, H(10))); + return new ListRenderer(list); + } + } + + private static string AfterTheMover(string kind, int characters, bool twin) => Save(r => + { + for (var i = 0; i < 4; i++) r.Add(new ParagraphRenderer(Lead())); + r.Add(ListOf(Mover(30), twin)); + r.Add(After(kind, characters)); + }, pageHeight: 100); + + /// + /// Every built-in element after a list counts, a paragraph, a heading, a preformatted text, a + /// table and another list, by its characters, entries and rows. A child of an item counts, and + /// an item with no text counts one. One whose bound is within the limit cannot reach it from + /// any start, and the lists are laid out new. + /// + [Theory] + [InlineData("paragraph")] + [InlineData("heading")] + [InlineData("preformatted")] + [InlineData("table")] + [InlineData("list")] + [InlineData("listchild")] + [InlineData("listempty")] + [InlineData("tablerows")] + public void AnElementWhoseBoundPassesTheLimit_keepsTheListsAsTheirTwins(string kind) + { + // The bound is two plus the characters, and the table adds a row. + var within = Limit - 4; + var past = Limit + 4; + + Assert.Equal(AfterTheMover(kind, past, twin: true), AfterTheMover(kind, past, twin: false)); + Assert.NotEqual(AfterTheMover(kind, within, twin: true), AfterTheMover(kind, within, twin: false)); + } + + /// + /// The size is read before anything is laid out, so a cell with no text, which a table with + /// column widths saves, is read as empty and does not raise an exception of its own. + /// + [Fact] + public void ATableCellWithNoText_isReadAsEmpty() + { + string Build(bool twin) => Save(r => + { + for (var i = 0; i < 4; i++) r.Add(new ParagraphRenderer(Lead())); + r.Add(ListOf(Mover(30), twin)); + var table = new TableElement().SetColumnWidths(100); + table.AddRow().AddCell(new Cell(null!)); + r.Add(new TableRenderer(table)); + }, pageHeight: 100); + + Assert.StartsWith("OK ", Build(twin: true)); + Assert.StartsWith("OK ", Build(twin: false)); + } + + /// + /// The line is the limit: a bound equal to it needs no fallback, and one more does. + /// + [Fact] + public void TheBoundOfTwoPlusTheCharacters_isComparedWithTheLimitItself() + { + Assert.NotEqual(AfterTheMover("paragraph", Limit - 2, twin: true), AfterTheMover("paragraph", Limit - 2, twin: false)); + Assert.Equal(AfterTheMover("paragraph", Limit - 1, twin: true), AfterTheMover("paragraph", Limit - 1, twin: false)); + } + + /// + /// The element has to come after a list: before every list its start is nobody's doing, so a + /// big element ahead of the lists leaves them new. Some number of lead lines puts the entry + /// where it moves, and there the document is not the twin's. + /// + [Fact] + public void AnElementAheadOfEveryList_doesNotTurnTheListsIntoTheirTwins() + { + string Build(int leads, bool twin) => Save(r => + { + r.Add(After("paragraph", Limit + 40)); + for (var i = 0; i < leads; i++) r.Add(new ParagraphRenderer(Lead())); + r.Add(ListOf(Mover(30), twin)); + }, pageHeight: 100); + + Assert.Contains(Enumerable.Range(0, 7), leads => Build(leads, twin: true) != Build(leads, twin: false)); + } + + /// + /// Each list the document places reports the fallback, as with the font rule. + /// + [Fact] + public void TheFallback_isReportedOncePerList() + { + var pdf = new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, 100), new EdgeInsets(10)) { ContinuationLimit = Limit }; + for (var i = 0; i < 4; i++) renderer.Add(new ParagraphRenderer(Lead())); + renderer.Add(new ListRenderer(Mover(30))); + renderer.Add(After("paragraph", Limit + 40)); + using var ms = new MemoryStream(); + + renderer.Render(ms); + + Assert.Single(renderer.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped); + } + + // ── Renderers the library ships that hold no list ─────────────────────── + + /// A renderer that lays no list out and carries no mark. + private sealed class Unmarked : IRenderer + { + public LayoutResult Layout(LayoutContext context) => + LayoutResult.Full(new LayoutBox(context.Area.X, context.Area.Y, 1, 1)); + + public void Draw(DrawContext ctx) + { + } + } + + private sealed class Marked : IRenderer, IListFreeRenderer + { + public LayoutResult Layout(LayoutContext context) => + LayoutResult.Full(new LayoutBox(context.Area.X, context.Area.Y, 1, 1)); + + public void Draw(DrawContext ctx) + { + } + } + + /// + /// A renderer that carries the mark is one of the library's own, so the lists of a document + /// that holds it are laid out the new way; one that does not carry it is a renderer of the + /// caller's, and every list is its twin and reports why. The mark is internal, so a caller's + /// renderer cannot carry it. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AMarkedRenderer_isTheLibrarysOwn_andAnUnmarkedOneIsNot(bool before) + { + IReadOnlyList Diagnostics(IRenderer other) + { + var pdf = new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, 100), new EdgeInsets(10)); + var list = new ListRenderer(new ListElement { Indent = 1000 }.Add(new ListItem("a b", H(10)))); + if (before) renderer.Add(other); + renderer.Add(list); + if (!before) renderer.Add(other); + using var ms = new MemoryStream(); + renderer.Render(ms); + return renderer.Diagnostics; + } + + Assert.Contains(Diagnostics(new Marked()), d => d.Code == LayoutDiagnosticCode.ListIndentClamped); + Assert.DoesNotContain(Diagnostics(new Marked()), d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped); + var skipped = Assert.Single( + Diagnostics(new Unmarked()), d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped); + Assert.Contains("a renderer of yours", skipped.Message, StringComparison.Ordinal); + Assert.DoesNotContain(Diagnostics(new Unmarked()), d => d.Code == LayoutDiagnosticCode.ListIndentClamped); + Assert.False(typeof(IListFreeRenderer).IsPublic); + } +} diff --git a/tests/VellumPdf.Layout.Tests/ListDocumentLimitTableTests.cs b/tests/VellumPdf.Layout.Tests/ListDocumentLimitTableTests.cs new file mode 100644 index 000000000..d87c455c9 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/ListDocumentLimitTableTests.cs @@ -0,0 +1,158 @@ +// 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; +using VellumPdf.Layout.Rendering.Table; + +namespace VellumPdf.Layout.Tests; + +/// +/// A table cell reads its line ends, so a cell of n characters can hold n + 1 lines, +/// and a row is cut into pieces that each take a line of the cells. The count of an element near +/// the limit (ListDocumentLimitRuleTests) is two, one for each row and the characters of the +/// cells, and it must stay above the continuations a table takes, whichever way its cells are read. +/// +public sealed class ListDocumentLimitTableTests +{ + private static readonly DateTimeOffset Stamp = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + + private static TextStyle H(double size) => new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = size }; + + private static T Pick(Random rng, params T[] values) => values[rng.Next(values.Length)]; + + // One row per entry, its cells holding the text and the size given. + private static TableElement Rows(int rows, params (string Text, double Size)[] cells) + { + var table = new TableElement(); + for (var i = 0; i < rows; i++) + { + var row = table.AddRow(); + foreach (var (text, size) in cells) + row.AddCell(new Cell(text) { Style = H(size), Padding = EdgeInsets.Zero }); + } + + return table; + } + + private static long BoundOf(TableElement table, double width, double height) + { + var probe = new DocumentRenderer(new PdfDocument(), new PdfRectangle(0, 0, width, height), new EdgeInsets(10)); + return probe.ContinuationBoundOf(new TableRenderer(table)); + } + + // Saves the table alone on a page, with the document's limit set to the bound, and returns the + // pages it took, or -1 when the save was refused for a reason other than the limit. + private static int PagesUnderItsOwnBound(TableElement table, double width, double height, string what) + { + var bound = BoundOf(table, width, height); + var pdf = new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var document = new DocumentRenderer(pdf, new PdfRectangle(0, 0, width, height), new EdgeInsets(10)) + { + ContinuationLimit = (int)bound, + }; + document.Add(new TableRenderer(table)); + try + { + using var ms = new MemoryStream(); + document.Render(ms); + return pdf.Pages.Count; + } + catch (InvalidOperationException ex) when (ex.Message.Contains("page continuations", StringComparison.Ordinal)) + { + Assert.Fail($"{what}: limit {bound} reached, page {width}x{height}"); + return -1; + } + catch (InvalidOperationException) + { + // A cell too tall for a page: a refusal that is not the limit. + return -1; + } + } + + /// + /// A row that holds a tall cell with line feeds and a short empty cell, over every page height + /// in a range, never reaches the limit set to its bound. The first piece of such a row can + /// take only the short cell when little room is left, which is the shape that adds a piece. + /// + [Fact] + public void ATallCellWithLineEndsBesideAnEmptyOne_staysWithinItsBound() + { + var taken = 0; + foreach (var lines in new[] { 1, 2, 3 }) + { + for (var height = 25.0; height <= 90; height += 1.5) + { + var table = Rows(40, (new string('\n', lines), 14), ("", 4)); + var pages = PagesUnderItsOwnBound(table, 100, height, $"{lines} line feeds, page height {height}"); + if (pages > 0) taken += pages; + } + } + + Assert.True(taken > 1000, $"only {taken} pages across the sample"); + } + + /// + /// Random tables with cells that hold line feeds, carriage returns, tabs and other control + /// white space, mixed sizes and paddings, and a repeated header row sometimes, are never + /// refused for the limit when it is set to their bound. + /// + [Fact] + public void ATableWhoseCellsReadLineEnds_staysWithinItsBound() + { + string[] contents = + [ + "", "", "\n", "\n\n", "\n\n\n", "x", "x\nx", "\nx", "x\n", " ", "ab cd", "\r\n", "\r", + "\r\n\r\n", "\t", "a\tb\nc", "WWWWWWWW", "\f\v", "\u0085", "\u2028", + ]; + var rng = new Random(20261123); + var taken = 0; + for (var seed = 0; seed < 500; seed++) + { + var table = new TableElement(); + var columns = rng.Next(1, 4); + if (rng.Next(5) == 0) + { + var header = table.AddRow(isHeader: true); + for (var c = 0; c < columns; c++) + header.AddCell(new Cell(Pick(rng, "h", "", "h\nh")) { Style = H(Pick(rng, 4.0, 6.0)), Padding = EdgeInsets.Zero }); + } + + for (var r = rng.Next(1, 40); r > 0; r--) + { + var row = table.AddRow(); + for (var c = 0; c < columns; c++) + { + row.AddCell(new Cell(Pick(rng, contents)) + { + Style = H(Pick(rng, 4.0, 6.0, 10.0, 14.0, 20.0, 30.0)), + Padding = new EdgeInsets(rng.Next(0, 3) * rng.Next(0, 8), 0, rng.Next(0, 3) * rng.Next(0, 8), 0), + }); + } + } + + var pages = PagesUnderItsOwnBound(table, Pick(rng, 60.0, 100.0, 200.0), 20 + rng.Next(5, 80), $"seed {seed}"); + if (pages > 0) taken += pages; + } + + // The sample reaches many pages, so the property is not met by tables of one page. + Assert.True(taken > 1500, $"only {taken} pages across the sample"); + } + + /// + /// The bound is two, one for each row and one for each character of each cell, with a null + /// cell text counting nothing. + /// + [Fact] + public void TheBoundOfATable_isTwoPlusItsRowsAndCharacters() + { + var table = Rows(3, ("a\nb", 10), ("", 10)); + table.AddRow().AddCell(new Cell(null!)); + + Assert.Equal(2 + 4 + 3 * 3, BoundOf(table, 200, 80)); + } +} diff --git a/tests/VellumPdf.Layout.Tests/ListEarlierLayoutTests.cs b/tests/VellumPdf.Layout.Tests/ListEarlierLayoutTests.cs new file mode 100644 index 000000000..a1c3c523d --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/ListEarlierLayoutTests.cs @@ -0,0 +1,575 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Security.Cryptography; +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Rendering; + +namespace VellumPdf.Layout.Tests; + +/// +/// A list builds its entries at its first layout and keeps them, as it did. When something other +/// than the document's own call in this save laid it out first, the document lays the list out as +/// it was before the fixes of #476 and #685, whatever comes later: the document placing it, a +/// renderer of the caller's holding it, a second document. The reference for every row is the +/// same document built over , the list as it was. +/// +public sealed class ListEarlierLayoutTests +{ + private static TextStyle H(double size) => new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = size }; + + private static readonly DateTimeOffset Stamp = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + + private static byte[] Save(Document doc) + { + doc.Timestamp = Stamp; + doc.DocumentId = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray(); + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + private static string Sha(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes))[..16]; + + private static string[] Shows(byte[] bytes) => + Regex.Matches(PdfTestUtil.DecompressAllFlatStreams(bytes), @"\(((?:\\.|[^\\)])*)\)\s*Tj") + .Select(m => m.Groups[1].Value).ToArray(); + + private const double PageWidth = 110; + private const double PageHeight = 100; + + private static Document Page(double width) => + new() { PageSize = new PdfRectangle(0, 0, width, PageHeight), Margins = new EdgeInsets(10) }; + + private static ListElement Make(string kind) => kind switch + { + // Text that wraps at the width it is laid out at. + "wrap" => new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem("WWW ab cd ef gh ij", H(10))) + .Add(new ListItem("kl mn op qr st uv wx", H(10))), + + // An indent no page width leaves any text, so the new layout clamps both entries. + "clamp" => new ListElement(ListStyle.OrderedDecimal) { Indent = 250 } + .Add(new ListItem("clamped text", H(10))) + .Add(new ListItem("second one", H(10))), + + // A 30 pt marker beside 10 pt text: the gutter is the marker's width where the area leaves + // the widest word room, and the indent where it does not. + _ => new ListElement(ListStyle.OrderedDecimal) { Indent = 10 } + .Add(new ListItem([new TextRun("WWWWW ab", H(10))]) { Style = H(30) }) + .Add(new ListItem([new TextRun("WWWWW cd", H(10))]) { Style = H(30) }), + }; + + /// + /// A renderer of the caller's. how 0 lays the inner renderer out through the context + /// it was given, 1 through at the width factor, 2 through + /// the public constructor at the factor, and 3 through at + /// three quarters of the width first and then through the context. + /// + private sealed class Caller(IRenderer inner, int how, double factor) : IRenderer + { + public LayoutResult Layout(LayoutContext context) + { + var a = context.Area; + var box = new LayoutBox(a.X, a.Y, a.Width * factor, a.Height); + LayoutResult result; + switch (how) + { + case 1: result = inner.Layout(context.WithArea(box)); break; + case 2: result = inner.Layout(new LayoutContext(box)); break; + case 3: + inner.Layout(context.WithArea(new LayoutBox(a.X, a.Y, a.Width * 0.75, a.Height))); + result = inner.Layout(context); + break; + default: result = inner.Layout(context); break; + } + + return result.Status switch + { + LayoutResult.Outcome.Full => LayoutResult.Full( + new LayoutBox(a.X, a.Y, a.Width, result.OccupiedArea!.Value.Height)), + LayoutResult.Outcome.Partial => LayoutResult.Partial( + new LayoutBox(a.X, a.Y, a.Width, result.OccupiedArea!.Value.Height), + new Caller(result.SplitRenderer!, 0, 1), + new Caller(result.OverflowRenderer!, how, factor)), + _ => LayoutResult.Nothing(), + }; + } + + public void Draw(DrawContext ctx) => inner.Draw(ctx); + } + + private static IRenderer Held(string how, IRenderer renderer) => how switch + { + "ctx" => new Caller(renderer, 0, 1), + "wa75" => new Caller(renderer, 1, 0.75), + "wa150" => new Caller(renderer, 1, 1.5), + "ctor75" => new Caller(renderer, 2, 0.75), + _ => new Caller(renderer, 3, 1), + }; + + // The renderer a scenario places: the list's own renderer, or the list as it was before the + // fixes, which is what 2.3.3 did with every list. + private static ListRenderer Renderer(string kind, bool twin, out ListElement list) + { + list = Make(kind); + var renderer = new ListRenderer(list); + return twin ? renderer.Unclamped() : renderer; + } + + /// + /// Runs one scenario and returns the last document's bytes. is the + /// layout that comes first and is not the document's own call: a renderer of the caller's that + /// holds the list in the same document, a layout before the save, or another document's save. + /// is the placement that follows, in the document saved last. + /// + private static byte[] Scenario(string earlier, string current, string kind, bool twin) + { + var renderer = Renderer(kind, twin, out _); + var width = PageWidth; + var doc = Page(width); + + if (earlier.StartsWith("pre")) + { + var factor = earlier == "pre75" ? 0.75 : 1.5; + renderer.Layout(new LayoutContext(new LayoutBox(10, 10, width * factor - 20, PageHeight - 20))); + } + else if (earlier.StartsWith("doc")) + { + var factor = earlier.EndsWith("75") ? 0.75 : 1.5; + var first = Page(width * factor); + first.Add(earlier.StartsWith("doc-held") ? Held("ctx", renderer) : renderer); + + // An element near the continuation limit makes that document lay every list out as its + // twin, so the entries the list keeps are built by the twin and not by the list. + if (earlier.StartsWith("doc-near")) first.Add(new Preformatted(new string('\t', 1_700), H(1)) { TabWidth = 32 }); + Save(first); + } + else + { + doc.Add(Held(earlier, renderer)); + doc.Add(new Paragraph("between", H(10)) { Margins = EdgeInsets.Zero }); + } + + doc.Add(current == "direct" ? renderer : Held(current, renderer)); + return Save(doc); + } + + /// + /// Whichever shape of layout built the entries first, and whichever shape comes after it, the + /// document lays the list out from those entries as it was before the fixes: the bytes are the + /// list's own as it was, for a list that wraps, one that clamps and one whose gutter depends on + /// the width, at an equal, a narrower and a wider first width. + /// + [Theory] + [InlineData("ctx", "direct")] + [InlineData("wa75", "direct")] + [InlineData("wa150", "direct")] + [InlineData("ctor75", "direct")] + [InlineData("measure", "direct")] + [InlineData("pre75", "direct")] + [InlineData("pre150", "direct")] + [InlineData("doc-held75", "direct")] + [InlineData("doc-direct75", "direct")] + [InlineData("doc-direct150", "direct")] + [InlineData("doc-near75", "direct")] + [InlineData("doc-near150", "direct")] + [InlineData("doc-near75", "wa150")] + [InlineData("ctx", "wa150")] + [InlineData("wa75", "wa150")] + [InlineData("measure", "wa150")] + [InlineData("pre75", "wa150")] + [InlineData("doc-direct75", "wa150")] + [InlineData("doc-direct150", "ctx")] + public void WhateverLaidTheListOutFirst_theDocumentKeepsTheEntriesThatLayoutBuilt(string earlier, string current) + { + foreach (var kind in new[] { "wrap", "clamp", "gutter" }) + { + var reference = Sha(Scenario(earlier, current, kind, twin: true)); + Assert.True(reference == Sha(Scenario(earlier, current, kind, twin: false)), $"{kind}: {earlier} then {current}"); + } + } + + /// + /// A renderer of the caller's lays the list out at three quarters of the width, and the + /// document then places the same renderer itself: the document draws that placement from the + /// entries the first layout built, at the width that layout had, so the text wraps where it did + /// there. Built at the page's own width the gutter would be the marker's, and the text would + /// wrap once. + /// + [Fact] + public void AListHeldByACallersRendererAndThenAddedToTheDocument_isDrawnFromTheEntriesTheHeldLayoutBuilt() + { + var shown = Shows(Scenario("measure", "direct", "gutter", twin: false)); + var asBefore = Shows(Scenario("measure", "direct", "gutter", twin: true)); + + Assert.Equal(asBefore, shown); + + // The first placement, the paragraph and the second placement: the second wraps "WWWWW" + // and "ab" apart, as the entries built at three quarters of the width do. + var second = shown.Skip(shown.ToList().IndexOf("between")).ToArray(); + Assert.Equal(["between", "1.", "WWWWW", "ab", "2.", "WWWWW", "cd"], second); + } + + /// + /// A list the document placed first and a renderer of the caller's holds afterwards keeps the + /// entries the document built. The renderer makes the document lay every list out as it was, so + /// the two placements the document makes report that, naming the renderer, and the placement + /// the renderer holds reports nothing. + /// + [Fact] + public void AListThePlacementBuiltAndACallersRendererThenHolds_isReportedAtEachPlacementTheDocumentMakes() + { + var renderer = new ListRenderer(Make("clamp")); + var doc = Page(PageWidth); + doc.Add(renderer); + doc.Add(Held("ctx", renderer)); + doc.Add(renderer); + Save(doc); + + var skipped = doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped).ToArray(); + Assert.Equal([0, 2], skipped.Select(d => d.ElementIndex).Order().ToArray()); + Assert.All(skipped, d => Assert.Contains("a renderer of yours", d.Message, StringComparison.Ordinal)); + Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListIndentClamped); + } + + /// + /// A list with an entry no page holds is placed as it was whole, and the document reports it + /// each time it places the list. The entries the twin built for the first placement are the + /// document's own, so they do not turn the second placement into a held one that reports + /// nothing. + /// + [Fact] + public void AListWithAnEntryNoPageHolds_isReportedAtEachPlacementOfTheSameRenderer() + { + var renderer = new ListRenderer(new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("abc", H(10))]) { Style = H(500) })); + var doc = Page(200); + doc.Add(renderer); + doc.Add(new Paragraph("between", H(10)) { Margins = EdgeInsets.Zero }); + doc.Add(renderer); + Save(doc); + + Assert.Equal( + [0, 2], + doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.ListEntryPartDropped) + .Select(d => d.ElementIndex).Order().ToArray()); + } + + // A renderer of the caller's that returns the list's own result, so the document calls the + // pieces of the list itself. + private sealed class PassThrough(IRenderer inner) : IRenderer + { + public LayoutResult Layout(LayoutContext context) => inner.Layout(context); + + public void Draw(DrawContext ctx) => inner.Draw(ctx); + } + + // Six entries of a 30 pt marker beside 10 pt text on a page that holds two of them, so the + // list splits into three pieces and the document calls the second and third itself. + private static ListRenderer SplitList(bool twin, bool midItem) + { + // The mid-item list holds two entries whose text runs over several pages, so the document + // calls a piece that resumes inside the entry. + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 10 }; + for (var i = 0; i < (midItem ? 2 : 6); i++) + { + list.Add(new ListItem([new TextRun(midItem ? string.Join(' ', Enumerable.Repeat("WWWWW", 40)) : "WWWWW ab", H(10))]) + { Style = H(30) }); + } + + var renderer = new ListRenderer(list); + return twin ? renderer.Unclamped() : renderer; + } + + // Draws nothing and takes no height. + private sealed class Empty : IRenderer + { + public LayoutResult Layout(LayoutContext context) => LayoutResult.Full(context.Area.WithHeight(0)); + + public void Draw(DrawContext ctx) + { + } + } + + // A renderer of the caller's that hands the document the first piece of the list as the + // overflow, with nothing of its own in front of it, so the document lays that first piece out + // itself on the next page. It is one way a first piece reaches the document without a + // downcast; the other is a piece the caller adds itself (SplitDocument, "addPiece"). + private sealed class Defer(IRenderer inner) : IRenderer + { + public LayoutResult Layout(LayoutContext context) + { + var result = inner.Layout(context); + return result.Status == LayoutResult.Outcome.Partial + ? LayoutResult.Partial(context.Area.WithHeight(0), new Empty(), result.SplitRenderer!) + : result; + } + + public void Draw(DrawContext ctx) => inner.Draw(ctx); + } + + private static Document SplitDocument(string shape, bool twin, double height = 80, int leads = 0) + { + var renderer = SplitList(twin, shape.EndsWith("Mid")); + var doc = new Document + { + PageSize = new PdfRectangle(0, 0, 200, height), + Margins = new EdgeInsets(10), + // The reference is the list as it was, which the document placing it directly reports. + // A document that holds a renderer of the caller's reports every list it places, the + // one over the entries that renderer built included, and the rows check that report. + StrictDiagnostics = !twin && !shape.StartsWith("heldThenDirect"), + }; + + for (var i = 0; i < leads; i++) doc.Add(new Paragraph("lead" + i, H(10)) { Margins = EdgeInsets.Zero }); + + if (shape.StartsWith("passThrough")) + { + doc.Add(new PassThrough(renderer)); + } + else if (shape.StartsWith("deferred")) + { + doc.Add(new Defer(renderer)); + } + else if (shape.StartsWith("addPiece")) + { + // The caller lays the list out before the save through the public constructor and adds + // the first piece, a renderer of the library's own, to the document. + var result = renderer.Layout(new LayoutContext(new LayoutBox(10, 10, 180, height - 20))); + doc.Add(result.Status == LayoutResult.Outcome.Partial ? result.SplitRenderer! : renderer); + } + else + { + // Held by a caller's renderer first, which builds the entries, and then placed by the + // document over them. + doc.Add(Held("ctx", renderer)); + doc.Add(new PageBreak()); + doc.Add(renderer); + } + + return doc; + } + + /// + /// The pieces of a list a renderer of the caller's holds take that placement, so the document + /// calling a piece itself does not make the piece one it placed. A caller that returns the + /// list's own result save with the bytes of the list as it was and report neither 207 nor + /// 208, with set. So does a caller that hands the + /// document the first piece as its overflow, so that the document lays the first piece out + /// itself, and a caller that adds the first piece to the document itself after laying the list + /// out, for a list that splits between entries and for one that splits inside an entry, on + /// several page heights and with lines ahead of the list. A list the document places over + /// entries a caller's renderer built has the bytes of the list as it was too, and reports the + /// fallback naming that renderer, because the document then holds a renderer of the caller's. + /// + [Theory] + [InlineData("passThrough")] + [InlineData("heldThenDirect")] + [InlineData("passThroughMid")] + [InlineData("heldThenDirectMid")] + [InlineData("deferred")] + [InlineData("deferredMid")] + [InlineData("addPiece")] + [InlineData("addPieceMid")] + public void ThePiecesOfAHeldList_reportNothingUnlessTheDocumentPlacesThem(string shape) + { + var deferred = shape.StartsWith("deferred", StringComparison.Ordinal) + || shape.StartsWith("addPiece", StringComparison.Ordinal); + foreach (var height in deferred ? new[] { 60.0, 70, 80, 90, 100, 110, 120 } : [80.0]) + { + foreach (var leads in deferred ? new[] { 0, 1, 2 } : [0]) + { + var reference = Save(SplitDocument(shape, twin: true, height, leads)); + var doc = SplitDocument(shape, twin: false, height, leads); + var bytes = Save(doc); + + Assert.True(Sha(reference) == Sha(bytes), $"{shape} height {height} leads {leads}"); + // A document that holds a renderer of the caller's reports the list it places over + // the entries that renderer built, and says why, and 208 where the twin drops a + // part; any other reports nothing. + if (!shape.StartsWith("heldThenDirect", StringComparison.Ordinal)) + Assert.DoesNotContain(doc.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListEntryPartDropped); + var skipped = doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped).ToArray(); + if (shape.StartsWith("heldThenDirect", StringComparison.Ordinal)) + { + var one = Assert.Single(skipped); + Assert.Contains("a renderer of yours", one.Message, StringComparison.Ordinal); + } + else + { + Assert.Empty(skipped); + } + } + } + } + + private static ListElement OneEntry(string text) => + new ListElement(ListStyle.OrderedDecimal).Add(new ListItem(text, H(10))); + + /// + /// A reused list in a document that lays every list out as it was reports what any list does + /// there: the fallback, once, whichever of the two rules made the document do so. A reused list + /// in a document that does not reports nothing. + /// + [Theory] + [InlineData("font", true)] + [InlineData("limit", true)] + [InlineData("none", false)] + public void AReusedList_reportsTheFallbackOnlyWhereTheDocumentLaysEveryListOutAsItWas(string rule, bool reports) + { + var renderer = new ListRenderer(Make("clamp")); + var first = Page(PageWidth); + first.Add(renderer); + Save(first); + + var second = Page(PageWidth); + second.Add(renderer); + if (rule == "font") + { + // Its text has no width at this indent, so it is dropped and the save does not draw it. + second.Add(new ListElement(ListStyle.Unordered) { Indent = 1000 } + .Add(new ListItem([new TextRun("bad", new TextStyle { FontRef = new FontReference((Standard14)99), FontSize = 10 })]) + { Style = H(10) })); + } + else if (rule == "limit") + { + second.Add(new Preformatted(new string('\t', 1_700), H(1)) { TabWidth = 32 }); + } + + Save(second); + + var skipped = second.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped).ToArray(); + Assert.Equal(reports, skipped.Length > 0); + Assert.DoesNotContain(second.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListIndentClamped); + if (reports) Assert.Contains(skipped, d => d.ElementIndex == 0); + } + + private static ListElement UndrawableList() => + new ListElement(ListStyle.Unordered) { Indent = 1000 } + .Add(new ListItem([new TextRun("bad", new TextStyle { FontRef = new FontReference((Standard14)99), FontSize = 10 })]) + { Style = H(10) }); + + private static Preformatted NearTheLimit() => new(new string('\t', 1_700), H(1)) { TabWidth = 32 }; + + // What each cause says that the other causes' messages do not. + private const string FontCause = "font it cannot draw"; + private const string NearCause = "element after a list"; + + /// + /// The 207 of a list the document lays out as it was names the rule that applied: the font the + /// document cannot draw, the element after a list near the limit, or both. Each message holds + /// the words of its causes and not the words of the other, and the order of the elements does + /// not change what the document found: a near-limit element ahead of the list in the font gives + /// the same message as one after it, whether that element is preformatted text or a list. + /// + [Theory] + [InlineData("font", true, false)] + [InlineData("near", false, true)] + [InlineData("font, near", true, true)] + [InlineData("near, font", true, true)] + [InlineData("font, nearlist", true, true)] + public void TheFallbackOfADocumentWideRule_namesTheRuleThatApplied(string order, bool namesFont, bool namesNear) + { + var doc = Page(PageWidth); + doc.Add(new ListRenderer(Make("clamp"))); + foreach (var cause in order.Split(", ")) + { + if (cause == "font") doc.Add(UndrawableList()); + else if (cause == "nearlist") doc.Add(new ListElement(ListStyle.Unordered).Add(new ListItem(new string('a', 50_000), H(1)))); + else doc.Add(NearTheLimit()); + } + + doc.Add(new ListRenderer(Make("clamp"))); + Save(doc); + + var skipped = doc.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped).ToArray(); + Assert.Contains(skipped, d => d.ElementIndex == 0); + Assert.All(skipped, d => + { + Assert.Equal(namesFont, d.Message.Contains(FontCause, StringComparison.Ordinal)); + Assert.Equal(namesNear, d.Message.Contains(NearCause, StringComparison.Ordinal)); + }); + } + + // Lays a list out only from its Draw, at the area Layout reserved, and draws it. + private sealed class LaysOutFromDraw(IRenderer inner) : IRenderer + { + private LayoutBox _box; + + public LayoutResult Layout(LayoutContext context) + { + _box = context.Area.WithHeight(Math.Min(20, context.Area.Height)); + return LayoutResult.Full(_box); + } + + public void Draw(DrawContext ctx) + { + inner.Layout(new LayoutContext(_box)); + inner.Draw(ctx); + } + } + + /// + /// A document that holds a renderer of the caller's lays every list out as it was before the + /// fixes of #476 and #685, whether that renderer lays its list out from Layout or only + /// from Draw: the document decides from the elements added, before any pass, so the + /// list ahead of it is not clamped. Both lists report why, naming the renderer. + /// + [Fact] + public void AListLaidOutOnlyFromDraw_isLaidOutAsItWas_likeEveryListOfTheDocument() + { + var doc = new Document { PageSize = new PdfRectangle(0, 0, 300, 300), Margins = new EdgeInsets(10) }; + ListElement Clamp() => new ListElement(ListStyle.OrderedDecimal) { Indent = 300 } + .Add(new ListItem("clamped text", H(10))); + + doc.Add(Clamp()); + doc.Add(new LaysOutFromDraw(new ListRenderer(UndrawableList()))); + doc.Add(Clamp()); + var bytes = Save(doc); + + // The same document before the fixes of #476 and #685 saves as 6D5D02C94C0F2E65. + Assert.Equal("6D5D02C94C0F2E65", Sha(bytes)); + Assert.Equal( + ["207x1@List0p1", "207x1@List2p1"], + doc.Diagnostics.Select(d => $"{(int)d.Code}x{d.Count}@{d.ElementKind}{d.ElementIndex}p{d.PageNumber}").ToArray()); + Assert.All( + doc.Diagnostics, + d => Assert.Contains("a renderer of yours", d.Message, StringComparison.Ordinal)); + } + + /// + /// The answer for a Standard 14 value is its own, whichever value was asked about before it: + /// the memo packs the value and its answer in one word, and no two values can share it. + /// + [Fact] + public void TheMemoOfTheLastStandard14Value_neverAnswersOneValueForAnother() + { + var run = ListLayoutRun.Begin(new PdfDocument(), out var previous); + try + { + var values = Enumerable.Range(-40, 100).Append(int.MinValue).Append(int.MaxValue).ToArray(); + foreach (var first in values) + { + foreach (var second in values) + { + // The memo holds the last value asked, so the first is asked again before each + // second: no other question may sit between the two. + ListLayoutRun.CanDraw(run, new TextStyle { FontRef = (Standard14)first }); + var style = new TextStyle { FontRef = (Standard14)second }; + Assert.True( + Enum.IsDefined((Standard14)second) == ListLayoutRun.CanDraw(run, style), + $"{second} asked after {first}"); + } + } + } + finally + { + ListLayoutRun.End(previous); + } + } +} diff --git a/tests/VellumPdf.Layout.Tests/ListEntryPlacementTests.cs b/tests/VellumPdf.Layout.Tests/ListEntryPlacementTests.cs new file mode 100644 index 000000000..f15e8761d --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/ListEntryPlacementTests.cs @@ -0,0 +1,262 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Security.Cryptography; +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Rendering; + +namespace VellumPdf.Layout.Tests; + +/// +/// A list entry is placed when its marker and its text are both placed (#685). When only one of +/// them fits what is left of a page the entry moves to the next page; when no page holds both it +/// keeps the part that fits, in the bytes the code wrote before, and the document reports it. The +/// digests are those of the base commit, read with the timestamp and document id this class pins. +/// +public sealed class ListEntryPlacementTests +{ + private static TextStyle H(double size) => new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = size }; + + private static byte[] Save(Document doc) + { + doc.Timestamp = new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + doc.DocumentId = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray(); + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + private static string Sha(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes))[..16]; + + private static string[] Shows(byte[] bytes) => + Regex.Matches(PdfTestUtil.DecompressAllFlatStreams(bytes), @"\(((?:\\.|[^\\)])*)\)\s*Tj") + .Select(m => m.Groups[1].Value).ToArray(); + + private static Document Square(int leadLines) + { + var doc = new Document { PageSize = new PdfRectangle(0, 0, 400, 400), Margins = new EdgeInsets(10) }; + for (var i = 0; i < leadLines; i++) doc.Add(new Paragraph("lead" + i, H(10)) { Margins = EdgeInsets.Zero }); + return doc; + } + + private static ListElement TallContent() => + new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("big", H(500))]) { Style = H(10) }) + .Add(new ListItem("next", H(10))); + + private static ListElement TallMarker() => + new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("abc", H(10))]) { Style = H(500) }) + .Add(new ListItem("next", H(10))); + + /// + /// Five lines of ten points use 60 of the 80 points of a page, and the first entry's marker + /// fits the 20 that are left while its twenty-point text, 24 high, does not. The entry moves to + /// the second page with its marker and its text; the base commit drew the marker and dropped + /// the text. + /// + [Fact] + public void AnEntryWhoseTextDoesNotFitWhatIsLeft_movesToTheNextPageWithItsMarker() + { + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 200, 100), Margins = new EdgeInsets(10) }; + for (var i = 0; i < 5; i++) doc.Add(new Paragraph("line" + i, H(10)) { Margins = EdgeInsets.Zero }); + doc.Add(new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("dropped", H(20))]) { Style = H(10) }) + .Add(new ListItem("next", H(10)))); + + var bytes = Save(doc); + + Assert.Equal(["line0", "line1", "line2", "line3", "line4", "1.", "dropped", "2.", "next"], Shows(bytes)); + Assert.Empty(doc.Diagnostics); + } + + /// + /// A sixty-point marker, 72 high, does not fit the 56 left under two lead lines. The base + /// commit drew the text and no marker; the entry now moves to the second page with both. + /// + [Fact] + public void AnEntryWhoseMarkerDoesNotFitWhatIsLeft_movesToTheNextPageWithItsText() + { + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 200, 100), Margins = new EdgeInsets(10) }; + for (var i = 0; i < 2; i++) doc.Add(new Paragraph("lead" + i, H(10)) { Margins = EdgeInsets.Zero }); + doc.Add(new ListElement(ListStyle.OrderedDecimal).Add(new ListItem([new TextRun("abc", H(10))]) { Style = H(60) })); + + Assert.Equal(["lead0", "lead1", "1.", "abc"], Shows(Save(doc))); + Assert.Empty(doc.Diagnostics); + } + + /// + /// A marker 40 points high in an area 20 wide breaks into two lines of 48, and eight lead lines + /// leave room for one. The base commit placed the entry with the marker's second line gone, a + /// "1" with no stop; the entry now moves, and the marker is drawn whole. + /// + [Fact] + public void AnEntryWhoseMarkerGetsSomeOfItsLines_movesToTheNextPage() + { + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 200, 300), Margins = new EdgeInsets(72, 90, 72, 90) }; + for (var i = 0; i < 8; i++) doc.Add(new Paragraph("l" + i, H(10)) { Margins = EdgeInsets.Zero }); + doc.Add(new ListElement(ListStyle.OrderedDecimal) { Indent = 5 } + .Add(new ListItem([new TextRun("abc", H(10))]) { Style = H(40) })); + + var bytes = Save(doc); + + Assert.Equal(["l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7", "1", ".", "ab", "c"], Shows(bytes)); + Assert.Empty(doc.Diagnostics); + } + + /// + /// At the top of a page nothing is gained by moving an entry, so it is placed where it is even + /// when a page of its own, as the context describes it, would hold both parts. + /// + [Fact] + public void AnEntryAtThePageTop_isNeverMoved() + { + var list = new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("dropped", H(20))]) { Style = H(10) }); + var renderer = new ListRenderer(list); + var context = new LayoutContext(new LayoutBox(10, 10, 180, 20)) + { + AtPageTop = true, + FreshPageArea = new LayoutBox(10, 10, 180, 80), + }; + + var result = renderer.Layout(context); + + Assert.Equal(LayoutResult.Outcome.Full, result.Status); + } + + /// The same entry with no lead lines is drawn on the first page, as before. + [Fact] + public void TheSameEntryAtThePageTop_isDrawnWhereItStarts() + { + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 200, 100), Margins = new EdgeInsets(10) }; + doc.Add(new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("dropped", H(20))]) { Style = H(10) }) + .Add(new ListItem("next", H(10)))); + + Assert.Equal("C21B6C8B3D63FDC0", Sha(Save(doc))); + Assert.Empty(doc.Diagnostics); + } + + /// + /// A line of 500 points fits no page of 380. The marker is drawn and the text is not, as it + /// was, and the document says so, at the top of a page and below other content. + /// + [Theory] + [InlineData(0, "DA0695640412B42C")] + [InlineData(3, "0B84BBC7F9D7A1AF")] + public void AnEntryWhoseTextIsTallerThanAPage_keepsTheBytesItHad_andIsReported(int lead, string digest) + { + using var doc = Square(lead); + doc.Add(TallContent()); + + Assert.Equal(digest, Sha(Save(doc))); + var item = Assert.Single(doc.Diagnostics); + Assert.Equal(LayoutDiagnosticCode.ListEntryPartDropped, item.Code); + Assert.Equal(LayoutDiagnosticSeverity.Error, item.Severity); + Assert.Equal(1, item.Count); + } + + [Theory] + [InlineData(0, "AEC6FFBE7431AC57")] + [InlineData(3, "D885F0FEB7A9EB25")] + public void AnEntryWhoseMarkerIsTallerThanAPage_keepsTheBytesItHad_andIsReported(int lead, string digest) + { + using var doc = Square(lead); + doc.Add(TallMarker()); + + var bytes = Save(doc); + + Assert.Equal(digest, Sha(bytes)); + Assert.Contains("abc", Shows(bytes)); + Assert.DoesNotContain("1.", Shows(bytes)); + var item = Assert.Single(doc.Diagnostics); + Assert.Equal(LayoutDiagnosticCode.ListEntryPartDropped, item.Code); + Assert.Equal(1, item.Count); + } + + /// StrictDiagnostics refuses the report, as it does the other list errors. + [Fact] + public void StrictDiagnostics_refusesAnEntryWithAPartDropped() + { + using var doc = Square(0); + doc.StrictDiagnostics = true; + doc.Add(TallContent()); + + var ex = Assert.Throws(() => Save(doc)); + + Assert.StartsWith("StrictDiagnostics refused the save: ListEntryPartDropped in List 0, page 1: ", ex.Message, StringComparison.Ordinal); + } + + // ── The continuation limit ────────────────────────────────────────────── + + private static readonly PdfRectangle ThirtyHigh = new(0, 0, 200, 50); + + // Entries whose text is 16.8 high and whose marker is 12: on a page 30 high the second entry + // of each page has room for its marker and none for its text, so it moves, and each page then + // holds one entry where it held two. + private static ListElement Staggered(int entries) + { + var list = new ListElement(ListStyle.OrderedDecimal); + for (var i = 0; i < entries; i++) + list.Add(new ListItem([new TextRun("t" + i, H(14))]) { Style = H(10) }); + + return list; + } + + private static (string Content, int Pages, IReadOnlyList Diagnostics, Exception? Error) Place( + ListRenderer renderer, int limit) + { + var pdf = new PdfDocument { Timestamp = new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero), DocumentId = new byte[16] }; + var documentRenderer = new DocumentRenderer(pdf, ThirtyHigh, new EdgeInsets(10)) { ContinuationLimit = limit }; + documentRenderer.Add(renderer); + using var ms = new MemoryStream(); + try + { + documentRenderer.Render(ms); + } + catch (InvalidOperationException ex) + { + return ("", 0, documentRenderer.Diagnostics, ex); + } + + return (PdfTestUtil.DecompressAllFlatStreams(ms.ToArray()), pdf.Pages.Count, documentRenderer.Diagnostics, null); + } + + /// + /// One hundred entries take 49 continuations with the second entry of each page left where it + /// falls, and 99 with it moved. Under a limit of 60 the move would refuse a list that saved, so + /// the list is placed as before and the fallback is reported; under 200 the entries move. + /// + [Fact] + public void MovedEntries_thatWouldPassTheLimit_fallBackToTheEarlierPlacement_andAreReported() + { + var main = Place(new ListRenderer(Staggered(100)).Unclamped(), limit: 60); + var run = Place(new ListRenderer(Staggered(100)), limit: 60); + + Assert.Null(main.Error); + Assert.Null(run.Error); + Assert.Equal(main.Content, run.Content); + Assert.Equal(main.Pages, run.Pages); + Assert.Contains(run.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped && d.Count == 1); + Assert.Contains(run.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListEntryPartDropped); + } + + [Fact] + public void MovedEntries_thatStayUnderTheLimit_areMoved_andTheirTextIsDrawn() + { + var main = Place(new ListRenderer(Staggered(100)).Unclamped(), limit: 200); + var run = Place(new ListRenderer(Staggered(100)), limit: 200); + + Assert.Null(run.Error); + Assert.Equal(100, Regex.Matches(run.Content, @"\(t\d+\)\s*Tj").Count); + Assert.Equal(50, Regex.Matches(main.Content, @"\(t\d+\)\s*Tj").Count); + Assert.DoesNotContain(run.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped); + Assert.Equal(100, run.Pages); + Assert.Equal(50, main.Pages); + } +} diff --git a/tests/VellumPdf.Layout.Tests/ListIndentClampTests.cs b/tests/VellumPdf.Layout.Tests/ListIndentClampTests.cs new file mode 100644 index 000000000..0de6e148e --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/ListIndentClampTests.cs @@ -0,0 +1,458 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Rendering; + +namespace VellumPdf.Layout.Tests; + +/// +/// A list indent that leaves an entry's text no width gives the text the width of its widest word +/// instead of discarding it (#476). Every row is a known answer: exact show strings, exact +/// Tm operands, exact report fields. The rows that must not move, a width that is positive +/// but short of the widest word, a long word, an entry with no word, and the nested refusal, are +/// pinned with the output the code produced before the change. +/// +public sealed class ListIndentClampTests +{ + private static TextStyle Helv(double size) => new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = size }; + + private static string Content(Document doc) + { + using var ms = new MemoryStream(); + doc.Save(ms); + return PdfTestUtil.DecompressAllFlatStreams(ms.ToArray()); + } + + private static string[] Shows(string content) => + Regex.Matches(content, @"\(((?:\\.|[^\\)])*)\)\s*Tj").Select(m => m.Groups[1].Value).ToArray(); + + private static string[] Positions(string content) => + Regex.Matches(content, @"1 0 0 1 (\S+) (\S+) Tm").Select(m => m.Groups[1].Value + "," + m.Groups[2].Value).ToArray(); + + // 200 x 400 with 72pt margins leaves an area 56pt wide. + private static Document Narrow(ListElement list) + { + var doc = new Document { PageSize = new PdfRectangle(0, 0, 200, 400) }; + doc.Add(list); + return doc; + } + + // 400 x 400 with 72pt margins leaves an area 256pt wide. + private static Document Wide(ListElement list) + { + var doc = new Document { PageSize = new PdfRectangle(0, 0, 400, 400) }; + doc.Add(list); + return doc; + } + + private static ListElement TenWs(double indent) => + new ListElement(ListStyle.OrderedDecimal) { Indent = indent } + .Add(new ListItem(string.Join(" ", Enumerable.Repeat("W", 10)), Helv(36))); + + private static ListElement Nested(double indent) + { + var item = new ListItem("parent", Helv(10)); + item.AddChild("child text"); + return new ListElement(ListStyle.OrderedDecimal) { Indent = indent }.Add(item); + } + + // ── The change ─────────────────────────────────────────────────────────── + + /// + /// An indent at or beyond the 56pt area keeps the text: ten W shows, the first at + /// 72 + 56 - 33.984 (a W is 944/1000 em, 33.984pt at 36pt), and the marker still first. + /// + [Theory] + [InlineData(56.0)] + [InlineData(200.0)] + [InlineData(10000.0)] + [InlineData(double.PositiveInfinity)] + public void FlatIndent_atOrBeyondTheArea_drawsTheTextAtTheWidthOfItsWidestWord(double indent) + { + using var doc = Narrow(TenWs(indent)); + + var content = Content(doc); + + var shows = Shows(content); + Assert.Equal("1.", shows[0]); + Assert.Equal(10, shows.Count(s => s == "W")); + Assert.Equal(11, shows.Length); + var positions = Positions(content); + Assert.Equal("72,292", positions[0]); + Assert.Equal("94.016,292", positions[1]); + Assert.Equal("94.016,248.8", positions[2]); + } + + [Fact] + public void FlatIndent_atTheArea_isReportedOnceWithTheCountOfClampedEntries() + { + using var doc = Narrow(TenWs(56)); + + Content(doc); + + var item = Assert.Single(doc.Diagnostics); + Assert.Equal(LayoutDiagnosticCode.ListIndentClamped, item.Code); + Assert.Equal(LayoutDiagnosticSeverity.Error, item.Severity); + Assert.Equal(1, item.Count); + Assert.Equal( + "Error ListIndentClamped List[0] page 1: A list indent left an entry's text no width beside its gutter, " + + "so the text was given a width, that of its widest word or the room right of its marker, " + + "and may overprint the marker.", + item.ToString()); + } + + /// + /// Every clamped entry is counted: at an indent of 200 in a 256pt area a parent's gutter of 200 + /// leaves 56, so only the three children, whose gutter is 400, are clamped. + /// + [Fact] + public void ReportCount_isTheNumberOfEntriesWhoseGutterWasNarrowed() + { + var one = new ListItem("one", Helv(10)); + one.AddChild("a"); + one.AddChild("b"); + var two = new ListItem("two", Helv(10)); + two.AddChild("c"); + using var doc = Wide(new ListElement(ListStyle.OrderedDecimal) { Indent = 200 }.Add(one).Add(two)); + + Content(doc); + + var item = Assert.Single(doc.Diagnostics); + Assert.Equal(LayoutDiagnosticCode.ListIndentClamped, item.Code); + Assert.Equal(3, item.Count); + } + + /// + /// A flat list at a 256pt area, an indent of 256, thirty items on a page that holds twelve: + /// the list is split, and the report comes from the piece that starts the list, once, with the + /// count of every entry, on page 1. + /// + [Fact] + public void ASplitList_reportsOnceFromItsFirstPage_withEveryEntryCounted() + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 256 }; + for (var i = 0; i < 30; i++) list.Add(new ListItem("item" + i, Helv(20))); + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 400, 400) }; + doc.Add(list); + + var content = Content(doc); + + Assert.Equal(30, Shows(content).Count(s => s.StartsWith("item", StringComparison.Ordinal))); + var item = Assert.Single(doc.Diagnostics); + Assert.Equal(30, item.Count); + Assert.Equal(1, item.PageNumber); + } + + [Fact] + public void StrictDiagnostics_refusesTheClampedList_andNamesTheCode() + { + using var doc = Narrow(TenWs(56)); + doc.StrictDiagnostics = true; + + var ex = Assert.Throws(() => Content(doc)); + + Assert.StartsWith("StrictDiagnostics refused the save: ListIndentClamped in List 0, page 1: ", ex.Message, StringComparison.Ordinal); + } + + /// + /// A nested list from half the area: the child text is drawn at the width of its widest word, + /// its marker where it was. + /// + [Theory] + [InlineData(128.0, "200,306")] + [InlineData(200.0, "272,306")] + public void NestedIndent_fromHalfTheArea_drawsTheChildText(double indent, string childMarker) + { + using var doc = Wide(Nested(indent)); + + var content = Content(doc); + + Assert.Equal(["1.", "parent", "1.", "child", "text"], Shows(content)); + var positions = Positions(content); + Assert.Equal("72,318", positions[0]); + Assert.Equal(childMarker, positions[2]); + Assert.Equal("307.44,306", positions[3]); + Assert.Equal("307.44,294", positions[4]); + Assert.Equal(1, Assert.Single(doc.Diagnostics).Count); + } + + /// + /// Just short of the area width the child's marker has 0.001pt left, so the clamp gives the + /// child text that width and it breaks to a glyph a line, as the parent text already did. + /// + [Fact] + public void NestedIndent_justBelowTheArea_drawsTheChildTextAtTheWidthLeftOfItsMarker() + { + using var doc = Wide(Nested(255.999)); + + var content = Content(doc); + + Assert.Equal( + ["1.", "p", "a", "r", "e", "n", "t", "1", ".", "c", "h", "i", "l", "d", "t", "e", "x", "t"], + Shows(content)); + var positions = Positions(content); + Assert.Equal("327.999,246", positions[7]); + Assert.Equal("327.999,234", positions[8]); + Assert.Equal("327.999,246", positions[9]); + Assert.Equal(1, Assert.Single(doc.Diagnostics).Count); + } + + // ── What does not move ─────────────────────────────────────────────────── + + [Theory] + [InlineData(0.0, "72,292 72,292 72,248.8")] + [InlineData(20.0, "72,292 92,292 92,248.8")] + [InlineData(55.0, "72,292 127,292 127,248.8")] + [InlineData(55.999999, "72,292 128,292 128,248.8")] + public void FlatIndent_belowTheArea_keepsItsOutput(double indent, string firstThree) + { + using var doc = Narrow(TenWs(indent)); + + var content = Content(doc); + + Assert.Equal(firstThree, string.Join(" ", Positions(content).Take(3))); + Assert.Equal(10, Shows(content).Count(s => s == "W")); + Assert.Empty(doc.Diagnostics); + } + + [Theory] + [InlineData(20.0, "1.|parent|1.|child text")] + [InlineData(100.0, "1.|parent|1.|child text")] + [InlineData(127.999, "1.|parent|1.|c|h|i|l|d|t|e|x|t")] + public void NestedIndent_belowHalfTheArea_keepsItsOutput(double indent, string shows) + { + using var doc = Wide(Nested(indent)); + + Assert.Equal(shows, string.Join("|", Shows(Content(doc)))); + Assert.Empty(doc.Diagnostics); + } + + [Theory] + [InlineData(200.0, "1.|alpha beta|gamma")] + [InlineData(220.0, "1.|alpha|beta|gamma")] + [InlineData(230.0, "1.|alpha|beta|gam|ma")] + [InlineData(240.0, "1.|alp|ha|bet|a|ga|m|ma")] + [InlineData(250.0, "1.|a|l|p|h|a|b|e|t|a|g|a|m|m|a")] + [InlineData(255.0, "1.|a|l|p|h|a|b|e|t|a|g|a|m|m|a")] + public void ShredZone_whereTheWidthIsPositive_isNotClamped(double indent, string shows) + { + using var doc = Wide(new ListElement(ListStyle.OrderedDecimal) { Indent = indent } + .Add(new ListItem("alpha beta gamma", Helv(10)))); + + Assert.Equal(shows, string.Join("|", Shows(Content(doc)))); + Assert.Empty(doc.Diagnostics); + } + + /// + /// A word wider than the whole area, at the default indent: the content stays at the gutter, + /// not on the marker. + /// + [Fact] + public void ALongWord_widerThanTheArea_keepsItsGutter() + { + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 595.28, 841.89) }; + doc.Add(new ListElement(ListStyle.OrderedDecimal).Add(new ListItem(new string('M', 70) + " tail", Helv(10)))); + + var content = Content(doc); + + Assert.Equal(4, Shows(content).Length); + Assert.Equal("72,759.89 92,759.89 92,747.89", string.Join(" ", Positions(content).Take(3))); + Assert.Empty(doc.Diagnostics); + } + + [Theory] + [InlineData(" ", 10.0)] + [InlineData("abc", 0.0)] + public void AnEntryWithNoWordWidth_isNotClamped(string text, double size) + { + using var doc = Narrow(new ListElement(ListStyle.OrderedDecimal) { Indent = 56 }.Add(new ListItem(text, Helv(size)))); + + Assert.Equal(["1."], Shows(Content(doc))); + Assert.Empty(doc.Diagnostics); + } + + /// + /// The child's own marker inset reaches the area: refused as before, with the same type and + /// message. + /// + [Theory] + [InlineData(256.0)] + [InlineData(300.0)] + public void NestedIndent_atTheArea_isStillRefused(double indent) + { + using var doc = Wide(Nested(indent)); + + var ex = Assert.Throws(() => Content(doc)); + + Assert.StartsWith("An element is too tall to fit on a single page and cannot be rendered.", ex.Message, StringComparison.Ordinal); + } + + [Fact] + public void ANaNIndent_isStillRefusedByTheCanvas() + { + using var doc = Narrow(TenWs(double.NaN)); + + Assert.Throws(() => Content(doc)); + } + + // ── What was refused stays refused ─────────────────────────────────────── + + // 200 x 150 with margins of 10 above and below and 72 either side: an area 56pt wide and 130pt + // tall, so a marker set at 200pt (a 240pt line) fits no page, and one at 100pt (120pt) fits a + // page top but not what is left under a line of ten-point text. + private static Document TallPage(ListElement list) + { + var doc = new Document { PageSize = new PdfRectangle(0, 0, 200, 150), Margins = new EdgeInsets(10, 72, 10, 72) }; + doc.Add(list); + return doc; + } + + private static ListItem TextAt10(string text, TextStyle markerStyle) => + new([new TextRun(text, Helv(10))]) { Style = markerStyle }; + + /// + /// A marker taller than the page has no room, and an entry whose text had no width was refused + /// for it. Giving the text a width must not turn that refusal into a save that draws the text + /// and no marker. + /// + [Theory] + [InlineData(56.0)] + [InlineData(1000.0)] + public void AFlatEntry_whoseMarkerHasNoRoom_isStillRefused(double indent) + { + using var doc = TallPage(new ListElement(ListStyle.OrderedDecimal) { Indent = indent }.Add(TextAt10("abc", Helv(200)))); + + var ex = Assert.Throws(() => Content(doc)); + + Assert.StartsWith("An element is too tall to fit on a single page and cannot be rendered.", ex.Message, StringComparison.Ordinal); + } + + [Fact] + public void ANestedEntry_whoseMarkerHasNoRoom_isStillRefused() + { + var parent = new ListItem("p", Helv(10)); + parent.AddChild(TextAt10("abc", Helv(200))); + using var doc = TallPage(new ListElement(ListStyle.OrderedDecimal) { Indent = 30 }.Add(parent)); + + var ex = Assert.Throws(() => Content(doc)); + + Assert.StartsWith("An element is too tall to fit on a single page and cannot be rendered.", ex.Message, StringComparison.Ordinal); + } + + /// + /// The same fixtures with a marker that fits: the clamp applies, both are drawn. + /// + [Fact] + public void TheSameEntries_withAMarkerThatFits_drawMarkerAndText() + { + var parent = new ListItem("p", Helv(10)); + parent.AddChild(TextAt10("abc", Helv(10))); + using var flat = TallPage(new ListElement(ListStyle.OrderedDecimal) { Indent = 56 }.Add(TextAt10("abc", Helv(10)))); + using var nested = TallPage(new ListElement(ListStyle.OrderedDecimal) { Indent = 30 }.Add(parent)); + + Assert.Equal(["1.", "abc"], Shows(Content(flat))); + Assert.Equal(["1.", "p", "1.", "abc"], Shows(Content(nested))); + Assert.Equal(1, Assert.Single(flat.Diagnostics).Count); + Assert.Equal(1, Assert.Single(nested.Diagnostics).Count); + } + + /// + /// Under a line of ten-point text 118pt are left, and the second entry's marker needs 120. The + /// marker has no room there, so the entry moves whole to the top of the next page, as it did + /// when its text was discarded; it is not drawn on the first page without its marker. + /// + [Fact] + public void AClampedEntry_whoseMarkerHasNoRoomOnThisPage_movesWholeToTheNext() + { + // An area 120pt wide, so that the 83pt marker is not broken. + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 120 } + .Add(TextAt10("one", Helv(10))) + .Add(TextAt10("abc", Helv(100))); + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 200, 150), Margins = new EdgeInsets(10, 40, 10, 40) }; + doc.Add(list); + + var content = Content(doc); + + Assert.Equal(["1.", "one", "2.", "abc"], Shows(content)); + var positions = Positions(content); + Assert.Equal("40,130", positions[0]); + Assert.Equal("40,40", positions[2]); + } + + // ── The arithmetic ─────────────────────────────────────────────────────── + + /// + /// For seeded areas, widest words and marker insets: the paragraph's own deflation + /// (area - gutter) never comes out below the width the word needs, and the gutter is the + /// widest that holds, so no word is broken and none gets more than a rounding error above the + /// width it asks for. The seed, the pair count and the number of pairs a plain + /// area - word would have broken are stated so the correction is shown to be reachable. + /// + [Fact] + public void ClampedGutter_leavesTheWordItsWidth_forSeededPairs() + { + const int Seed = 476; + const int Pairs = 200_000; + var rng = new Random(Seed); + var plainWouldBreak = 0; + for (var i = 0; i < Pairs; i++) + { + var area = 1 + (rng.NextDouble() * 1999); + var word = rng.NextDouble() * area; + var inset = i % 3 == 0 ? 0 : rng.NextDouble() * area * 0.9; + if (i % 50 == 0) word = area; + + // The widest word the room allows short of the room itself, where the gutter comes + // closest to the marker's inset. + if (i % 7 == 0 && area - inset > 0) word = Math.BitDecrement(area - inset); + + Assert.True(ListRenderer.TryClampGutter(area, area + rng.NextDouble(), inset, word, out var gutter)); + + var room = area - inset; + var need = Math.Min(word, room); + Assert.True(area - gutter >= need, $"pair {i}: {area} {word} {inset} -> {gutter}"); + Assert.True(gutter >= inset, $"pair {i}: gutter {gutter} left of inset {inset}"); + Assert.True(area - gutter - need <= area * 1e-9, $"pair {i}: gutter {gutter} gives the word more than it needs"); + if (word < room && area - (area - word) < word) plainWouldBreak++; + } + + Assert.True(plainWouldBreak > 0, "no seeded pair needs the one-step correction"); + } + + [Theory] + [InlineData(100.0, 100.0, 0.0, 30.0)] + [InlineData(100.0, 120.0, 0.0, 30.0)] + [InlineData(100.0, double.PositiveInfinity, 0.0, 30.0)] + public void TryClampGutter_whenTheTextWouldBeDiscarded_givesItsWord(double area, double gutter, double inset, double word) + { + Assert.True(ListRenderer.TryClampGutter(area, gutter, inset, word, out var clamped)); + Assert.Equal(70, clamped); + } + + [Theory] + [InlineData(100.0, 99.9, 0.0, 30.0)] + [InlineData(100.0, double.NaN, 0.0, 30.0)] + [InlineData(100.0, 100.0, 0.0, 0.0)] + [InlineData(100.0, 100.0, 100.0, 30.0)] + [InlineData(100.0, 100.0, 120.0, 30.0)] + [InlineData(100.0, 100.0, 0.0, double.NaN)] + public void TryClampGutter_otherwise_returnsTheGutterAsGiven(double area, double gutter, double inset, double word) + { + Assert.False(ListRenderer.TryClampGutter(area, gutter, inset, word, out var clamped)); + Assert.Equal(gutter, clamped); + } + + [Fact] + public void TryClampGutter_aWordWiderThanTheRoom_startsAtTheMarkersInset() + { + Assert.True(ListRenderer.TryClampGutter(100, 100, 0, 150, out var top)); + Assert.Equal(0, top); + Assert.True(ListRenderer.TryClampGutter(100, 250, 40, 90, out var nested)); + Assert.Equal(40, nested); + } +} diff --git a/tests/VellumPdf.Layout.Tests/ListIndentContinuationTests.cs b/tests/VellumPdf.Layout.Tests/ListIndentContinuationTests.cs new file mode 100644 index 000000000..19bf5e453 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/ListIndentContinuationTests.cs @@ -0,0 +1,386 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Rendering; + +namespace VellumPdf.Layout.Tests; + +/// +/// The list indent clamp (#476) draws text a list used to discard, so a list can need more page +/// continuations than before. A list whose clamp could take it past the limit is laid out without +/// drawing first, and is placed unclamped when that run reaches the limit, so a document that saved +/// still saves and a document that was refused is still refused. +/// +public sealed class ListIndentContinuationTests +{ + private static TextStyle Helv10() => new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = 10 }; + + // A page 40pt tall with 10pt margins leaves an area 20pt tall: one 12pt line, never two. + private static readonly PdfRectangle OneLinePage = new(0, 0, 200, 40); + + // 50pt leaves 30pt: two lines, never three. + private static readonly PdfRectangle TwoLinePage = new(0, 0, 200, 50); + + private static readonly DateTimeOffset Stamp = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + + private static PdfDocument NewPdf() => new() { Timestamp = Stamp, DocumentId = new byte[16] }; + + // The text "W" repeated, one word per line at the width the clamp gives it. + private static string Words(int count) => string.Join(" ", Enumerable.Repeat("W", count)); + + private static ListElement FlatList(int entries, int words) + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 }; + for (var i = 0; i < entries; i++) list.Add(new ListItem(Words(words), Helv10())); + return list; + } + + private sealed record Run( + string Content, + int Pages, + IReadOnlyList Diagnostics, + int Probes, + Exception? Error); + + private static Run Place( + IRenderer renderer, PdfRectangle page, int limit = 50_000) + { + var pdf = NewPdf(); + var documentRenderer = new DocumentRenderer(pdf, page, new EdgeInsets(10)) { ContinuationLimit = limit }; + documentRenderer.Add(renderer); + using var ms = new MemoryStream(); + Exception? error = null; + try + { + documentRenderer.Render(ms); + } + catch (InvalidOperationException ex) + { + error = ex; + } + + var content = error is null ? PdfTestUtil.DecompressAllFlatStreams(ms.ToArray()) : ""; + return new Run(content, pdf.Pages.Count, documentRenderer.Diagnostics, documentRenderer.ContinuationProbes, error); + } + + private static int Shows(Run run, string text) => + Regex.Matches(run.Content, @"\(" + Regex.Escape(text) + @"\)\s*Tj").Count; + + private static bool Skipped(Run run) => + run.Diagnostics.Any(d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped); + + // ── The decision, at a limit small enough to reach in a blink ─────────────── + + /// + /// One entry of N words, a page that holds one line: the clamped list takes N - 1 + /// continuations. At the limit it keeps the clamp, one more word and it is placed unclamped. + /// + [Theory] + [InlineData(100, false)] + [InlineData(101, false)] + [InlineData(102, true)] + [InlineData(500, true)] + public void AListThatNeedsMoreContinuationsThanTheLimit_isPlacedUnclamped(int words, bool unclamped) + { + var run = Place(new ListRenderer(FlatList(1, words)), OneLinePage, limit: 100); + + Assert.Null(run.Error); + Assert.Equal(unclamped, Skipped(run)); + Assert.Equal(unclamped ? 0 : words, Shows(run, "W")); + Assert.Equal(1, Shows(run, "1.")); + Assert.Equal(unclamped ? 1 : words, run.Pages); + } + + /// + /// The bound is the number of wrapped lines. At the limit it cannot be exceeded, so no probe + /// runs; one line above it the document lays the list out twice without drawing, as its twin + /// and its new layout, and, when the page holds two lines, finds room. + /// + [Theory] + [InlineData(100, 0)] + [InlineData(101, 2)] + [InlineData(200, 2)] + public void TheBound_keepsTheProbeForListsThatCouldReachTheLimit(int words, int probes) + { + var run = Place(new ListRenderer(FlatList(1, words)), TwoLinePage, limit: 100); + + Assert.Null(run.Error); + Assert.Equal(probes, run.Probes); + Assert.False(Skipped(run)); + Assert.Equal(words, Shows(run, "W")); + } + + /// + /// The bound counts the entries from the renderer's own start: a renderer built to start at + /// entry 100 of 150 holds 50 units, which a limit of 100 cannot be reached with. + /// + [Fact] + public void TheBound_countsFromTheStartItem() + { + var run = Place(new ListRenderer(FlatList(150, 1), startItem: 100), OneLinePage, limit: 100); + + Assert.Null(run.Error); + Assert.Equal(0, run.Probes); + } + + [Fact] + public void AListWithNoClampedEntry_isNeverProbed() + { + var list = new ListElement(ListStyle.OrderedDecimal); + for (var i = 0; i < 90; i++) list.Add(new ListItem(Words(3), Helv10())); + + var run = Place(new ListRenderer(list), OneLinePage, limit: 100); + + Assert.Null(run.Error); + Assert.Equal(0, run.Probes); + Assert.Empty(run.Diagnostics); + } + + /// + /// An entry with no text is a unit as well: it is a marker line that takes a page here. One + /// clamped entry and 150 empty ones is 152 units against a limit of 100, so the list is probed, + /// and the probe finds the 150 pages the empty entries take, which main refuses too. + /// + [Fact] + public void EntriesWithNoText_countAsOneUnitEach() + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 }; + list.Add(new ListItem(Words(2), Helv10())); + for (var i = 0; i < 150; i++) list.Add(new ListItem("", Helv10())); + var unclamped = Place(new ListRenderer(list).Unclamped(), OneLinePage, limit: 100); + + var run = Place(new ListRenderer(list), OneLinePage, limit: 100); + + Assert.NotNull(unclamped.Error); + Assert.Equal(1, run.Probes); + Assert.NotNull(run.Error); + Assert.Equal(unclamped.Error.Message, run.Error.Message); + } + + /// + /// The probe places the list on a copy of the cursor and puts the cursor back. With mirrored + /// margins the page a later element lands on decides its left edge: a paragraph that follows + /// the list is on page 2, a left-hand page, so it starts at the outside margin. A probe that + /// leaves the page index moved by an odd number puts it on the inside one. + /// + [Fact] + public void TheProbe_leavesThePageIndexWhereItWas() + { + var pdf = NewPdf(); + var renderer = new DocumentRenderer(pdf, OneLinePage, new EdgeInsets(10, 30, 10, 10)) + { + ContinuationLimit = 100, + MirrorMargins = true, + }; + renderer.Add(new ListRenderer(FlatList(1, 150))); + renderer.Add(new ParagraphRenderer(new Paragraph("para", Helv10()))); + using var ms = new MemoryStream(); + + renderer.Render(ms); + + var content = PdfTestUtil.DecompressAllFlatStreams(ms.ToArray()); + Assert.Equal(2, renderer.ContinuationProbes); + Assert.Single(Regex.Matches(content, @"1 0 0 1 10 \S+ Tm\s+\(1\.\)")); + Assert.Single(Regex.Matches(content, @"1 0 0 1 30 \S+ Tm\s+\(para\)")); + } + + /// + /// The unclamped placement is the placement a list gets with no clamp in the library: a list + /// that main refuses at the limit is refused here with the same message. + /// + [Fact] + public void AListTheUnclampedPlacementRefuses_isRefusedWithItsMessage() + { + // 150 entries, one marker line each on a one-line page: 149 continuations unclamped. + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 }; + for (var i = 0; i < 150; i++) list.Add(new ListItem("W", Helv10())); + var unclamped = Place(new ListRenderer(list).Unclamped(), OneLinePage, limit: 100); + + var clamped = Place(new ListRenderer(list), OneLinePage, limit: 100); + + Assert.NotNull(unclamped.Error); + Assert.NotNull(clamped.Error); + Assert.Equal(unclamped.Error.Message, clamped.Error.Message); + Assert.StartsWith("A single element needed more than 50000 page continuations", clamped.Error.Message, StringComparison.Ordinal); + } + + /// + /// Seeded lists at a small limit, each placed through the decision and as the unclamped twin: + /// the twin saves, so the decision saves; the twin is refused, so the decision is refused with + /// the same message; and where the decision falls back, its output is the twin's. + /// + [Fact] + public void Decision_agreesWithTheUnclampedPlacement_forSeededLists() + { + const int Seed = 476_207; + const int Lists = 3_000; + var rng = new Random(Seed); + int fellBack = 0, keptClamp = 0, bothRefused = 0, probed = 0; + for (var n = 0; n < Lists; n++) + { + var limit = rng.Next(4, 60); + var page = rng.Next(3) switch { 0 => OneLinePage, 1 => TwoLinePage, _ => new PdfRectangle(0, 0, 200, 90) }; + var style = (ListStyle)rng.Next(4); + var list = new ListElement(style) { Indent = rng.Next(3) == 0 ? rng.Next(0, 400) : 1000 }; + for (var i = rng.Next(1, 6); i > 0; i--) + { + var item = new ListItem(Words(rng.Next(1, 45)), Helv10()); + if (rng.Next(3) == 0) + for (var c = rng.Next(1, 3); c > 0; c--) item.AddChild(Words(rng.Next(1, 25))); + list.Add(item); + } + + var main = Place(new ListRenderer(list).Unclamped(), page, limit); + var run = Place(new ListRenderer(list), page, limit); + + if (main.Error is not null) + { + bothRefused++; + Assert.True(run.Error is not null, $"list {n}: refused unclamped, saved clamped"); + Assert.Equal(main.Error.Message, run.Error.Message); + continue; + } + + Assert.True(run.Error is null, $"list {n}: saved unclamped, refused clamped: {run.Error?.Message}"); + if (run.Probes > 0) probed++; + if (Skipped(run)) + { + fellBack++; + Assert.Equal(main.Content, run.Content); + Assert.Equal(main.Pages, run.Pages); + } + else if (run.Diagnostics.Any(d => d.Code == LayoutDiagnosticCode.ListIndentClamped)) + { + keptClamp++; + } + } + + // Measured for this seed. Each branch is reached, or the loop above proves nothing. + Assert.Equal(375, fellBack); + Assert.Equal(631, keptClamp); + Assert.Equal(1727, bothRefused); + Assert.Equal(701, probed); + } + + // ── Full size, at the limit the library ships with ────────────────────────── + + /// + /// A thousand entries of 51 words on a page that holds one line: 51,000 continuations clamped, + /// 1,000 unclamped. It saved as 1,000 marker lines before the clamp, and still does. + /// + [Fact] + public void ADocumentThatSaved_stillSaves_whenTheClampWouldPassFiftyThousandContinuations() + { + using var doc = new Document { PageSize = OneLinePage, Margins = new EdgeInsets(10), Timestamp = Stamp, DocumentId = new byte[16] }; + doc.Add(FlatList(1000, 51)); + using var ms = new MemoryStream(); + + doc.Save(ms); + + var content = PdfTestUtil.DecompressAllFlatStreams(ms.ToArray()); + Assert.Equal(1000, Regex.Matches(content, @"\((?:\d+)\.\)\s*Tj").Count); + Assert.DoesNotContain("(W)", content, StringComparison.Ordinal); + var item = Assert.Single(doc.Diagnostics); + Assert.Equal(LayoutDiagnosticCode.ListIndentClampSkipped, item.Code); + Assert.Equal(LayoutDiagnosticSeverity.Error, item.Severity); + Assert.Equal(1000, item.Count); + Assert.Equal(1, item.PageNumber); + } + + // A thousand entries of fifty words, and ahead of them one entry of `first` words when that is + // not zero: 50,000 + first lines, so 49,999 + first continuations on a page that holds one + // line. + private static ListElement AroundTheLimit(int first) + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 }; + if (first > 0) list.Add(new ListItem(Words(first), Helv10())); + for (var i = 0; i < 1000; i++) list.Add(new ListItem(Words(50), Helv10())); + return list; + } + + /// + /// 50,001 lines on a page that holds one line is 50,000 continuations, the most one element may + /// take: the bound cannot rule it out, so the list is probed in both layouts, and it keeps its + /// clamp. + /// + [Fact] + public void AListOneLineAboveTheBound_isProbedInBothLayoutsAndKeepsItsClampAtTheLimitExactly() + { + var run = Place(new ListRenderer(AroundTheLimit(1)), OneLinePage); + + Assert.Null(run.Error); + Assert.Equal(2, run.Probes); + Assert.Equal(50_001, Shows(run, "W")); + Assert.Equal(50_001, run.Pages); + Assert.False(Skipped(run)); + } + + /// + /// One line more is 50,001 continuations, which the limit refuses, so the list is placed + /// unclamped. + /// + [Fact] + public void AListOneContinuationPastTheLimit_isPlacedUnclamped() + { + var run = Place(new ListRenderer(AroundTheLimit(2)), OneLinePage); + + Assert.Null(run.Error); + Assert.Equal(2, run.Probes); + Assert.Equal(0, Shows(run, "W")); + Assert.Equal(1001, run.Pages); + Assert.True(Skipped(run)); + } + + /// 50,000 lines is at the bound, so no probe runs and the clamp is kept. + [Fact] + public void AListAtTheBound_isNotProbed() + { + var run = Place(new ListRenderer(AroundTheLimit(0)), OneLinePage); + + Assert.Null(run.Error); + Assert.Equal(0, run.Probes); + Assert.Equal(50_000, Shows(run, "W")); + Assert.False(Skipped(run)); + } + + /// + /// 60,000 lines is above the bound, two to a page is 30,000 pages: the probes run once in each + /// layout, find the room, and the text is kept. + /// + [Fact] + public void AListAboveTheBoundThatFits_isProbedInBothLayoutsAndKeepsItsClamp() + { + var run = Place(new ListRenderer(FlatList(1000, 60)), TwoLinePage); + + Assert.Null(run.Error); + Assert.Equal(2, run.Probes); + Assert.Equal(60_000, Shows(run, "W")); + Assert.Equal(30_000, run.Pages); + Assert.Equal(1000, Assert.Single(run.Diagnostics).Count); + Assert.Equal(LayoutDiagnosticCode.ListIndentClamped, Assert.Single(run.Diagnostics).Code); + } + + /// + /// A list above the bound whose entries all carry a run style the line-height walk refuses has + /// no clamped entry, so the list placed without the clamp is the list as it was, and the + /// refusal is the limit's, as it was, not the colour's. + /// + [Fact] + public void AListAboveTheBound_whoseStylesAreRefused_isRefusedAtTheLimitNotByTheStyle() + { + var refused = new TextStyle { FontRef = new FontReference(Standard14.Helvetica), FontSize = 10, Color = new ColorRgb(double.NaN, 0, 0) }; + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 }; + for (var i = 0; i < 150; i++) list.Add(new ListItem([new TextRun("W", refused)]) { Style = Helv10() }); + + var run = Place(new ListRenderer(list), OneLinePage, limit: 100); + + Assert.NotNull(run.Error); + Assert.Contains("page continuations", run.Error.Message, StringComparison.Ordinal); + Assert.DoesNotContain("colour", run.Error.Message, StringComparison.Ordinal); + } +} diff --git a/tests/VellumPdf.Layout.Tests/ListIndentRefusalParityTests.cs b/tests/VellumPdf.Layout.Tests/ListIndentRefusalParityTests.cs new file mode 100644 index 000000000..81a431ad8 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/ListIndentRefusalParityTests.cs @@ -0,0 +1,217 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Security.Cryptography; +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Rendering; + +namespace VellumPdf.Layout.Tests; + +/// +/// The list indent clamp (#476) gives text a width it did not have, and that starts the wrap and +/// the line-height walk the zero-width paragraph returned before. A clamp must not turn a save into +/// a refusal, so an entry the walk would refuse is left as it was, and these rows pin the whole +/// file the code saved before the change: the digests below are those of the base commit, read +/// with the timestamp and document id this class pins. +/// +public sealed class ListIndentRefusalParityTests +{ + private static TextStyle H(double size) => new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = size }; + + private static string Sha(Document doc) + { + doc.Timestamp = new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + doc.DocumentId = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray(); + using var ms = new MemoryStream(); + doc.Save(ms); + return Convert.ToHexString(SHA256.HashData(ms.ToArray()))[..16]; + } + + private static Document Page(double width, double height, ListElement list) + { + var doc = new Document { PageSize = new PdfRectangle(0, 0, width, height) }; + doc.Add(list); + return doc; + } + + public static TheoryData RefusedStyles() => + [ + "red-nan", "red-posinf", "red-neginf", "green-nan", "blue-posinf", "size-posinf", "size-nan", "size-neginf", + ]; + + private static TextStyle Refused(string name) => name switch + { + "red-nan" => new TextStyle { FontSize = 10, Color = new ColorRgb(double.NaN, 0, 0) }, + "red-posinf" => new TextStyle { FontSize = 10, Color = new ColorRgb(double.PositiveInfinity, 0, 0) }, + "red-neginf" => new TextStyle { FontSize = 10, Color = new ColorRgb(double.NegativeInfinity, 0, 0) }, + "green-nan" => new TextStyle { FontSize = 10, Color = new ColorRgb(0, double.NaN, 0) }, + "blue-posinf" => new TextStyle { FontSize = 10, Color = new ColorRgb(0, 0, double.PositiveInfinity) }, + "size-posinf" => new TextStyle { FontSize = double.PositiveInfinity }, + "size-nan" => new TextStyle { FontSize = double.NaN }, + "size-neginf" => new TextStyle { FontSize = double.NegativeInfinity }, + _ => throw new ArgumentOutOfRangeException(nameof(name)), + }; + + private static ListItem Entry(TextStyle runStyle, string text = "abc") => + new([new TextRun(text, runStyle)]) { Style = H(10) }; + + // The digests are the base commit's output for each layout, which does not depend on the style + // that was discarded: the marker only (flat), the parent and a child marker (nested), 400 + // markers (many). + private const string FlatDigest = "B43E8CB320B26453"; + private const string NestedDigest = "483FB82145AF91CF"; + private const string ManyDigest = "B9D99E3C97B80840"; + + /// + /// A flat list whose indent would give the text a width, with a run style the line-height walk + /// refuses, saves as it did: the marker is drawn, the text is not, nothing is reported. At an + /// indent of 20 the same style is refused, as it always was. + /// + [Theory] + [MemberData(nameof(RefusedStyles))] + public void FlatEntry_withAStyleTheWalkRefuses_keepsTheOutputItHad(string style) + { + foreach (var indent in new[] { 56.0, 1000.0 }) + { + using var doc = Page(200, 400, new ListElement(ListStyle.OrderedDecimal) { Indent = indent }.Add(Entry(Refused(style)))); + + Assert.Equal(FlatDigest, Sha(doc)); + Assert.Empty(doc.Diagnostics); + } + + using var plain = Page(200, 400, new ListElement(ListStyle.OrderedDecimal) { Indent = 20 }.Add(Entry(Refused(style)))); + Assert.Throws(() => Sha(plain)); + } + + [Theory] + [MemberData(nameof(RefusedStyles))] + public void NestedChild_withAStyleTheWalkRefuses_keepsTheOutputItHad(string style) + { + var parent = new ListItem("p", H(10)); + parent.AddChild(Entry(Refused(style))); + using var doc = Page(400, 400, new ListElement(ListStyle.OrderedDecimal) { Indent = 128 }.Add(parent)); + + Assert.Equal(NestedDigest, Sha(doc)); + Assert.Empty(doc.Diagnostics); + } + + /// + /// Four hundred entries on a page that holds one line each: the list is long enough to need + /// the continuation bound if any entry were clamped. None is, so nothing is walked. + /// + [Theory] + [MemberData(nameof(RefusedStyles))] + public void ManyEntries_withAStyleTheWalkRefuses_keepTheOutputTheyHad(string style) + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 }; + for (var i = 0; i < 400; i++) list.Add(Entry(Refused(style), "W")); + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 200, 40), Margins = new EdgeInsets(10) }; + doc.Add(list); + + Assert.Equal(ManyDigest, Sha(doc)); + Assert.Empty(doc.Diagnostics); + } + + /// + /// The refusal is one entry's, not the list's: a second entry with an accepted style is still + /// clamped, and the refused entry beside it is still not. + /// + [Fact] + public void AnAcceptedEntry_besideARefusedOne_isStillClamped() + { + using var doc = Page(200, 400, new ListElement(ListStyle.OrderedDecimal) { Indent = 56 } + .Add(Entry(Refused("red-nan"))) + .Add(Entry(H(10), "abc"))); + + using var ms = new MemoryStream(); + doc.Save(ms); + var content = PdfTestUtil.DecompressAllFlatStreams(ms.ToArray()); + + Assert.Equal(["1.", "2.", "abc"], Regex.Matches(content, @"\(((?:\\.|[^\\)])*)\)\s*Tj").Select(m => m.Groups[1].Value).ToArray()); + Assert.Equal(1, Assert.Single(doc.Diagnostics).Count); + } + + /// + /// The predicate is the same rule as ValidateStyle: it says a style is accepted exactly + /// when the validation does not throw, for every refused style and for the accepted ones. + /// + [Theory] + [MemberData(nameof(RefusedStyles))] + public void TheClampsPredicate_agreesWithValidateStyle(string style) + { + var refused = Refused(style); + var accepted = H(10); + + Assert.Throws(() => LayoutValidation.ValidateStyle(refused, "x")); + LayoutValidation.ValidateStyle(accepted, "x"); + Assert.False(LayoutValidation.AreRunStylesAccepted([new TextRun("abc", refused)])); + Assert.False(LayoutValidation.AreRunStylesAccepted([new TextRun("ok", accepted), new TextRun("abc", refused)])); + Assert.True(LayoutValidation.AreRunStylesAccepted([new TextRun("abc", accepted)])); + + // A run that holds no text yields no fragment, so its style is never walked. + Assert.True(LayoutValidation.AreRunStylesAccepted([new TextRun("abc", accepted), new TextRun("", refused)])); + } + + /// + /// An entry whose clamped line would be taller than a page is not clamped, because no page + /// holds it: the list is placed as the base commit placed it, and written as it wrote it. The + /// entry is reported as one that fits no page, and no gutter is reported as narrowed. + /// + [Fact] + public void AnEntry_whoseLineWouldBeTallerThanAPage_isWrittenAsItWas() + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 300 } + .Add(new ListItem([new TextRun("big", H(500))]) { Style = H(10) }); + using var doc = new Document { PageSize = new PdfRectangle(0, 0, 400, 400) }; + doc.Add(list); + doc.Add(new Paragraph("after", H(10))); + + Assert.Equal("60DC9BDAB5A29371", Sha(doc)); + Assert.Equal( + [LayoutDiagnosticCode.ListEntryPartDropped], + doc.Diagnostics.Select(d => d.Code).ToArray()); + } + + /// + /// A marker with no room mid-page: the entry moves whole to the next page, where its text is + /// drawn and the clamp is reported. It is not the output the base commit wrote, which left the + /// text off page 2. + /// + [Fact] + public void AMarkerWithNoRoomMidPage_movesTheEntryAndItsClampedTextToTheNextPage() + { + var doc = new Document { PageSize = new PdfRectangle(0, 0, 200, 100), Margins = new EdgeInsets(10, 72, 10, 72) }; + for (var i = 0; i < 5; i++) doc.Add(new Paragraph("l" + i, H(10)) { Margins = EdgeInsets.Zero }); + doc.Add(new ListElement(ListStyle.OrderedDecimal) { Indent = 56 } + .Add(new ListItem("abc", H(10)) { Style = H(30) })); + + using var ms = new MemoryStream(); + doc.Save(ms); + var content = PdfTestUtil.DecompressAllFlatStreams(ms.ToArray()); + + Assert.Matches(@"\(1\.\)\s*Tj[\s\S]*\(abc\)\s*Tj", content); + Assert.Equal(1, Assert.Single(doc.Diagnostics).Count); + Assert.Equal(LayoutDiagnosticCode.ListIndentClamped, doc.Diagnostics[0].Code); + doc.Dispose(); + } + + /// + /// A list whose area has width but no height builds no entry, as the list's own layout does, + /// so the refusal that reaches the caller is the "too tall" one, not the entry's null text. + /// + [Fact] + public void AListWithNoHeight_isRefusedAsTooTall_beforeAnyEntryIsBuilt() + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 1000, Margins = new EdgeInsets(1000, 0, 0, 0) } + .Add(new ListItem((string)null!, H(10))); + using var doc = Page(200, 400, list); + + var ex = Assert.Throws(() => Sha(doc)); + + Assert.StartsWith("An element is too tall to fit on a single page and cannot be rendered.", ex.Message, StringComparison.Ordinal); + } +} diff --git a/tests/VellumPdf.Layout.Tests/ListPlacementAdoptionTests.cs b/tests/VellumPdf.Layout.Tests/ListPlacementAdoptionTests.cs new file mode 100644 index 000000000..3f3e16424 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/ListPlacementAdoptionTests.cs @@ -0,0 +1,1133 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Security.Cryptography; +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Rendering; + +namespace VellumPdf.Layout.Tests; + +/// +/// A list lays out its new way (the indent clamp of #476, the moved entries of #685) only where the +/// document addressed the call to it and decided the continuation limit (#686). These rows pin what +/// that means for the list: any other context, an entry that cannot be drawn, an entry no page +/// holds and a first box with no height all give the placement the list had before, which is what +/// lays out. +/// +public sealed class ListPlacementAdoptionTests +{ + private static TextStyle H(double size) => new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = size }; + + private static readonly DateTimeOffset Stamp = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + + private static byte[] Save(Document doc) + { + doc.Timestamp = Stamp; + doc.DocumentId = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray(); + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + private static string Sha(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes))[..16]; + + private static string[] Shows(byte[] bytes) => + Regex.Matches(PdfTestUtil.DecompressAllFlatStreams(bytes), @"\(((?:\\.|[^\\)])*)\)\s*Tj") + .Select(m => m.Groups[1].Value).ToArray(); + + private static Document Page(double width, double height, int leadLines = 0, double lead = 10) + { + var doc = new Document { PageSize = new PdfRectangle(0, 0, width, height), Margins = new EdgeInsets(10) }; + for (var i = 0; i < leadLines; i++) doc.Add(new Paragraph("lead" + i, H(lead)) { Margins = EdgeInsets.Zero }); + return doc; + } + + private static LayoutDiagnosticCode[] Codes(Document doc) => doc.Diagnostics.Select(d => d.Code).ToArray(); + + /// + /// The document the list is added to as a list, and the same document with its twin. + /// + private static (byte[] New, Document NewDoc, byte[] Twin, Document TwinDoc) Both( + Func page, Func list) + { + var newDoc = page(); + newDoc.Add(list()); + var twinDoc = page(); + twinDoc.Add(new ListRenderer(list()).Unclamped()); + return (Save(newDoc), newDoc, Save(twinDoc), twinDoc); + } + + // An entry the clamp widens, and one that does not fit what is left of a page. + private static ListElement ClampAndMove() => + new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 } + .Add(new ListItem("clamped text", H(10))) + .Add(new ListItem([new TextRun("dropped", H(20))]) { Style = H(10) }); + + // ── A context the document did not build ───────────────────────────────── + + /// + /// A renderer of the caller's that lays a list out through the context it was given, through + /// , or through the public constructor, is laid out as + /// before the fixes: the output is the twin's, byte for byte, and the list is drawn. + /// + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + public void AListALayoutRendererOfTheCallersLaysOut_isPlacedAsBefore(int how) + { + Document Wrapped(bool twin) + { + var doc = Page(200, 100, leadLines: 5); + var inner = new ListRenderer(ClampAndMove()); + doc.Add(new PassOn(twin ? inner.Unclamped() : inner, how)); + return doc; + } + + var wrapped = Wrapped(twin: false); + var plain = Wrapped(twin: true); + + var bytes = Save(wrapped); + + Assert.Equal(Sha(Save(plain)), Sha(bytes)); + Assert.Contains("1.", Shows(bytes)); + Assert.DoesNotContain("clamped", string.Concat(Shows(bytes)), StringComparison.Ordinal); + Assert.DoesNotContain(LayoutDiagnosticCode.ListIndentClamped, Codes(wrapped)); + Assert.DoesNotContain(LayoutDiagnosticCode.ListIndentClampSkipped, Codes(wrapped)); + } + + /// + /// A caller's renderer that reserves 100 points above a list and lays the list out in the rest + /// through keeps the output the list had. Moving the first + /// entry there answered Nothing for the list, and the document refused the wrapper as too tall + /// where it had saved. + /// + [Fact] + public void AListInANarrowedAreaAtAPageTop_isNotMovedAndNotRefused() + { + Document Build(bool twin) + { + var doc = Page(200, 200); + var list = new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("big", H(100))]) { Style = H(10) }) + .Add(new ListItem("next", H(10))); + var inner = new ListRenderer(list); + doc.Add(new Inset(twin ? inner.Unclamped() : inner, 100)); + doc.Add(new Paragraph("after", H(10))); + return doc; + } + + var doc = Build(twin: false); + var bytes = Save(doc); + + Assert.Equal(Sha(Save(Build(twin: true))), Sha(bytes)); + Assert.Equal(["1.", "2.", "next", "after"], Shows(bytes)); + } + + /// + /// A twin a caller's renderer holds is not one the document chose: it reports nothing about the + /// continuation limit, and the list it wraps saves or is refused as the twin does. + /// + [Fact] + public void AListTheCallersRendererHolds_reportsNoFallbackAtTheContinuationLimit() + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 }; + list.Add(new ListItem(string.Join(" ", Enumerable.Repeat("W", 150)), H(10))); + var pdf = new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, 40), new EdgeInsets(10)) { ContinuationLimit = 100 }; + renderer.Add(new PassOn(new ListRenderer(list), 0)); + + using var ms = new MemoryStream(); + renderer.Render(ms); + + Assert.DoesNotContain(renderer.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped); + Assert.DoesNotContain(renderer.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListIndentClamped); + } + + /// + /// A renderer that a caller laid out before the save keeps the entries that call built, as it + /// did on 2.3.3: the document does not build them again at its own width, and does not clamp + /// them. The list here has an indent no width is left beyond, so a clamp would give the text a + /// width and draw it. + /// + [Fact] + public void AListLaidOutBeforeTheSave_keepsTheEntriesThatCallBuilt() + { + var renderer = new ListRenderer(new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 } + .Add(new ListItem("clamped text", H(10)))); + renderer.Layout(new LayoutContext(new LayoutBox(0, 0, 200, 100))); + var pdf = new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var documentRenderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, 100), new EdgeInsets(10)); + documentRenderer.Add(renderer); + + using var ms = new MemoryStream(); + documentRenderer.Render(ms); + + Assert.DoesNotContain("clamped", string.Concat(Shows(ms.ToArray())), StringComparison.Ordinal); + Assert.DoesNotContain(documentRenderer.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListIndentClamped); + } + + // Thirty entries whose gutter leaves the text five points at a width of 25, so a layout at that + // width wraps each word to a letter a line, and the paragraphs keep that wrap. + private static ListElement NarrowList() + { + var list = new ListElement(ListStyle.OrderedRoman) { Indent = 20 }; + for (var i = 0; i < 30; i++) list.Add(new ListItem("word", H(10))); + return list; + } + + private static Document NarrowPage() => + new() { PageSize = new PdfRectangle(0, 0, 200, 2000), Margins = new EdgeInsets(10) }; + + /// Lays the list out through the context it is given, as a caller does. + private sealed class Passes(IRenderer inner) : IRenderer + { + public LayoutResult Layout(LayoutContext context) => inner.Layout(context); + + public void Draw(DrawContext ctx) => inner.Draw(ctx); + } + + /// + /// A caller's renderer after the list, which makes the document lay every list out as it was. + /// + private sealed class Counts : IRenderer + { + public LayoutResult Layout(LayoutContext context) => + LayoutResult.Full(new LayoutBox(context.Area.X, context.Area.Y, 1, 1)); + + public void Draw(DrawContext ctx) + { + } + } + + /// + /// The entries a caller built at another width are the ones the save draws, whether the list is + /// added to the document or held by a renderer of the caller's, and whether or not another list + /// comes before it. Each row has the same document with the twin, which + /// holds those entries as 2.3.3 did, as its reference. + /// + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void AListLaidOutBeforeTheSaveAtAnotherWidth_isDrawnFromTheEntriesThatCallBuilt(bool held, bool afterAList) + { + Document Build(bool twin, bool laidOutBefore) + { + var doc = NarrowPage(); + if (afterAList) doc.Add(new ListElement().Add(new ListItem("first", H(10)))); + var renderer = new ListRenderer(NarrowList()); + IRenderer added = twin ? renderer.Unclamped() : renderer; + if (laidOutBefore) added.Layout(new LayoutContext(new LayoutBox(0, 0, 25, 1000))); + doc.Add(held ? new Passes(added) : added); + doc.Add(new Counts()); + return doc; + } + + var kept = Save(Build(twin: false, laidOutBefore: true)); + var reference = Save(Build(twin: true, laidOutBefore: true)); + var fresh = Save(Build(twin: false, laidOutBefore: false)); + + // The call laid out the entries that fit its 1000 points, and each of those is wrapped at + // five points of text; the entries after them were wrapped when the document drew them. + Assert.Equal(Sha(reference), Sha(kept)); + Assert.Contains("w", Shows(kept)); + Assert.True(Shows(kept).Count(t => t == "word") < 30); + Assert.Equal(30, Shows(fresh).Count(t => t == "word")); + } + + // An indent that leaves the first document's 180-point area no text, so the clamp narrows it, + // and leaves the second document's 380-point area 130 points. + private static ListElement ClampedAtTheFirstWidth() => new ListElement(ListStyle.OrderedDecimal) { Indent = 250 } + .Add(new ListItem(ClampedText, H(10))); + + private const string ClampedText = "reused text that wraps over several lines"; + + // An indent that clamps nothing, and a text that wraps differently at 160 and at 360 points. + private static ListElement WrapsAtTheFirstWidth() + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 20 }; + for (var i = 0; i < 3; i++) list.Add(new ListItem(string.Join(" ", Enumerable.Repeat("reused", 14)), H(10))); + return list; + } + + private static Document Narrow(double width) => + new() { PageSize = new PdfRectangle(0, 0, width, 300), Margins = new EdgeInsets(10) }; + + // The second document's bytes after one renderer served a first document of 200 points. + private static byte[] SecondDocument(Func make, string shape, bool twin) + { + var renderer = new ListRenderer(make()); + IRenderer Use(bool held) => held ? new Passes(twin ? renderer.Unclamped() : renderer) : twin ? renderer.Unclamped() : renderer; + + var first = Narrow(200); + first.Add(Use(shape.StartsWith("held", StringComparison.Ordinal))); + Save(first); + var second = Narrow(400); + second.Add(Use(shape.EndsWith("held", StringComparison.Ordinal))); + return Save(second); + } + + private static byte[] FreshSecondDocument(Func make) + { + var second = Narrow(400); + second.Add(new ListRenderer(make())); + return Save(second); + } + + /// + /// A renderer that served one document keeps the entries it built there, at the width of that + /// document, when it serves another, as 2.3.3 kept them, whether it was added to each + /// document or held by a renderer of a caller's in either. The reference is the twin, which + /// holds the entries as 2.3.3 built them, and a list built again at the second document's + /// width differs from it. + /// + [Theory] + [InlineData("direct-direct", false)] + [InlineData("held-direct", true)] + [InlineData("direct-held", true)] + [InlineData("direct-direct", true)] + public void AListRendererReusedForASecondDocument_keepsTheEntriesTheFirstBuilt(string shape, bool wraps) + { + Func make = wraps ? WrapsAtTheFirstWidth : ClampedAtTheFirstWidth; + + var kept = SecondDocument(make, shape, twin: false); + + Assert.Equal(Sha(SecondDocument(make, shape, twin: true)), Sha(kept)); + if (wraps) + Assert.NotEqual(Sha(FreshSecondDocument(make)), Sha(kept)); + + // The clamp narrowed the first document's gutter to the widest word, which would have put + // the text on one line in the second. 2.3.3 kept the indent, so the text wraps at 130 + // points. + else + Assert.DoesNotContain(ClampedText, Shows(kept)); + } + + // The twenty-seventh roman marker, "xxvii.", is wider than the indent, so the gutter widens to + // it when the entry's longest word still fits beside it, and stays at the indent when it does + // not. The word is wider than the first document's area and fits the second's. + private static ListElement GutterThatDependsOnTheWidth() + { + var list = new ListElement(ListStyle.OrderedRoman) { Indent = 20 }; + for (var i = 0; i < 26; i++) list.Add(new ListItem("a", H(10))); + return list.Add(new ListItem(new string('w', 30), H(10))); + } + + // The same with an indent that leaves the first document's area no text, so the clamp narrows + // the entries there, and a marker of 85 points that is wider than the indent. The twin builds + // the entries the clamp narrowed anew, and the width it builds them at decides their gutter. + private static ListElement ClampedGutterThatDependsOnTheWidth() + { + var list = new ListElement(ListStyle.OrderedRoman) { Indent = 185 }; + for (var i = 0; i < 26; i++) list.Add(new ListItem("a", H(10))); + return list.Add(new ListItem("w", H(85))); + } + + /// + /// The entries the second document keeps are built at the first document's width: a gutter the + /// first width left at the indent stays there, though the second width would widen it, for an + /// entry the clamp narrowed as for one it left alone. + /// + [Theory] + [InlineData("direct-direct", false)] + [InlineData("held-direct", false)] + [InlineData("direct-held", false)] + [InlineData("direct-direct", true)] + [InlineData("held-direct", true)] + [InlineData("direct-held", true)] + public void AListRendererReusedForASecondDocument_keepsTheGutterTheFirstWidthGave(string shape, bool clamped) + { + Func make = clamped ? ClampedGutterThatDependsOnTheWidth : GutterThatDependsOnTheWidth; + + var kept = SecondDocument(make, shape, twin: false); + + Assert.Equal(Sha(SecondDocument(make, shape, twin: true)), Sha(kept)); + Assert.NotEqual(Sha(FreshSecondDocument(make)), Sha(kept)); + } + + private static ListElement TwoItems() => new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem("one", H(10))) + .Add(new ListItem("two", H(10))); + + // The list is changed after the first document; the second must not read what changed. + private static void Change(ListElement list, string kind) + { + switch (kind) + { + case "plain": list.Add(new ListItem("added", H(10))); break; + case "child": list.Items[0].AddChild("child", H(10)); break; + case "undefined": + list.Add(new ListItem("added", new TextStyle { FontRef = new FontReference((Standard14)99), FontSize = 10 })); + break; + case "nan": + list.Add(new ListItem("added", new TextStyle + { + FontRef = new FontReference(Standard14.Helvetica), + FontSize = 10, + Color = new ColorRgb(double.NaN, 0, 0), + })); + break; + default: throw new ArgumentOutOfRangeException(nameof(kind)); + } + } + + // The second document's bytes after one renderer served a first document of 200 points and the + // list was changed, or was not, before the second. + private static byte[] SecondDocumentAfterChange( + Func make, string? kind, bool firstHeld, bool secondHeld, bool twin, double secondWidth = 200) + { + var list = make(); + var renderer = new ListRenderer(list); + IRenderer Use(bool held) => held ? new Passes(twin ? renderer.Unclamped() : renderer) : twin ? renderer.Unclamped() : renderer; + + var first = Page(200, 100, 1); + first.Add(Use(firstHeld)); + Save(first); + if (kind is not null) Change(list, kind); + var second = Page(secondWidth, 100, 1); + second.Add(Use(secondHeld)); + return Save(second); + } + + /// + /// A renderer whose list changed after the first document keeps the entries that document built + /// and never reads the change, as 2.3.3 did: an added item, an added child, an item in a font + /// the document cannot draw and an item with a colour that cannot be written leave the second + /// document the one an unchanged list gives. The references are the twin, which keeps the + /// entries it built, and the unchanged list. + /// + [Theory] + [InlineData("plain", false, false)] + [InlineData("plain", true, false)] + [InlineData("plain", false, true)] + [InlineData("child", false, false)] + [InlineData("child", true, false)] + [InlineData("undefined", false, false)] + [InlineData("undefined", true, false)] + [InlineData("undefined", false, true)] + [InlineData("nan", false, false)] + [InlineData("nan", true, false)] + [InlineData("nan", false, true)] + public void AListChangedBetweenTwoDocuments_isDrawnFromTheEntriesTheFirstBuilt( + string kind, bool firstHeld, bool secondHeld) + { + var kept = SecondDocumentAfterChange(TwoItems, kind, firstHeld, secondHeld, twin: false); + + Assert.Equal(["lead0", "1.", "one", "2.", "two"], Shows(kept)); + Assert.Equal(Sha(SecondDocumentAfterChange(TwoItems, null, firstHeld, secondHeld, twin: false)), Sha(kept)); + Assert.Equal(Sha(SecondDocumentAfterChange(TwoItems, kind, firstHeld, secondHeld, twin: true)), Sha(kept)); + } + + /// + /// An entry the first document's clamp narrowed is not an entry 2.3.3 built. The second + /// document lays it out as 2.3.3 built it in the first, from the text it had then and without + /// the clamp, and not from the list as it is now: a child added to the narrowed item moves + /// every entry after it, and an item added after it is not there. + /// + [Theory] + [InlineData("plain")] + [InlineData("child")] + public void AListChangedAfterTheClampNarrowedAnEntry_keepsTheEntryAsTheFirstDocumentBuiltItWithoutTheClamp(string kind) + { + ListElement Make() => ClampedAtTheFirstWidth().Add(new ListItem("second entry", H(10))); + + var kept = SecondDocumentAfterChange(Make, kind, false, false, twin: false, secondWidth: 400); + + Assert.Equal(Sha(SecondDocumentAfterChange(Make, null, false, false, twin: false, secondWidth: 400)), Sha(kept)); + Assert.Equal(Sha(SecondDocumentAfterChange(Make, kind, false, false, twin: true, secondWidth: 400)), Sha(kept)); + Assert.DoesNotContain(ClampedText, Shows(kept)); + Assert.DoesNotContain("added", Shows(kept)); + Assert.DoesNotContain("child", Shows(kept)); + } + + // A flat indent of 250 leaves the first document's 180-point area no text, so the clamp narrows + // the entry there, and the marker is 20 points where the text is 10. + private static ListElement ClampedWithATallMarker() => new ListElement(ListStyle.OrderedDecimal) { Indent = 250 } + .Add(new ListItem([new TextRun("small text", H(10))]) { Style = H(20) }); + + // The child's gutter is twice the indent, 200, which leaves the first document's 180-point + // area no text for the child, and 200 points in the second document's 400. + private static ListElement ClampedChild() + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 100 }; + list.Add(new ListItem("parent", H(10)).AddChild(string.Join(" ", Enumerable.Repeat("reused", 14)), H(10))); + return list; + } + + private static byte[] SecondDocumentWithLeads(Func make, bool twin, int leads) + { + var renderer = new ListRenderer(make()); + IRenderer Use() => twin ? renderer.Unclamped() : renderer; + + var first = Narrow(200); + first.Add(Use()); + Save(first); + var second = leads == 0 ? Narrow(400) : Page(400, 100, leads); + second.Add(Use()); + return Save(second); + } + + /// + /// The second document lays out an entry the first document's clamp narrowed as an entry no + /// clamp touched. A marker that does not fit what is left of a page and text that does are + /// drawn as the twin draws them, the text without the marker, and the clamp's rule that the + /// text of an entry whose marker is refused is refused too does not apply to it. + /// + [Fact] + public void AnEntryTheFirstDocumentsClampNarrowed_isNotHeldToTheClampsRuleInTheSecond() + { + var kept = SecondDocumentWithLeads(ClampedWithATallMarker, twin: false, leads: 5); + + Assert.Equal(Sha(SecondDocumentWithLeads(ClampedWithATallMarker, twin: true, leads: 5)), Sha(kept)); + Assert.Contains("small text", Shows(kept)); + } + + /// + /// The text the second document lays out for an entry the first document's clamp narrowed + /// carries the item's language into the structure tree, as the entry's text does where no clamp + /// narrowed it. + /// + [Fact] + public void AnEntryTheFirstDocumentsClampNarrowed_keepsItsLanguageInTheSecond() + { + byte[] Second(bool twin, string? language) + { + var renderer = new ListRenderer(new ListElement(ListStyle.OrderedDecimal) { Indent = 250 } + .Add(new ListItem(ClampedText, H(10)) { Language = language })); + IRenderer Use() => twin ? renderer.Unclamped() : renderer; + + var first = Narrow(200); + first.Add(Use()); + Save(first); + var second = new Document { Tagged = true, PageSize = new PdfRectangle(0, 0, 400, 300), Margins = new EdgeInsets(10) }; + second.Add(Use()); + return Save(second); + } + + var kept = Second(twin: false, "fr-FR"); + + Assert.Equal(Sha(Second(twin: true, "fr-FR")), Sha(kept)); + Assert.NotEqual(Sha(Second(twin: false, null)), Sha(kept)); + } + + /// + /// A reused list that the second document lays out as its twin because the document holds an + /// entry it cannot draw reports the entries the first document's clamp narrowed: they are the + /// entries the clamp would have narrowed, which the fallback reports as its count. + /// + [Fact] + public void AReusedListInADocumentThatHoldsAnUndrawableEntry_reportsTheEntriesTheFirstClampNarrowed() + { + var renderer = new ListRenderer(new ListElement(ListStyle.OrderedDecimal) { Indent = 250 } + .Add(new ListItem("first clamped entry", H(10))) + .Add(new ListItem("second clamped entry", H(10)))); + var first = Narrow(200); + first.Add(renderer); + Save(first); + Assert.Equal(2, first.Diagnostics.Single(d => d.Code == LayoutDiagnosticCode.ListIndentClamped).Count); + + var second = Narrow(400); + second.Add(renderer); + second.Add(new ListElement(ListStyle.Unordered) { Indent = 1000 } + .Add(new ListItem([new TextRun("bad", new TextStyle { FontRef = new FontReference((Standard14)99), FontSize = 10 })]) + { Style = H(10) })); + Save(second); + + var skipped = second.Diagnostics.Where(d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped).ToArray(); + Assert.Equal(2, skipped.Length); + Assert.Equal(2, skipped[0].Count); + } + + private static TextStyle Undefined() => new() { FontRef = new FontReference((Standard14)99), FontSize = 10 }; + + /// + /// A list reused for a second document keeps an entry in a font only the first document + /// defines. The second document finds that in the entries it keeps, so every list of the + /// second document is laid out as its twin, as 2.3.3 laid them out: a later list that would + /// move an entry is not moved. + /// + [Fact] + public void AReusedListWhoseKeptEntryUsesTheFirstDocumentsFont_makesEveryListOfTheSecondDocumentItsTwin() + { + byte[] Second(bool twinForTheSecondList) + { + var first = Page(200, 100, 4); + var style = new TextStyle { FontRef = first.UseTrueTypeFont(FontReportSupport.DejaVuBytes), FontSize = 10 }; + var renderer = new ListRenderer(new ListElement(ListStyle.Unordered) { Indent = 1000 } + .Add(new ListItem([new TextRun("embedded", style)]) { Style = H(10) })); + first.Add(renderer); + Save(first); + var second = Page(200, 100, 4); + second.Add(new Passes(renderer)); + var tall = new ListRenderer(TallTextEntry()); + second.Add(twinForTheSecondList ? tall.Unclamped() : tall); + return Save(second); + } + + var kept = Second(twinForTheSecondList: false); + + Assert.Equal(Sha(Second(twinForTheSecondList: true)), Sha(kept)); + Assert.DoesNotContain("dropped", Shows(kept)); + } + + /// + /// A child the first document's clamp narrowed keeps the gutter it has without the clamp, twice + /// the indent, in the second document, where that gutter leaves it text. + /// + [Fact] + public void AChildTheFirstDocumentsClampNarrowed_keepsItsGutterInTheSecond() + { + var kept = SecondDocumentWithLeads(ClampedChild, twin: false, leads: 0); + + Assert.Equal(Sha(SecondDocumentWithLeads(ClampedChild, twin: true, leads: 0)), Sha(kept)); + } + + // An entry whose text is 20 points in a 10-point style: it fits a page top, and not what is + // left of a short page after a few lines. + private static ListElement TallTextEntry() => new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("dropped", H(20))]) { Style = H(10) }) + .Add(new ListItem("next", H(10))); + + /// + /// A renderer added to a document and then held by a renderer of the caller's, in the same + /// document, lays the second placement out from the entries the first one built, as a list laid + /// out as it was before the fixes does. Here the second placement falls where the entry's text + /// does not fit, and the paragraph draws the lines of its last layout there: the entry's text + /// shows twice, once at each place. That is a stale placement the list had before the fixes + /// (#691), and this change leaves it as it was. + /// + [Fact] + public void ARendererAddedAndThenHeldInOneDocument_laysTheHeldOneOutFromTheEntriesItBuilt() + { + Document Build(ListRenderer renderer) + { + var doc = Page(200, 100); + doc.Add(renderer); + doc.Add(new Paragraph("between0", H(10)) { Margins = EdgeInsets.Zero }); + doc.Add(new Paragraph("between1", H(10)) { Margins = EdgeInsets.Zero }); + doc.Add(new Passes(renderer)); + return doc; + } + + var reused = Save(Build(new ListRenderer(TallTextEntry()))); + + Assert.Equal(Sha(Save(Build(new ListRenderer(TallTextEntry()).Unclamped()))), Sha(reused)); + Assert.Equal(2, Shows(reused).Count(t => t == "dropped")); + } + + /// + /// A list renderer reused for a second document reports nothing there, as one that a caller + /// laid out before the save: the document did not place the list the way it placed it first. + /// + [Fact] + public void AListRendererReusedForASecondDocument_reportsNothingThere() + { + var renderer = new ListRenderer(ClampedAtTheFirstWidth()); + var first = Narrow(200); + first.Add(renderer); + Save(first); + Assert.Contains(LayoutDiagnosticCode.ListIndentClamped, Codes(first)); + + var second = Narrow(400); + second.Add(renderer); + Save(second); + + Assert.DoesNotContain(second.Diagnostics, d => d.Code is LayoutDiagnosticCode.ListIndentClamped + or LayoutDiagnosticCode.ListIndentClampSkipped or LayoutDiagnosticCode.ListEntryPartDropped); + } + + /// + /// A list changed after the first document that holds it saved, or after a caller laid it out + /// before the save, is not measured again for the second. The list lays out as its twin, which + /// holds the entries built before, as the save does. Measuring an item added since would add + /// its glyphs to the font subset, which a document that never reads that item must not hold. + /// + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public void AListChangedAfterTheFirstDocument_addsNoGlyphToTheSecondDocumentsSubset(bool child, bool laidOut) + { + byte[] Second(bool twin, bool changed) + { + var first = new Document { PageSize = new PdfRectangle(0, 0, 300, 200), Margins = new EdgeInsets(10) }; + var firstStyle = new TextStyle { FontRef = first.UseTrueTypeFont(FontReportSupport.DejaVuBytes), FontSize = 10 }; + var list = new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem("abc", firstStyle)) + .Add(new ListItem("abc", firstStyle)); + var renderer = new ListRenderer(list); + IRenderer Use() => twin ? renderer.Unclamped() : renderer; + first.Add(Use()); + if (laidOut) Use().Layout(new LayoutContext(new LayoutBox(10, 10, 280, 180))); + else Save(first); + + if (changed && child) list.Items[0].AddChild(new ListItem("QJKXYZ", firstStyle)); + else if (changed) list.Add(new ListItem("QJKXYZ", firstStyle)); + + var second = new Document { PageSize = new PdfRectangle(0, 0, 300, 200), Margins = new EdgeInsets(10) }; + var secondStyle = new TextStyle { FontRef = second.UseTrueTypeFont(FontReportSupport.DejaVuBytes), FontSize = 10 }; + second.Add(Use()); + second.Add(new Counts()); + second.Add(new Paragraph("after", secondStyle)); + return Save(second); + } + + var kept = Second(twin: false, changed: true); + + Assert.Equal(Sha(Second(twin: true, changed: true)), Sha(kept)); + Assert.Equal(Sha(Second(twin: false, changed: false)), Sha(kept)); + } + + /// A caller's renderer that takes no room and draws nothing. + private sealed class TakesNoRoom : IRenderer + { + public LayoutResult Layout(LayoutContext context) => + LayoutResult.Full(new LayoutBox(context.Area.X, context.Area.Y, 1, 0)); + + public void Draw(DrawContext ctx) + { + } + } + + /// + /// A renderer of the caller's after a list makes the second document lay every list out as its + /// twin, a reused renderer's among them, and the entries of that renderer are the ones the + /// first document's save, or a layout the caller made before it, built. A renderer that takes + /// no room is the whole of the difference between the two documents, so the document that + /// holds it equals the one whose lists are all replaced by their twins. + /// + [Theory] + [InlineData("tall text", 60, 4, 1, false)] + [InlineData("tall text", 72, 5, 2, false)] + [InlineData("tall marker", 64, 4, 1, false)] + [InlineData("tall marker", 76, 5, 2, false)] + [InlineData("tall text", 60, 4, 1, true)] + [InlineData("tall marker", 76, 5, 2, true)] + public void ACallersRenderer_laysAReusedRenderersEntriesOutAsItsTwin( + string kind, double height, int leads, int mid, bool laidOut) + { + ListElement List() => kind == "tall text" + ? TallTextEntry() + : new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("small text", H(10))]) { Style = H(20) }) + .Add(new ListItem("next", H(10))); + + byte[] Second(bool withCaller) + { + var renderer = new ListRenderer(List()); + IRenderer Use() => withCaller ? renderer : renderer.Unclamped(); + var first = Page(200, height + 20); + if (laidOut) + { + renderer.Layout(new LayoutContext(new LayoutBox(10, 10, 180, height))); + } + else + { + first.Add(renderer); + Save(first); + } + + var second = Page(200, height + 20, leads); + if (withCaller) second.Add(List()); + else second.Add(new ListRenderer(List()).Unclamped()); + for (var i = 0; i < mid; i++) second.Add(new Paragraph("mid" + i, H(10)) { Margins = EdgeInsets.Zero }); + second.Add(Use()); + if (withCaller) second.Add(new TakesNoRoom()); + return Save(second); + } + + Assert.Equal(Sha(Second(withCaller: false)), Sha(Second(withCaller: true))); + } + + /// + /// The document places the same object in the measuring pass and the drawing pass. + /// + [Fact] + public void TheTwin_isTheSameObjectOnEveryCall() + { + var renderer = new ListRenderer(new ListElement(ListStyle.OrderedDecimal).Add("a")); + + Assert.Same(((IContinuationTwin)renderer).Twin(), ((IContinuationTwin)renderer).Twin()); + Assert.Same(renderer.Unclamped(), ((IContinuationTwin)renderer).Twin()); + } + + // ── A first box with no height ─────────────────────────────────────────── + + /// + /// A paragraph whose leading fills the 20-point area leaves the list a box with no height, + /// which it answers Nothing for before it builds an item. The decision is made at the retry on + /// the next page, where the list reports, so the list that would pass the limit is placed as it + /// was. + /// + [Fact] + public void AListFirstOfferedNoHeight_isDecidedAtTheRetry() + { + Run Place(bool twin) + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 }; + list.Add(new ListItem(string.Join(" ", Enumerable.Repeat("W", 102)), H(10))); + var pdf = new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, 40), new EdgeInsets(10)) { ContinuationLimit = 100 }; + renderer.Add(new ParagraphRenderer( + new Paragraph("lead", new TextStyle { FontSize = 10, Leading = 20 }) { Margins = EdgeInsets.Zero })); + renderer.Add(twin ? new ListRenderer(list).Unclamped() : new ListRenderer(list)); + using var ms = new MemoryStream(); + renderer.Render(ms); + return new Run(ms.ToArray(), renderer.Diagnostics); + } + + var run = Place(twin: false); + var twin = Place(twin: true); + + Assert.Equal(Sha(twin.Bytes), Sha(run.Bytes)); + Assert.Contains(run.Diagnostics, d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped); + Assert.DoesNotContain("W", Shows(run.Bytes)); + } + + // ── What cannot be drawn keeps its layout ──────────────────────────────── + + private static EmbeddedFontHandle ForeignHandle() => new Document().UseTrueTypeFont(FontReportSupport.DejaVuBytes); + + private static TextStyle StyleOf(FontReference font, double size = 10) => new() { FontRef = font, FontSize = size }; + + /// + /// A run in an embedded font that another document returned would be refused at the save once + /// its text is drawn, and the document never drew it. The document holds an entry it cannot + /// draw, so its list is laid out as its twin, the save is the one the list had, and the + /// fallback is reported. + /// + [Theory] + [InlineData("foreign-handle")] + [InlineData("undefined-standard14")] + public void AnEntryWithARunThatCannotBeDrawn_isNotClamped(string kind) + { + FontReference font = kind == "foreign-handle" ? ForeignHandle() : (Standard14)99; + var (bytes, doc, twin, _) = Both( + () => Page(200, 400), + () => new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 } + .Add(new ListItem([new TextRun("abc", StyleOf(font))]) { Style = H(10) })); + + Assert.Equal(Sha(twin), Sha(bytes)); + Assert.Equal([LayoutDiagnosticCode.ListIndentClampSkipped], Codes(doc)); + } + + /// + /// The same entry at a page bottom: main dropped the text mid-page and saved. The entry is not + /// moved, because drawing it on the next page would refuse the save, and the part dropped is + /// reported. + /// + [Theory] + [InlineData("foreign-handle")] + [InlineData("undefined-standard14")] + public void AnEntryWithARunThatCannotBeDrawn_isNotMoved(string kind) + { + FontReference font = kind == "foreign-handle" ? ForeignHandle() : (Standard14)99; + var (bytes, doc, twin, _) = Both( + () => Page(200, 100, leadLines: 5), + () => new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("dropped", StyleOf(font, 20))]) { Style = H(10) }) + .Add(new ListItem("next", H(10)))); + + Assert.Equal(Sha(twin), Sha(bytes)); + Assert.Equal(["lead0", "lead1", "lead2", "lead3", "lead4", "1.", "2.", "next"], Shows(bytes)); + Assert.Equal( + [LayoutDiagnosticCode.ListIndentClampSkipped, LayoutDiagnosticCode.ListEntryPartDropped], Codes(doc)); + } + + /// + /// A marker in a font that cannot be drawn is not moved onto a page either, where the entry + /// would otherwise move for it. + /// + [Fact] + public void AnEntryWhoseMarkerStyleCannotBeDrawn_isNotMoved() + { + var (bytes, _, twin, _) = Both( + () => Page(200, 100, leadLines: 2), + () => new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("abc", H(10))]) { Style = StyleOf((Standard14)99, 60) })); + + Assert.Equal(Sha(twin), Sha(bytes)); + } + + /// The same two rules for a nested child, whose entry is its own. + [Theory] + [InlineData("clamp")] + [InlineData("move")] + public void AChildWithARunThatCannotBeDrawn_isNeitherClampedNorMoved(string rule) + { + // An undefined Standard 14 value measures zero, which the clamp never narrows, so the clamp + // row uses a handle another document returned, which measures. + var undefined = rule == "move" ? StyleOf((Standard14)99, 20) : StyleOf(ForeignHandle()); + var (bytes, doc, twin, _) = Both( + () => rule == "move" ? Page(200, 100, leadLines: 4) : Page(400, 400), + () => + { + var parent = new ListItem("p", H(10)); + parent.AddChild(new ListItem([new TextRun("abc", undefined)]) { Style = H(10) }); + return new ListElement(ListStyle.OrderedDecimal) { Indent = rule == "move" ? 20 : 200 }.Add(parent); + }); + + Assert.Equal(Sha(twin), Sha(bytes)); + Assert.DoesNotContain(LayoutDiagnosticCode.ListIndentClamped, Codes(doc)); + } + + /// + /// The control: a font this document defines is drawn, so the entry is clamped and moved. + /// + [Fact] + public void AnEntryWithARunThisDocumentDefines_isStillClampedAndMoved() + { + var doc = Page(200, 100, leadLines: 5); + var font = doc.UseTrueTypeFont(FontReportSupport.DejaVuBytes); + doc.Add(new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 } + .Add(new ListItem([new TextRun("dropped", StyleOf(font, 20))]) { Style = H(10) })); + + var bytes = Save(doc); + + Assert.Contains(LayoutDiagnosticCode.ListIndentClamped, Codes(doc)); + Assert.Contains("1.", Shows(bytes)); + } + + /// + /// An entry at a page top is never moved: moving it answers Nothing for the list, and the retry + /// offers the same top. Every entry fits a page of its own where the document lays the list + /// out, so the document never offers a top that is smaller than that page, but a context that + /// does leaves the entry where it falls. + /// + [Fact] + public void AnEntryAtAPageTopThatDoesNotFitItsBox_isNotMoved() + { + var renderer = new ListRenderer(new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("dropped", H(20))]) { Style = H(10) })); + var context = new LayoutContext(new LayoutBox(0, 0, 200, 20)) + { + FreshPageArea = new LayoutBox(0, 0, 200, 100), + AtPageTop = true, + Session = new ContinuationSession(ContinuationMode.New) { Called = renderer }, + }; + + var result = renderer.Layout(context); + + Assert.Equal(LayoutResult.Outcome.Full, result.Status); + } + + // ── An entry no page holds ─────────────────────────────────────────────── + + // An entry the new layout would move, followed by one whose marker is taller than a page. + private static ListElement MovesThenNoPageHolds() => + new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("dropped", H(20))]) { Style = H(10) }) + .Add(new ListItem([new TextRun("abc", H(10))]) { Style = H(500) }); + + /// + /// When any entry of a list fits no page, the whole list is placed as it was: the entry that + /// would have moved is placed where it falls, and the output is the twin's. + /// + [Fact] + public void AListWithAnEntryNoPageHolds_isPlacedAsBeforeWhole() + { + var (bytes, doc, twin, twinDoc) = Both(() => Page(200, 100, leadLines: 5), MovesThenNoPageHolds); + + Assert.Equal(Sha(twin), Sha(bytes)); + Assert.Equal([LayoutDiagnosticCode.ListEntryPartDropped], Codes(doc)); + Assert.Equal(2, Assert.Single(doc.Diagnostics).Count); + Assert.Equal(Codes(twinDoc), Codes(doc)); + } + + /// + /// The list the document calls answers with its twin's layout, and the document asks the + /// instance it called for the placements of the list's anchors and of its items'. Both come + /// from the twin, so the destinations are the ones the twin writes. + /// + [Fact] + public void AListWithAnEntryNoPageHolds_keepsTheAnchorsItsTwinReports() + { + // A list that comes back Full is asked for its placements on the instance the document + // called, which answers for the twin. + var (bytes, _, twin, _) = Both( + () => Page(400, 400), + () => new ListElement(ListStyle.OrderedDecimal) { Indent = 300, Anchor = "whole-list" } + .Add(new ListItem([new TextRun("big", H(500))]) { Style = H(10), Anchor = "first-item" })); + + Assert.Equal(Sha(twin), Sha(bytes)); + var text = System.Text.Encoding.Latin1.GetString(bytes); + Assert.Contains("whole-list", text, StringComparison.Ordinal); + Assert.Contains("first-item", text, StringComparison.Ordinal); + } + + /// + /// A marker that wraps and gets only some of its lines on a page of its own is an entry no page + /// holds, so an entry ahead of it that would move stays where it falls, and the list is placed + /// as before. + /// + [Fact] + public void AMarkerTallerThanAPageThatWraps_isAnEntryNoPageHolds() + { + var (bytes, doc, twin, _) = Both( + () => Page(60, 100, leadLines: 5), + () => new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("a", H(20))]) { Style = H(10) }) + .Add(new ListItem("x", H(10)) { Style = H(60) })); + + Assert.Equal(Sha(twin), Sha(bytes)); + Assert.Contains(LayoutDiagnosticCode.ListEntryPartDropped, Codes(doc)); + } + + /// + /// A clamped entry whose clamped line is taller than a page fits no page, so the list keeps its + /// earlier layout whole and reports no clamp. + /// + [Fact] + public void AClampedLineTallerThanAPage_leavesTheListUnclamped() + { + var (bytes, doc, twin, _) = Both( + () => Page(400, 400), + () => new ListElement(ListStyle.OrderedDecimal) { Indent = 300 } + .Add(new ListItem([new TextRun("big", H(500))]) { Style = H(10) })); + + Assert.Equal(Sha(twin), Sha(bytes)); + Assert.Equal([LayoutDiagnosticCode.ListEntryPartDropped], Codes(doc)); + } + + /// + /// Only that list keeps its earlier layout. Another list in the document is still clamped and + /// its entries are still moved. + /// + [Fact] + public void AnotherListInTheDocument_keepsTheFixes() + { + var doc = Page(200, 100, leadLines: 5); + doc.Add(MovesThenNoPageHolds()); + doc.Add(new PageBreak()); + for (var i = 0; i < 5; i++) doc.Add(new Paragraph("again" + i, H(10)) { Margins = EdgeInsets.Zero }); + doc.Add(new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("moved", H(20))]) { Style = H(10) })); + + var shows = Shows(Save(doc)); + + Assert.Contains("moved", shows); + Assert.DoesNotContain("dropped", shows); + Assert.Equal([LayoutDiagnosticCode.ListEntryPartDropped], Codes(doc)); + } + + /// + /// Text with no width is discarded, not unplaced: an entry whose marker wraps and gets some of + /// its lines mid-page, beside text with no width, moves to the page that holds the marker + /// whole. + /// + [Fact] + public void AMarkerThatGetsSomeOfItsLines_besideTextWithNoWidth_moves() + { + var doc = Page(200, 100, leadLines: 3); + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 170 }; + var item = new ListItem("p", H(10)); + item.AddChild(new ListItem([new TextRun(" ", H(10))]) { Style = H(20) }); + list.Add(item); + list.Add(new ListItem("q", H(10))); + doc.Add(list); + + var bytes = Save(doc); + + Assert.Equal(["lead0", "lead1", "lead2", "1.", "p", "1", ".", "2.", "q"], Shows(bytes)); + Assert.DoesNotContain(LayoutDiagnosticCode.ListEntryPartDropped, Codes(doc)); + } + + // ── What the analysis reads early ──────────────────────────────────────── + + /// + /// A list reads every entry before it places the first, to find one no page holds. A refusal an + /// entry raises is the layout's to raise where it reached it, so the refusal the list reports + /// is the one it always did: an element too tall, before the colour of a later entry. + /// + [Fact] + public void ARefusalALaterEntryRaises_doesNotReplaceTheOneAnEarlierEntryRaisesFirst() + { + ListElement List() => new ListElement(ListStyle.OrderedDecimal) + .Add(new ListItem([new TextRun("abc", H(500))]) { Style = H(500) }) + .Add(new ListItem([new TextRun("abc", new TextStyle { FontSize = 10, Color = new ColorRgb(double.NaN, 0, 0) })]) { Style = H(10) }); + + var twin = Page(200, 100); + twin.Add(new ListRenderer(List()).Unclamped()); + var expected = Assert.Throws(() => Save(twin)); + var doc = Page(200, 100); + doc.Add(List()); + + var actual = Assert.Throws(() => Save(doc)); + + Assert.Equal(expected.Message, actual.Message); + Assert.StartsWith("An element is too tall", actual.Message, StringComparison.Ordinal); + } + + // ── Mirrored margins ───────────────────────────────────────────────────── + + /// + /// The verdict at the limit does not depend on x, so unequal mirrored margins decide the same + /// list as equal ones do. + /// + [Theory] + [InlineData(100, false)] + [InlineData(102, true)] + public void TheVerdictAtTheLimit_doesNotDependOnMirroredMargins(int words, bool skipped) + { + var list = new ListElement(ListStyle.OrderedDecimal) { Indent = 1000 }; + list.Add(new ListItem(string.Join(" ", Enumerable.Repeat("W", words)), H(10))); + var pdf = new PdfDocument { Timestamp = Stamp, DocumentId = new byte[16] }; + var renderer = new DocumentRenderer(pdf, new PdfRectangle(0, 0, 200, 40), new EdgeInsets(10, 30, 10, 10)) + { + ContinuationLimit = 100, + MirrorMargins = true, + }; + renderer.Add(new ListRenderer(list)); + + using var ms = new MemoryStream(); + renderer.Render(ms); + + Assert.Equal(skipped, renderer.Diagnostics.Any(d => d.Code == LayoutDiagnosticCode.ListIndentClampSkipped)); + } + + // ── Helpers ────────────────────────────────────────────────────────────── + + private sealed record Run(byte[] Bytes, IReadOnlyList Diagnostics); + + /// + /// A renderer of a caller's that lays another renderer out, through the context or through one + /// it makes. + /// + private sealed class PassOn(IRenderer inner, int how) : IRenderer + { + public LayoutResult Layout(LayoutContext context) => inner.Layout(how switch + { + 0 => context, + 1 => context.WithArea(context.Area), + _ => new LayoutContext(context.Area, context.ContentTop), + }); + + public void Draw(DrawContext ctx) => inner.Draw(ctx); + } + + /// + /// Reserves a band above the renderer it wraps and lays that out in the rest through + /// WithArea. + /// + private sealed class Inset(IRenderer inner, double top) : IRenderer + { + public LayoutResult Layout(LayoutContext context) + { + var area = context.Area; + var rest = new LayoutBox(area.X, area.Y + top, area.Width, area.Height - top); + var result = inner.Layout(context.WithArea(rest)); + return result.Status == LayoutResult.Outcome.Full + ? LayoutResult.Full(new LayoutBox(area.X, area.Y, area.Width, top + result.OccupiedArea!.Value.Height)) + : result; + } + + public void Draw(DrawContext ctx) => inner.Draw(ctx); + } +} diff --git a/tests/VellumPdf.Layout.Tests/ParagraphLineCountAtTests.cs b/tests/VellumPdf.Layout.Tests/ParagraphLineCountAtTests.cs new file mode 100644 index 000000000..d97ee253e --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/ParagraphLineCountAtTests.cs @@ -0,0 +1,70 @@ +// 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.Rendering; + +namespace VellumPdf.Layout.Tests; + +/// +/// says how many lines +/// wraps a paragraph into for a box of a given width, so it +/// must take off the margins on both sides. The list's own content paragraphs have a left margin +/// only, which leaves the right one unread by every list row. +/// +public sealed class ParagraphLineCountAtTests +{ + private static readonly TextStyle Style = new() { FontRef = new FontReference(Standard14.Helvetica), FontSize = 10 }; + + private const string Text = "alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima"; + + private static int LinesLaidOut(Paragraph paragraph, double boxWidth) + { + var result = new ParagraphRenderer(paragraph).Layout(new LayoutContext(new LayoutBox(0, 0, boxWidth, 10_000))); + Assert.Equal(LayoutResult.Outcome.Full, result.Status); + return (int)Math.Round(result.OccupiedArea!.Value.Height / Style.EffectiveLeading); + } + + [Theory] + [InlineData(0.0, 0.0)] + [InlineData(40.0, 0.0)] + [InlineData(0.0, 60.0)] + [InlineData(25.0, 70.0)] + public void TheCountIsTheLinesLayoutWraps_atEveryMargin(double left, double right) + { + Paragraph Make() => new(Text, Style) { Margins = new EdgeInsets(0, right, 0, left) }; + + foreach (var box in new[] { 120.0, 200.0, 300.0 }) + { + var expected = LinesLaidOut(Make(), box); + Assert.Equal(expected, new ParagraphRenderer(Make()).LineCountAt(box)); + } + } + + /// + /// The fixture tells the margins apart: the same text wraps into more lines when a right margin + /// narrows it, so a count that read only the left margin would not equal the one above. + /// + [Fact] + public void ARightMargin_changesTheCount() + { + var without = new ParagraphRenderer(new Paragraph(Text, Style) { Margins = EdgeInsets.Zero }).LineCountAt(200); + var with = new ParagraphRenderer(new Paragraph(Text, Style) { Margins = new EdgeInsets(0, 70, 0, 0) }).LineCountAt(200); + + Assert.True(with > without, $"{with} lines with a right margin, {without} without"); + } + + [Theory] + [InlineData(50.0, 0.0, 50.0)] + [InlineData(0.0, 50.0, 50.0)] + [InlineData(20.0, 40.0, 60.0)] + public void ABoxTheMarginsFill_hasNoLines(double left, double right, double box) + { + var renderer = new ParagraphRenderer(new Paragraph(Text, Style) { Margins = new EdgeInsets(0, right, 0, left) }); + + Assert.Equal(0, renderer.LineCountAt(box)); + } +}