Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,27 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
before it, and with areas on pages it does not end up on. A `Full` result is still drawn after
the last `Layout` call on that instance; see `IRenderer.Layout`.

- **`{chapter}` in a running band (#603).** `RunningBand.ChapterToken` turns on a `{chapter}`
token that prints the title of the chapter the page is in, so a header can read "Hoofdstuk 2:
Ontwikkeling" on the pages of that chapter. It is `false` by default: a template that holds
`{chapter}` without it prints that text as it always did, and a document that does not set the
property saves to the same bytes.
- A chapter is a level-0 `Heading`. A page shows the first one whose first line is on the page,
else the last one drawn on an earlier page, else no text where the token stands; the rest of
the template is drawn as written. A heading that splits over a page break counts on the page
it starts on. A page where the next chapter starts partway down shows that next chapter, and
the blank page a recto break inserts has no band, so it shows no title. The title is the
heading's `BookmarkTitle` when set, otherwise its text. A tab, line break, form feed or other
control white space in it is drawn as a space.
- The save refuses a title with an unpaired surrogate when the band's font is embedded
(`ArgumentException`), and a template that repeats `{chapter}` until the text passes
`int.MaxValue` characters (`InvalidOperationException`).
- Headings of other levels and anything a custom `IRenderer` draws start no chapter.
- The save follows chapters only when a band sets the property and holds the token, and only in
the drawing pass, so the page count and the number of layout runs do not change. A title wider
than the band is cut and reported as `BandTruncated`, like any band text.
- `RunningBand.Resolve(int, int)` knows no headings and leaves `{chapter}` as given.

- **`Document.MirrorMargins` for double-sided print (#608).** With it set, `Margins.Left` is the
inside margin and `Margins.Right` the outside one. The inside margin is on the left of a
right-hand page (an odd physical page number, page 1 first) and on the right of a left-hand
Expand Down
16 changes: 11 additions & 5 deletions src/VellumPdf.Layout/Document.cs
Original file line number Diff line number Diff line change
Expand Up @@ -502,28 +502,33 @@ public byte[]? DocumentId
/// <summary>
/// Optional header band drawn at the top of every page.
/// Set via <see cref="SetHeader"/> for a fluent API.
/// Supports {page} and {pages} tokens.
/// Supports {page} and {pages} tokens, and {chapter} when
/// <see cref="RunningBand.ChapterToken"/> is set.
/// </summary>
/// <remarks>
/// A band whose <see cref="RunningBand.Template"/> is null is refused when the band is drawn,
/// not when it is assigned. The band's height and style carry
/// refusals of their own; see <see cref="RunningBand.Height"/>,
/// <see cref="TextStyle.FontSize"/>, <see cref="TextStyle.Leading"/> and
/// <see cref="TextStyle.FontRef"/>.
/// <see cref="TextStyle.FontRef"/>. The chapter title that <c>{chapter}</c> prints comes from
/// the document's level-0 headings; see <see cref="RunningBand.ChapterToken"/>.
/// </remarks>
/// <exception cref="ArgumentException">
/// Raised from <see cref="Save(System.IO.Stream)"/> and the other save overloads, when the
/// band's height leaves the content area no positive size, or when <c>Height</c> is null and
/// its style's size or leading does; see <see cref="RunningBand.Height"/> and
/// <see cref="RunningBand.Style"/>. It is also raised when the band measures text that holds an
/// unpaired surrogate in an embedded font, which can include part of the template it then does
/// not draw; see <see cref="TextStyle.FontRef"/>.
/// not draw and the chapter title <see cref="RunningBand.ChapterToken"/> prints; see
/// <see cref="TextStyle.FontRef"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Raised from <see cref="Save(System.IO.Stream)"/> and the other save overloads, when the
/// band's height, or its style's size or leading, is refused; see
/// <see cref="RunningBand.Height"/>, <see cref="TextStyle.FontSize"/> and
/// <see cref="TextStyle.Leading"/>.
/// <see cref="TextStyle.Leading"/>. It is also raised when a template that repeats
/// <c>{chapter}</c> resolves to more than <see cref="int.MaxValue"/> characters; see
/// <see cref="RunningBand.ChapterToken"/>.
/// </exception>
/// <exception cref="IndexOutOfRangeException">
/// Raised from <see cref="Save(System.IO.Stream)"/> and the other save overloads, when the
Expand All @@ -535,7 +540,8 @@ public byte[]? DocumentId
/// <summary>
/// Optional footer band drawn at the bottom of every page.
/// Set via <see cref="SetFooter"/> for a fluent API.
/// Supports {page} and {pages} tokens.
/// Supports {page} and {pages} tokens, and {chapter} when
/// <see cref="RunningBand.ChapterToken"/> is set.
/// </summary>
/// <inheritdoc cref="Header" path="/remarks"/>
/// <inheritdoc cref="Header" path="/exception"/>
Expand Down
66 changes: 60 additions & 6 deletions src/VellumPdf.Layout/Elements/BandTemplate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,19 @@ internal enum BandToken

/// <summary><c>{pages}</c>: the total page count.</summary>
Pages = 1,

/// <summary>
/// <c>{chapter}</c>: the title of the chapter the page is in. Recognised only in a template
/// compiled with the token on, which <see cref="RunningBand.ChapterToken"/> asks for.
/// </summary>
Chapter = 2,
}

/// <summary>
/// The one table of tokens the save substitutes. A new token is a new <see cref="BandToken"/>
/// member, a row here, a value in <see cref="BandText.Reset"/> and a pass in
/// <c>RunningBand.Resolve</c>, which scans the template on its own.
/// <c>RunningBand.Resolve</c>, which scans the template on its own. A token that a caller must ask
/// for, as it must for <c>{chapter}</c>, also needs a test in <see cref="BandTemplate.Compile"/>.
/// </summary>
internal static class BandTokens
{
Expand All @@ -31,6 +38,7 @@ private static readonly (string Text, BandToken Kind)[] Table =
[
("{page}", BandToken.Page),
("{pages}", BandToken.Pages),
("{chapter}", BandToken.Chapter),
];

internal static int Count => Table.Length;
Expand Down Expand Up @@ -77,11 +85,16 @@ private BandTemplate(string source, int[] starts, int[] lengths, sbyte[] kinds,
TokenCounts = counts;
}

/// <param name="template">The template text.</param>
/// <param name="chapterToken">
/// Whether <c>{chapter}</c> is a token. When false the text stays literal, as it always has, so
/// a template that holds it is scanned exactly as before the token existed.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="template"/> is <see langword="null"/>. <c>ParamName</c> is <c>template</c>,
/// as for <see cref="RunningBand.Resolve"/>.
/// </exception>
internal static BandTemplate Compile(string template)
internal static BandTemplate Compile(string template, bool chapterToken = false)
{
if (template is null) throw new ArgumentNullException("template", "The band's template is null.");

Expand All @@ -101,6 +114,7 @@ internal static BandTemplate Compile(string template)
var matched = false;
foreach (var (text, kind) in BandTokens.Entries)
{
if (kind == BandToken.Chapter && !chapterToken) continue;
if (!template.AsSpan(brace).StartsWith(text, StringComparison.Ordinal)) continue;

if (brace > runStart)
Expand Down Expand Up @@ -167,24 +181,64 @@ internal sealed class BandText
/// What <c>{page}</c> prints, or null for the decimal <paramref name="pageNumber"/>. The text is
/// copied as it is and never scanned for a token.
/// </param>
internal void Reset(int pageNumber, int totalPages, string? pageLabel = null)
/// <param name="chapter">
/// What <c>{chapter}</c> prints, or null for no text. Copied as it is and never scanned for a
/// token. The caller has already read its control white space as spaces; see
/// <see cref="ControlSpacesToSpaces"/>.
/// </param>
internal void Reset(int pageNumber, int totalPages, string? pageLabel = null, string? chapter = null)
{
_values[(int)BandToken.Page] =
pageLabel ?? pageNumber.ToString(System.Globalization.CultureInfo.InvariantCulture);
_values[(int)BandToken.Pages] = totalPages.ToString(System.Globalization.CultureInfo.InvariantCulture);
_values[(int)BandToken.Chapter] = chapter ?? "";

long length = Template.LiteralLength;
for (var k = 0; k < _values.Length; k++)
length += (long)Template.TokenCounts[k] * _values[k].Length;
// Defensive: a string over 1,073,741,823 characters throws OutOfMemoryException first, a
// token is at least 6 characters and a number is at most 11, so this cannot overflow.
Length = checked((int)length);
// The literal text and the page and count values cannot overflow int: a template over
// 1,073,741,823 characters throws OutOfMemoryException first and a token is at least 6
// characters. A chapter title can: a long one repeated by many {chapter} tokens is a text
// no band could draw, and no string could hold.
if (length > int.MaxValue)
throw new InvalidOperationException(
"The band's text is too long: its template repeats {chapter} " +
$"{Template.TokenCounts[(int)BandToken.Chapter]} times and the chapter title is " +
$"{_values[(int)BandToken.Chapter].Length} characters long.");
Length = (int)length;

_produced = 0;
_segment = 0;
_offset = 0;
}

/// <summary>
/// Returns <paramref name="text"/> with every tab, line break, form feed and other control
/// white space replaced by U+0020, or the same instance when it holds none. A band draws one
/// line, and no font draws these characters, so left as written they reach glyph lookup. The
/// Unicode space separators, the no-break spaces among them, are left as they are, because a
/// font draws them.
/// </summary>
internal static string ControlSpacesToSpaces(string text)
{
var at = -1;
for (var i = 0; i < text.Length; i++)
{
if (IsControlSpace(text[i])) { at = i; break; }
}
if (at < 0) return text;

return string.Create(text.Length, (text, at), static (span, state) =>
{
state.text.AsSpan().CopyTo(span);
for (var i = state.at; i < span.Length; i++)
if (IsControlSpace(span[i])) span[i] = ' ';
});
}

private static bool IsControlSpace(char c) =>
char.IsWhiteSpace(c) && char.GetUnicodeCategory(c) != System.Globalization.UnicodeCategory.SpaceSeparator;

internal char this[int index]
{
get
Expand Down
22 changes: 20 additions & 2 deletions src/VellumPdf.Layout/Elements/Heading.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ public sealed class Heading
/// Raised from <see cref="Document.Save(System.IO.Stream)"/> and the other save overloads, not
/// from this property, when the text holds an unpaired surrogate and is measured in an embedded
/// font; see <see cref="TextStyle.FontRef"/>. A pair split between two runs that share one
/// style instance is joined and does not throw.
/// style instance is joined and does not throw. It is also raised, whatever font the heading is
/// set in, when this is the title of a level-0 heading that a running band prints through
/// <see cref="RunningBand.ChapterToken"/> in an embedded font.
/// </exception>
public string Text { get; }

Expand Down Expand Up @@ -94,7 +96,23 @@ public sealed class Heading
/// <summary>
/// Override the bookmark title. When null the heading text is used.
/// </summary>
/// <remarks>Null means use <see cref="Text"/>. Empty is an empty bookmark title.</remarks>
/// <remarks>
/// Null means use <see cref="Text"/>. Empty is an empty bookmark title.
/// <para><b>An unpaired surrogate is refused where a band prints the title.</b> When
/// the heading is level 0 and a band sets <see cref="RunningBand.ChapterToken"/> and holds
/// <c>{chapter}</c> in an embedded font, the save throws <see cref="ArgumentException"/>,
/// whatever font the heading is set in. A document without such a band saves it. The same
/// band throws <see cref="InvalidOperationException"/> when a template repeats
/// <c>{chapter}</c> so often that the titles it prints add up to more than
/// <see cref="int.MaxValue"/> characters; see <see cref="RunningBand.ChapterToken"/>.</para>
/// </remarks>
/// <exception cref="ArgumentException">
/// Raised from <see cref="Document.Save(System.IO.Stream)"/> and the other save overloads, not
/// from this property, as described above.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Raised from the save, not from this property, as described above.
/// </exception>
public string? BookmarkTitle { get; init; }

/// <summary>Whether the heading's bookmark is shown open (the default) or closed in the outline.</summary>
Expand Down
Loading
Loading