diff --git a/CHANGELOG.md b/CHANGELOG.md index abbf0981..754656a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -128,6 +128,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - In a tagged document each drawn piece is one `P` structure element. Nothing in the character stream separates two lines. Documents without the element save to the same bytes as before. +- **`Preformatted.Anchor`, a code block can be a link target (#693).** The property has the name + rule, the refusals and the named destination of `Paragraph.Anchor`: a name of 1 to 127 + characters from `A-Z a-z 0-9 . _ - :` is accepted, any other name throws `ArgumentException` from + the `init` accessor, and the save adds `[page /XYZ 0 top null]` to the `/Names` `/Dests` tree at + the top of the block's first line, below its top margin. A block that splits across pages reports the anchor + from its first piece only, so the destination is on the page the first line is on. + - A name held by a `Preformatted` and by another element of any kind is refused like a name held + by two paragraphs: the save throws `InvalidOperationException` before any layout, naming both + elements, and the document stays saveable. + - A block with no anchor saves to the same bytes as before. + - **Page labels and anchors (#262, Layout).** A document can set the page numbers a viewer shows, and name places that other documents and links can open it at. - `PageLabelRange(style, prefix, firstNumber)` describes a run of pages: decimal, upper or lower diff --git a/src/VellumPdf.Layout/Elements/Paragraph.cs b/src/VellumPdf.Layout/Elements/Paragraph.cs index 5ff03ddb..dc75c06f 100644 --- a/src/VellumPdf.Layout/Elements/Paragraph.cs +++ b/src/VellumPdf.Layout/Elements/Paragraph.cs @@ -309,9 +309,10 @@ public int MinLinesAfterBreak /// raised from the save, not from this property, as /// naming top, when the destination's top is not finite or lies beyond ±3.403 × 10^38, /// the range of a PDF real (ISO 32000-1, Table C.1): a top margin below -3.403 × 10^38 or equal - /// to negative infinity on a paragraph or heading, and also NaN on an image. A paragraph with a - /// NaN top margin never gets that far: it is refused as too tall to fit, anchored or not. The - /// layout had started, so the document cannot be saved again. + /// to negative infinity on a paragraph or heading, and also NaN on an image. A page taller than + /// 3.403 × 10^38 points raises it as well. A paragraph with a NaN top margin never gets that + /// far: it is refused as too tall to fit, anchored or not. The layout had started, so the + /// document cannot be saved again. /// /// /// Raised from the save, not from this property, when another element in the document holds the diff --git a/src/VellumPdf.Layout/Elements/Preformatted.cs b/src/VellumPdf.Layout/Elements/Preformatted.cs index dad9e682..a0a880dd 100644 --- a/src/VellumPdf.Layout/Elements/Preformatted.cs +++ b/src/VellumPdf.Layout/Elements/Preformatted.cs @@ -56,8 +56,8 @@ namespace VellumPdf.Layout.Elements; /// refuses that save. /// What is ignored. does not apply, as for lists /// and tables. Alignment, justification and hyphenation do not exist on this element. A paragraph -/// tab stop does not apply: a tab is a number of spaces. No language is written for the block. The -/// element is not a target of an anchor. +/// tab stop does not apply: a tab is a number of spaces. No language is written for the +/// block. /// In a tagged document each drawn piece, the part of the block on one page, is one P /// structure element. Nothing in the character stream separates two lines, so a reader that follows /// the structure order alone sees the lines run together. @@ -176,6 +176,53 @@ public PageBreakMode BreakBefore init => _breakBefore = PageBreakModes.Validate(value); } + /// + /// A name that a link or an outside reference can jump to: the save adds a named destination at + /// the first line of this block. , the default, adds none. + /// + /// + /// A name outside the rule is refused by this init accessor. It throws + /// for an empty name, one longer than 127 characters, or one + /// with a character outside A-Z a-z 0-9 . _ - :, as does, + /// and for the same reason. + /// A repeated anchor is refused by the save, before any layout. The save throws + /// naming the anchor and the kind and zero-based + /// position of both elements that hold it, whatever their kinds: a paragraph and a block + /// holding one name are refused as two paragraphs are. Nothing has been laid out then, so the + /// document can be saved once the elements are replaced. The same instance added twice holds + /// its anchor twice. + /// The destination is written whether or not a link refers to it, so a reader can open + /// the file at it by name (file.pdf#nameddest=name). Its position is the top edge of the + /// block's first line, below , at the left edge of the page, with the + /// viewer's zoom unchanged. When the block splits across pages, that is the page its first + /// line is on, and no later piece reports the anchor. The destinations are written in the + /// order of their names, so the order the elements were added in does not change a key. + /// Names are compared byte by byte, so Code and code are two destinations, + /// as they are on . + /// + /// + /// Raised from this init accessor when the name breaks the rule above. + /// + /// + /// Raised from the save, not from this property, naming top, when the page is taller + /// than 3.403 × 10^38 points: the destination's top is then beyond the range of a PDF real + /// (ISO 32000-1, Table C.1). cannot cause it, because it refuses a + /// negative or non-finite edge. A page of exactly 3.403 × 10^38 saves, and the same block with + /// no anchor saves on a taller page. The layout had started, so the document cannot be saved + /// again. + /// + /// + /// Raised from the save, not from this property, before any layout, when another element in + /// the document holds the same anchor. + /// + public string? Anchor + { + get => _anchor; + init => _anchor = AnchorNames.Validate(value); + } + + private string? _anchor; + /// Creates a block from a string, in the given style or in Courier at 10 pt. /// /// This constructor refuses a null text, a refused character and a refused style. It diff --git a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt index be3c4f41..62dce73c 100644 --- a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt +++ b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt @@ -90,6 +90,8 @@ VellumPdf.Layout.LayoutDiagnosticCode.NotdefGlyph = 102 -> VellumPdf.Layout.Layo VellumPdf.Layout.LayoutDiagnosticCode.UnembeddedFont = 601 -> VellumPdf.Layout.LayoutDiagnosticCode VellumPdf.Layout.Document.Add(VellumPdf.Layout.Elements.Preformatted! preformatted) -> VellumPdf.Layout.Document! VellumPdf.Layout.Elements.Preformatted +VellumPdf.Layout.Elements.Preformatted.Anchor.get -> string? +VellumPdf.Layout.Elements.Preformatted.Anchor.init -> void VellumPdf.Layout.Elements.Preformatted.BreakBefore.get -> VellumPdf.Layout.Core.PageBreakMode VellumPdf.Layout.Elements.Preformatted.BreakBefore.init -> void VellumPdf.Layout.Elements.Preformatted.Margins.get -> VellumPdf.Layout.Core.EdgeInsets diff --git a/src/VellumPdf.Layout/Rendering/NavigationPlan.cs b/src/VellumPdf.Layout/Rendering/NavigationPlan.cs index 0611cd26..1e9d19b8 100644 --- a/src/VellumPdf.Layout/Rendering/NavigationPlan.cs +++ b/src/VellumPdf.Layout/Rendering/NavigationPlan.cs @@ -63,6 +63,9 @@ internal static NavigationPlan Build(IReadOnlyList renderers) case LayoutImageRenderer image: plan.Add(image.Element.Anchor, LayoutElementKind.Image, i); break; + case PreformattedRenderer block: + plan.Add(block.Element.Anchor, LayoutElementKind.Preformatted, i); + break; case ListRenderer list: plan.WalkList(list.Element, i, ref deep); break; diff --git a/src/VellumPdf.Layout/Rendering/PreformattedRenderer.cs b/src/VellumPdf.Layout/Rendering/PreformattedRenderer.cs index 8c24f0d6..c80eacbb 100644 --- a/src/VellumPdf.Layout/Rendering/PreformattedRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/PreformattedRenderer.cs @@ -19,7 +19,7 @@ namespace VellumPdf.Layout.Rendering; /// Both passes lay out the same cached lines and read no pagination plan, so the measuring pass and /// the drawing pass agree by construction. /// -internal sealed class PreformattedRenderer : IRenderer, IPageBreakSource +internal sealed class PreformattedRenderer : IRenderer, IPageBreakSource, IPlacementSource { // The continuation marker is a hook drawn with two open subpaths inside one column, 0.6 em wide // (the width the wrap reserves, PreformattedText.MarkerUnits), between the baseline and the cap @@ -69,6 +69,16 @@ internal PreformattedRenderer(Preformatted element, int startLine = 0) PageBreakMode IPageBreakSource.BreakBefore => _element.BreakBefore; + // Explicit, as in the other renderers. The anchor lands where the first line does, so only the + // piece that starts at line 0 reports it; the overflow of a split block starts later and + // reports nothing, which keeps the destination on the page the first line is on. The box is + // the occupied area, whose top is the top of the first line. + void IPlacementSource.ReportPlacements(PlacementSink sink) + { + if (_startLine == 0 && _element.Anchor is { } anchor) + sink.ReportAnchor(_element, anchor, _occupied); + } + public LayoutResult Layout(LayoutContext context) { var area = context.Area.Deflate(_element.Margins); diff --git a/tests/VellumPdf.Layout.Tests/PreformattedAnchorTests.cs b/tests/VellumPdf.Layout.Tests/PreformattedAnchorTests.cs new file mode 100644 index 00000000..67761ecd --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/PreformattedAnchorTests.cs @@ -0,0 +1,295 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Globalization; +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Reader; +using VellumPdf.TestSupport; +using static VellumPdf.Layout.Tests.PlacementLoopSupport; + +namespace VellumPdf.Layout.Tests; + +/// +/// Preformatted.Anchor: the named destination of a code block. A page is 300 x 300 pt with +/// 20 pt margins, so the content box is 260 pt high and holds 21 lines of the default 12 pt +/// leading. Expected positions are worked out from that geometry, not read back from the file. +/// +public sealed class PreformattedAnchorTests +{ + private const double Leading = 12; + + private static readonly double TopOfPage = Page.Height - Margins.Top; + + private static Document NewDocument() => new() { PageSize = Page, Margins = Margins }; + + private static string Lines(int count) => string.Join('\n', Enumerable.Range(1, count).Select(i => $"line {i}")); + + private static byte[] Save(Document doc) + { + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + private sealed record Dest(int Page, double Left, double Top); + + // The name tree and the destinations it names, read from the file text. Page numbers are + // 0-based and follow the page tree's /Kids order. + private static Dictionary Dests(byte[] pdf) + { + var text = Regex.Replace(System.Text.Encoding.Latin1.GetString(pdf), @"\s+", " "); + var kids = Regex.Match(text, @"/Kids \[([^\]]*)\]").Groups[1].Value; + var pageOf = new Dictionary(); + foreach (Match kid in Regex.Matches(kids, @"(\d+) 0 R")) + pageOf[int.Parse(kid.Groups[1].Value, CultureInfo.InvariantCulture)] = pageOf.Count; + + var result = new Dictionary(StringComparer.Ordinal); + var names = Regex.Match(text, @"/Dests << /Names \[(.*?)\]").Groups[1].Value; + foreach (Match pair in Regex.Matches(names, @"\(([^)]*)\) (\d+) 0 R")) + { + var obj = Regex.Match( + text, + @"(? PdfinfoDests(string path) + { + if (!ExternalTool.TryRun("pdfinfo", ["-dests", path], out var exit, out var stdout, out var stderr, out var timedOut)) + OracleGate.Unavailable("pdfinfo"); + Assert.False(timedOut); + Assert.True(exit == 0, $"pdfinfo -dests exit {exit}\n{stdout}\n{stderr}"); + var result = new List<(int, double, string)>(); + foreach (var line in stdout.Split('\n', StringSplitOptions.TrimEntries)) + { + var m = Regex.Match(line, @"^(\d+)\s+\[\s*XYZ\s+(\S+)\s+(\S+)\s+null\s*\]\s+""([^""]*)""$"); + if (m.Success) + { + result.Add(( + int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture), + double.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture), + m.Groups[4].Value)); + } + } + + return result; + } + + [Fact] + public void Anchor_isNullByDefault_andHoldsWhatWasSet() + { + Assert.Null(new Preformatted("x").Anchor); + Assert.Equal("code-1", new Preformatted("x") { Anchor = "code-1" }.Anchor); + var all = "AZaz09._-:" + new string('k', 117); + Assert.Equal(all, new Preformatted("x") { Anchor = all }.Anchor); + } + + [Fact] + public void BlockAtTheTopOfTheDocument_isANamedDestinationAtTheTopOfTheContentBox() + { + using var doc = NewDocument(); + doc.Add(new Preformatted("a\n\tb") { Anchor = "block" }); + + var dests = Dests(Save(doc)); + + Assert.Equal(["block"], dests.Keys); + Assert.Equal(new Dest(0, 0, TopOfPage), dests["block"]); + } + + [Fact] + public void BlockAfterAFillerLine_isBelowThatLine() + { + using var doc = NewDocument(); + doc.Add(new Paragraph("filler", Body)); + doc.Add(new Preformatted("target") { Anchor = "target" }); + + var dest = Dests(Save(doc))["target"]; + + Assert.Equal(0, dest.Page); + Assert.Equal(TopOfPage - Body.EffectiveLeading, dest.Top, 4); + } + + [Fact] + public void BlockWithATopMargin_isAnchoredBelowTheMargin() + { + using var doc = NewDocument(); + doc.Add(new Preformatted("target") { Margins = new EdgeInsets(7, 0, 0, 0), Anchor = "target" }); + + var dest = Dests(Save(doc))["target"]; + + Assert.Equal(TopOfPage - 7, dest.Top, 4); + } + + [Fact] + public void BlockThatSplits_isAnchoredOnceOnThePageOfItsFirstLine() + { + // Three lines of filler leave 18 lines on page 0; 50 lines run on to a third page. + const int Filler = 3; + static Document Build() + { + var doc = NewDocument(); + doc.Add(new Preformatted(Lines(Filler))); + doc.Add(new Preformatted(Lines(50)) { Anchor = "long" }); + return doc; + } + + using (var measured = Build()) + { + var renderer = measured.CreateRenderer(); + renderer.RunLayout(); + var reported = renderer.DrawPlan!.Placements.Where(p => p.Anchor == "long").ToList(); + Assert.Equal(0, Assert.Single(reported).PageIndex); + Assert.Equal(Margins.Top + (Filler * Leading), reported[0].Y, 4); + } + + using var doc = Build(); + var pdf = Save(doc); + using var reader = PdfReader.Open(pdf); + Assert.Equal(3, reader.PageCount); + var dests = Dests(pdf); + Assert.Equal(["long"], dests.Keys); + Assert.Equal(new Dest(0, 0, TopOfPage - (Filler * Leading)), dests["long"]); + } + + [Fact] + public void BlockAnchor_isReportedUnderTheElement_soAPlanTargetFindsIt() + { + // A page reference resolves a target by the element it was given, so a report keyed by + // anything else, the renderer for one, would leave the element without a page. + var block = new Preformatted(Lines(50)) { Anchor = "long" }; + using var doc = NewDocument(); + doc.Add(new Preformatted(Lines(3))); + doc.Add(block); + + var renderer = doc.CreateRenderer(); + renderer.RunLayout(); + + var reported = Assert.Single(renderer.DrawPlan!.Placements, p => p.Anchor == "long"); + Assert.Same(block, reported.Key); + Assert.True(renderer.DrawPlan.TryGetTarget(block, out var page, out var y)); + Assert.Equal(0, page); + Assert.Equal(Margins.Top + (3 * Leading), y, 4); + } + + [Fact] + public void LabelledPageBreak_followedOnlyByABlock_saves() + { + using var doc = NewDocument(); + doc.Add(new Paragraph("front", Body)); + doc.Add(new PageBreak { PageLabel = new PageLabelRange(PdfPageLabelStyle.LowerRoman) }); + doc.Add(new Preformatted("code") { Anchor = "code" }); + + var pdf = Save(doc); + + Assert.Equal(new Dest(1, 0, TopOfPage), Dests(pdf)["code"]); + } + + [Fact] + public void BlockThatStartsOnALaterPage_isAnchoredOnThatPage() + { + using var doc = NewDocument(); + doc.Add(new Preformatted(Lines(21))); + doc.Add(new Preformatted("second") { Anchor = "second" }); + + var dest = Dests(Save(doc))["second"]; + + Assert.Equal(new Dest(1, 0, TopOfPage), dest); + } + + [Fact] + public void BlockWithBreakBefore_isAnchoredAtTheTopOfTheNewPage() + { + using var doc = NewDocument(); + doc.Add(new Paragraph("front", Body)); + doc.Add(new Preformatted("code") { BreakBefore = PageBreakMode.Page, Anchor = "code" }); + + Assert.Equal(new Dest(1, 0, TopOfPage), Dests(Save(doc))["code"]); + } + + [Fact] + public void Anchor_refusesTheNamesAParagraphRefuses_withTheSameTypeAndMessage() + { + foreach (var bad in new[] { "", "a b", "é", "a/b", "a#b", "a(b", new string('x', 128), "\uD800" }) + { + var expected = Assert.Throws(() => new Paragraph("x", Body) { Anchor = bad }); + var actual = Assert.Throws(() => new Preformatted("x") { Anchor = bad }); + Assert.Equal(expected.GetType(), actual.GetType()); + Assert.Equal(expected.ParamName, actual.ParamName); + Assert.Equal(expected.Message, actual.Message); + } + } + + [Fact] + public void RepeatedAnchor_acrossAParagraphAndABlock_isRefusedBeforeLayout_namingBoth() + { + using var doc = NewDocument(); + doc.Add(new Paragraph("a", Body) { Anchor = "same" }); + doc.Add(new Preformatted("b") { Anchor = "same" }); + + var first = Assert.Throws(() => Save(doc)); + var second = Assert.Throws(() => Save(doc)); + + Assert.Contains("\"same\"", first.Message, StringComparison.Ordinal); + Assert.Contains("Paragraph 0 and Preformatted 1", first.Message, StringComparison.Ordinal); + Assert.Equal(first.Message, second.Message); + Assert.DoesNotContain("cannot be saved again", second.Message, StringComparison.Ordinal); + } + + [Fact] + public void RepeatedAnchor_acrossABlockAndAList_isRefusedBeforeLayout() + { + using var doc = NewDocument(); + doc.Add(new Preformatted("b") { Anchor = "same" }); + var list = new ListElement(); + list.Add(new ListItem("x", Body) { Anchor = "same" }); + doc.Add(list); + + var ex = Assert.Throws(() => Save(doc)); + + Assert.Contains("Preformatted 0 and List 1 (item 0)", ex.Message, StringComparison.Ordinal); + } + + [Fact] + public void SameBlockAddedTwice_holdsItsAnchorTwice() + { + using var doc = NewDocument(); + var block = new Preformatted("a") { Anchor = "once" }; + doc.Add(block); + doc.Add(block); + + var ex = Assert.Throws(() => Save(doc)); + Assert.Contains("Preformatted 0 and Preformatted 1", ex.Message, StringComparison.Ordinal); + } + + [Fact] + public void BlockAnchor_pdfinfoResolvesTheNameToThePageAndTopWeComputed() + { + using var doc = NewDocument(); + doc.Add(new Preformatted(Lines(21))); + doc.Add(new Preformatted(Lines(2)) { Anchor = "listing" }); + var path = Path.Combine(Path.GetTempPath(), "vellum_preanchor_" + Guid.NewGuid().ToString("N") + ".pdf"); + try + { + File.WriteAllBytes(path, Save(doc)); + var only = Assert.Single(PdfinfoDests(path)); + Assert.Equal(2, only.Page); + Assert.Equal(TopOfPage, only.Top, 4); + Assert.Equal("listing", only.Name); + } + finally + { + try { File.Delete(path); } + catch (IOException) { /* best-effort cleanup */ } + } + } +}